Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ad524b108 | ||
|
|
9bbd937cf2 | ||
|
|
51a0e81a09 | ||
|
|
c8af1b1338 | ||
|
|
920411fb4e | ||
|
|
899771edab | ||
|
|
665ecafe8c |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.9.1",
|
||||
"version": "2.9.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
|
||||
Generated
-962
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { cacheLayer } from "./CacheLayer";
|
||||
|
||||
describe("CacheLayer", () => {
|
||||
let mockDB: any;
|
||||
let mockObjectStore: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
cacheLayer.clear();
|
||||
|
||||
mockObjectStore = {
|
||||
put: vi.fn(),
|
||||
get: vi.fn(() => ({ onsuccess: null })),
|
||||
delete: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
};
|
||||
|
||||
mockDB = {
|
||||
transaction: vi.fn(() => ({
|
||||
objectStore: () => mockObjectStore,
|
||||
})),
|
||||
objectStoreNames: {
|
||||
contains: vi.fn(() => true),
|
||||
},
|
||||
};
|
||||
|
||||
// Mock IndexedDB
|
||||
const mockRequest: any = {
|
||||
onsuccess: null,
|
||||
onerror: null,
|
||||
onupgradeneeded: null,
|
||||
result: mockDB,
|
||||
};
|
||||
|
||||
global.indexedDB = {
|
||||
open: vi.fn(() => mockRequest),
|
||||
} as any;
|
||||
|
||||
// Stub global performance for WsClient logs if needed, but here we just need window
|
||||
vi.stubGlobal("window", {});
|
||||
});
|
||||
|
||||
it("should initialize and open IndexedDB", async () => {
|
||||
const initPromise = cacheLayer.init();
|
||||
const request = (global.indexedDB.open as any).mock.results[0].value;
|
||||
request.onsuccess();
|
||||
await initPromise;
|
||||
|
||||
expect(global.indexedDB.open).toHaveBeenCalledWith("worldwideview-cache", 1);
|
||||
});
|
||||
|
||||
it("should set and get items from memory cache", () => {
|
||||
const entities = [{ id: "1" }];
|
||||
cacheLayer.set("plugin-a", entities as any, 1000);
|
||||
|
||||
expect(cacheLayer.get("plugin-a")).toEqual(entities);
|
||||
});
|
||||
|
||||
it("should respect TTL for memory cache", () => {
|
||||
const entities = [{ id: "1" }];
|
||||
cacheLayer.set("plugin-a", entities as any, 1000);
|
||||
|
||||
vi.advanceTimersByTime(1001);
|
||||
expect(cacheLayer.get("plugin-a")).toBeNull();
|
||||
});
|
||||
|
||||
it("should persist to IndexedDB when set is called", async () => {
|
||||
// Initialize DB first
|
||||
const initPromise = cacheLayer.init();
|
||||
const request = (global.indexedDB.open as any).mock.results[0].value;
|
||||
request.onsuccess();
|
||||
await initPromise;
|
||||
|
||||
const entities = [{ id: "1" }];
|
||||
cacheLayer.set("plugin-a", entities as any, 1000);
|
||||
|
||||
expect(mockDB.transaction).toHaveBeenCalledWith("entities", "readwrite");
|
||||
expect(mockObjectStore.put).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entities }),
|
||||
"plugin-a"
|
||||
);
|
||||
});
|
||||
|
||||
it("should fetch from persistent storage if memory miss", async () => {
|
||||
// Initialize DB
|
||||
const initPromise = cacheLayer.init();
|
||||
const request = (global.indexedDB.open as any).mock.results[0].value;
|
||||
request.onsuccess();
|
||||
await initPromise;
|
||||
|
||||
const entities = [{ id: "persistent" }];
|
||||
const getRequest: any = { onsuccess: null, result: { entities, timestamp: Date.now(), ttl: 10000 } };
|
||||
mockObjectStore.get.mockReturnValue(getRequest);
|
||||
|
||||
const fetchPromise = cacheLayer.getFromPersistent("plugin-a");
|
||||
getRequest.onsuccess();
|
||||
const result = await fetchPromise;
|
||||
|
||||
expect(result).toEqual(entities);
|
||||
// Should also populate memory cache
|
||||
expect(cacheLayer.get("plugin-a")).toEqual(entities);
|
||||
});
|
||||
|
||||
it("should handle IndexedDB initialization failure gracefully", async () => {
|
||||
const mockRequest: any = { onerror: null };
|
||||
global.indexedDB.open = vi.fn(() => mockRequest);
|
||||
|
||||
const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const initPromise = cacheLayer.init();
|
||||
mockRequest.onerror();
|
||||
await initPromise;
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("IndexedDB unavailable")
|
||||
);
|
||||
});
|
||||
|
||||
it("should return null from getFromPersistent if entry is expired", async () => {
|
||||
const initPromise = cacheLayer.init();
|
||||
const request = (global.indexedDB.open as any).mock.results[0].value;
|
||||
request.onsuccess();
|
||||
await initPromise;
|
||||
|
||||
const entities = [{ id: "expired" }];
|
||||
const getRequest: any = { onsuccess: null, result: { entities, timestamp: Date.now() - 2000, ttl: 1000 } };
|
||||
mockObjectStore.get.mockReturnValue(getRequest);
|
||||
|
||||
const fetchPromise = cacheLayer.getFromPersistent("plugin-a");
|
||||
getRequest.onsuccess();
|
||||
const result = await fetchPromise;
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should invalidate both memory and persistent cache", async () => {
|
||||
const initPromise = cacheLayer.init();
|
||||
const request = (global.indexedDB.open as any).mock.results[0].value;
|
||||
request.onsuccess();
|
||||
await initPromise;
|
||||
|
||||
cacheLayer.set("plugin-a", [{ id: "1" }] as any);
|
||||
cacheLayer.invalidate("plugin-a");
|
||||
|
||||
expect(cacheLayer.get("plugin-a")).toBeNull();
|
||||
expect(mockObjectStore.delete).toHaveBeenCalledWith("plugin-a");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { dataBus } from "./DataBus";
|
||||
|
||||
describe("DataBus", () => {
|
||||
beforeEach(() => {
|
||||
dataBus.removeAllListeners();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should register and emit events", () => {
|
||||
const handler = vi.fn();
|
||||
dataBus.on("dataUpdated" as any, handler);
|
||||
|
||||
const payload = { pluginId: "p1", entities: [] };
|
||||
dataBus.emit("dataUpdated" as any, payload);
|
||||
|
||||
expect(handler).toHaveBeenCalledWith(payload);
|
||||
});
|
||||
|
||||
it("should unsubscribe via return function", () => {
|
||||
const handler = vi.fn();
|
||||
const unsub = dataBus.on("dataUpdated" as any, handler);
|
||||
|
||||
unsub();
|
||||
dataBus.emit("dataUpdated" as any, {});
|
||||
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should unsubscribe via off()", () => {
|
||||
const handler = vi.fn();
|
||||
dataBus.on("dataUpdated" as any, handler);
|
||||
|
||||
dataBus.off("dataUpdated" as any, handler);
|
||||
dataBus.emit("dataUpdated" as any, {});
|
||||
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not crash if a handler throws", () => {
|
||||
const brokenHandler = () => { throw new Error("Boom"); };
|
||||
const goodHandler = vi.fn();
|
||||
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
dataBus.on("dataUpdated" as any, brokenHandler);
|
||||
dataBus.on("dataUpdated" as any, goodHandler);
|
||||
|
||||
dataBus.emit("dataUpdated" as any, {});
|
||||
|
||||
expect(goodHandler).toHaveBeenCalled();
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('[DataBus] Error in handler for "dataUpdated"'),
|
||||
expect.any(Error)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { fetchLocalEngineManifest, localEngineHasPlugin, resetManifestCache } from "./engineManifest";
|
||||
import { resolveEngineUrl } from "./resolveEngineUrl";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
|
||||
// Mock PluginManager
|
||||
vi.mock("@/core/plugins/PluginManager", () => ({
|
||||
pluginManager: {
|
||||
getPlugin: vi.fn(),
|
||||
getManifest: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("EngineManifest", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetManifestCache();
|
||||
global.fetch = vi.fn() as any;
|
||||
});
|
||||
|
||||
it("should fetch manifest from local engine and cache it", async () => {
|
||||
(global.fetch as any).mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ plugins: ["plugin-a", "plugin-b"] }),
|
||||
});
|
||||
|
||||
const plugins = await fetchLocalEngineManifest();
|
||||
expect(plugins).toEqual(["plugin-a", "plugin-b"]);
|
||||
expect(localEngineHasPlugin("plugin-a")).toBe(true);
|
||||
expect(localEngineHasPlugin("plugin-c")).toBe(false);
|
||||
|
||||
// Second call should used cache
|
||||
await fetchLocalEngineManifest();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should return null and cache failure if local engine is missing", async () => {
|
||||
(global.fetch as any).mockRejectedValue(new Error("Connection refused"));
|
||||
|
||||
const plugins = await fetchLocalEngineManifest();
|
||||
expect(plugins).toBeNull();
|
||||
|
||||
// Should not retry fetch
|
||||
await fetchLocalEngineManifest();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEngineUrl", () => {
|
||||
beforeEach(() => {
|
||||
resetManifestCache();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should prioritize local engine if plugin is found there", async () => {
|
||||
// Setup local manifest
|
||||
(global.fetch as any).mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ plugins: ["plugin-local"] }),
|
||||
});
|
||||
await fetchLocalEngineManifest();
|
||||
|
||||
const url = resolveEngineUrl("plugin-local");
|
||||
expect(url).toContain("localhost:5000/stream");
|
||||
});
|
||||
|
||||
it("should fall back to plugin's custom streamUrl if not local", () => {
|
||||
(pluginManager.getPlugin as any).mockReturnValue({
|
||||
plugin: {
|
||||
getServerConfig: () => ({ streamUrl: "ws://custom-engine/stream" })
|
||||
}
|
||||
});
|
||||
|
||||
const url = resolveEngineUrl("plugin-custom");
|
||||
expect(url).toBe("ws://custom-engine/stream");
|
||||
});
|
||||
|
||||
it("should fall back to manifest streamUrl if provided", () => {
|
||||
(pluginManager.getPlugin as any).mockReturnValue(undefined);
|
||||
(pluginManager.getManifest as any).mockReturnValue({
|
||||
dataSource: { streamUrl: "ws://manifest-engine/stream" }
|
||||
});
|
||||
|
||||
const url = resolveEngineUrl("plugin-manifest");
|
||||
expect(url).toBe("ws://manifest-engine/stream");
|
||||
});
|
||||
|
||||
it("should use default cloud engine as last resort", () => {
|
||||
(pluginManager.getPlugin as any).mockReturnValue(undefined);
|
||||
(pluginManager.getManifest as any).mockReturnValue(undefined);
|
||||
|
||||
const url = resolveEngineUrl("unknown-plugin");
|
||||
expect(url).toContain("worldwideview.dev/stream");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { pollingManager } from "./PollingManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
const { mockState, shared } = vi.hoisted(() => ({
|
||||
mockState: {
|
||||
dataConfig: {
|
||||
pollingIntervals: {},
|
||||
},
|
||||
},
|
||||
shared: {
|
||||
storeSubscriber: null as any
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock("@/core/state/store", () => ({
|
||||
useStore: {
|
||||
getState: vi.fn(() => mockState),
|
||||
subscribe: vi.fn((sub) => {
|
||||
shared.storeSubscriber = sub;
|
||||
return () => {};
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("PollingManager", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
// Clear private tasks map
|
||||
(pollingManager as any).tasks.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("should register a polling task", () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
|
||||
const task = (pollingManager as any).tasks.get("test-plugin");
|
||||
expect(task).toBeDefined();
|
||||
expect(task.intervalMs).toBe(1000);
|
||||
});
|
||||
|
||||
it("should run the callback immediately on start", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should poll at the specified interval", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(callback).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("should not poll if paused", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
pollingManager.pause("test-plugin");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(callback).toHaveBeenCalledTimes(1); // Only the initial run
|
||||
});
|
||||
|
||||
it("should resume polling", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
pollingManager.pause("test-plugin");
|
||||
pollingManager.resume("test-plugin");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should stop polling", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
pollingManager.stop("test-plugin");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should update interval when store changes", async () => {
|
||||
const callback = vi.fn().mockResolvedValue(undefined);
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
pollingManager.start("test-plugin");
|
||||
|
||||
// Simulate store update
|
||||
const newState = {
|
||||
dataConfig: {
|
||||
pollingIntervals: {
|
||||
"test-plugin": 500,
|
||||
},
|
||||
},
|
||||
};
|
||||
shared.storeSubscriber(newState, mockState);
|
||||
|
||||
expect((pollingManager as any).tasks.get("test-plugin").intervalMs).toBe(500);
|
||||
|
||||
// Should now poll every 500ms
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(callback).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("should support backoff on error", async () => {
|
||||
const callback = vi.fn().mockRejectedValue(new Error("Fail"));
|
||||
pollingManager.register("test-plugin", 1000, callback);
|
||||
|
||||
// We need to trigger the error to increment errorCount
|
||||
await pollingManager.start("test-plugin");
|
||||
|
||||
// Now that it has failed once, the NEXT interval will be backed off
|
||||
// However, start() schedules the interval immediately based on CURRENT errorCount (0)
|
||||
// So we need to stop and start again to see the backoff, or wait for the next cycle.
|
||||
|
||||
// Let's just verify errorCount incremented
|
||||
const task = (pollingManager as any).tasks.get("test-plugin");
|
||||
expect(task.errorCount).toBe(1);
|
||||
});
|
||||
|
||||
it("should stop all and unregister", () => {
|
||||
pollingManager.register("p1", 1000, async () => {});
|
||||
pollingManager.register("p2", 1000, async () => {});
|
||||
pollingManager.start("p1");
|
||||
pollingManager.start("p2");
|
||||
|
||||
pollingManager.stopAll();
|
||||
expect((pollingManager as any).tasks.get("p1").timerId).toBeNull();
|
||||
expect((pollingManager as any).tasks.get("p2").timerId).toBeNull();
|
||||
|
||||
pollingManager.unregister("p1");
|
||||
expect((pollingManager as any).tasks.has("p1")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { wsClient } from "./WsClient";
|
||||
import { dataBus } from "./DataBus";
|
||||
import { pluginManager } from "../plugins/PluginManager";
|
||||
|
||||
// Mock DataBus
|
||||
vi.mock("./DataBus", () => ({
|
||||
dataBus: {
|
||||
emit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock PluginManager
|
||||
vi.mock("../plugins/PluginManager", () => ({
|
||||
pluginManager: {
|
||||
getPlugin: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock Store
|
||||
vi.mock("../state/store", () => ({
|
||||
useStore: {
|
||||
getState: vi.fn(() => ({
|
||||
entitiesByPlugin: {},
|
||||
setLayerLoading: vi.fn(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("WsClient", () => {
|
||||
let mockWs: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock WebSocket global
|
||||
mockWs = {
|
||||
send: vi.fn(),
|
||||
close: vi.fn(),
|
||||
readyState: 0, // CONNECTING
|
||||
};
|
||||
|
||||
global.WebSocket = vi.fn().mockImplementation(function() {
|
||||
return mockWs;
|
||||
}) as any;
|
||||
Object.assign(global.WebSocket, {
|
||||
CONNECTING: 0,
|
||||
OPEN: 1,
|
||||
CLOSING: 2,
|
||||
CLOSED: 3,
|
||||
});
|
||||
|
||||
// Clear singleton state
|
||||
(wsClient as any).engines.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("should create a new WebSocket connection when subscribing to a new engine", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
|
||||
expect(global.WebSocket).toHaveBeenCalledWith("ws://engine-1/stream");
|
||||
});
|
||||
|
||||
it("should reuse an existing connection for the same engine URL", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
wsClient.subscribe("plugin-b", "ws://engine-1/stream");
|
||||
|
||||
expect(global.WebSocket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should send a subscribe action once the socket is open", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
|
||||
// Simulate open
|
||||
mockWs.readyState = 1; // OPEN
|
||||
mockWs.onopen();
|
||||
|
||||
expect(mockWs.send).toHaveBeenCalledWith(
|
||||
JSON.stringify({ action: "subscribe", pluginId: "plugin-a" })
|
||||
);
|
||||
});
|
||||
|
||||
it("should attempt to reconnect after 5s if the connection is closed while subscriptions exist", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
mockWs.onclose();
|
||||
|
||||
expect(global.WebSocket).toHaveBeenCalledTimes(1); // Initial
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(global.WebSocket).toHaveBeenCalledTimes(2); // Reconnect
|
||||
});
|
||||
|
||||
it("should close the connection after 30s if all plugins unsubscribe", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
wsClient.unsubscribe("plugin-a", "ws://engine-1/stream");
|
||||
|
||||
// Should not close immediately (grace period)
|
||||
expect(mockWs.close).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(30000);
|
||||
|
||||
expect(mockWs.close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle data messages and emit dataUpdated via DataBus", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
|
||||
const mockEntities = [{ id: "1", type: "point", lat: 10, lng: 20 }];
|
||||
const message = {
|
||||
type: "data",
|
||||
pluginId: "plugin-a",
|
||||
payload: mockEntities
|
||||
};
|
||||
|
||||
mockWs.onmessage({ data: JSON.stringify(message) });
|
||||
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("dataUpdated", expect.objectContaining({
|
||||
pluginId: "plugin-a",
|
||||
entities: expect.arrayContaining([
|
||||
expect.objectContaining({ id: "1" })
|
||||
])
|
||||
}));
|
||||
});
|
||||
|
||||
it("should use plugin's custom mapWebsocketPayload if available", () => {
|
||||
const mockPlugin = {
|
||||
mapWebsocketPayload: vi.fn((payload) => payload.map((e: any) => ({ ...e, custom: true })))
|
||||
};
|
||||
(pluginManager.getPlugin as any).mockReturnValue({ plugin: mockPlugin });
|
||||
|
||||
wsClient.subscribe("plugin-custom", "ws://engine-1/stream");
|
||||
|
||||
const mockEntities = [{ id: "1" }];
|
||||
const message = {
|
||||
type: "data",
|
||||
pluginId: "plugin-custom",
|
||||
payload: mockEntities
|
||||
};
|
||||
|
||||
mockWs.onmessage({ data: JSON.stringify(message) });
|
||||
|
||||
expect(mockPlugin.mapWebsocketPayload).toHaveBeenCalled();
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("dataUpdated", expect.objectContaining({
|
||||
entities: [expect.objectContaining({ custom: true })]
|
||||
}));
|
||||
});
|
||||
|
||||
it("should cancel cleanup timer if a new subscription is added during grace period", () => {
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
wsClient.unsubscribe("plugin-a", "ws://engine-1/stream");
|
||||
|
||||
// Cleanup timer is running
|
||||
wsClient.subscribe("plugin-b", "ws://engine-1/stream");
|
||||
|
||||
vi.advanceTimersByTime(30000);
|
||||
expect(mockWs.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should print connections to console", () => {
|
||||
const groupSpy = vi.spyOn(console, "groupCollapsed").mockImplementation(() => {});
|
||||
const tableSpy = vi.spyOn(console, "table").mockImplementation(() => {});
|
||||
wsClient.subscribe("plugin-a", "ws://engine-1/stream");
|
||||
wsClient.printConnections();
|
||||
expect(groupSpy).toHaveBeenCalled();
|
||||
expect(tableSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { resolveEdition } from "./edition";
|
||||
|
||||
describe("edition", () => {
|
||||
describe("resolveEdition", () => {
|
||||
it("should resolve valid editions", () => {
|
||||
expect(resolveEdition("cloud")).toBe("cloud");
|
||||
expect(resolveEdition("LOCAL")).toBe("local");
|
||||
expect(resolveEdition(" demo ")).toBe("demo");
|
||||
});
|
||||
|
||||
it("should fall back to local for invalid editions", () => {
|
||||
expect(resolveEdition("enterprise")).toBe("local");
|
||||
expect(resolveEdition("")).toBe("local");
|
||||
expect(resolveEdition(undefined)).toBe("local");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { pluginManager } from "./PluginManager";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { pollingManager } from "@/core/data/PollingManager";
|
||||
import { cacheLayer } from "@/core/data/CacheLayer";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { loadPluginFromManifest } from "./loadPluginFromManifest";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@/core/data/DataBus", () => ({
|
||||
dataBus: {
|
||||
emit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/data/PollingManager", () => ({
|
||||
pollingManager: {
|
||||
register: vi.fn(),
|
||||
start: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/data/CacheLayer", () => ({
|
||||
cacheLayer: {
|
||||
init: vi.fn().mockResolvedValue(undefined),
|
||||
get: vi.fn(),
|
||||
getFromPersistent: vi.fn().mockResolvedValue(null),
|
||||
set: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockStore = {
|
||||
dataConfig: {
|
||||
pluginSettings: {},
|
||||
},
|
||||
setLayerLoading: vi.fn(),
|
||||
isPlaybackMode: false,
|
||||
currentTime: new Date(),
|
||||
};
|
||||
|
||||
vi.mock("@/core/state/store", () => ({
|
||||
useStore: {
|
||||
getState: vi.fn(() => mockStore),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./loadPluginFromManifest", () => ({
|
||||
loadPluginFromManifest: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/analytics", () => ({
|
||||
trackEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/data/resolveEngineUrl", () => ({
|
||||
resolveEngineUrl: vi.fn(() => "ws://localhost:5000/stream"),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/data/engineManifest", () => ({
|
||||
fetchLocalEngineManifest: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
|
||||
describe("PluginManager", () => {
|
||||
const mockPlugin = {
|
||||
id: "test-plugin",
|
||||
name: "Test Plugin",
|
||||
initialize: vi.fn().mockResolvedValue(undefined),
|
||||
fetch: vi.fn().mockResolvedValue([]),
|
||||
getPollingInterval: vi.fn(() => 30000),
|
||||
destroy: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockStore.setLayerLoading.mockClear();
|
||||
// Clear private plugins map via any
|
||||
(pluginManager as any).plugins.clear();
|
||||
(pluginManager as any).initialized = false;
|
||||
});
|
||||
|
||||
it("should initialize cacheLayer on init", async () => {
|
||||
await pluginManager.init();
|
||||
expect(cacheLayer.init).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should register a plugin and initialize it", async () => {
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
|
||||
expect(mockPlugin.initialize).toHaveBeenCalled();
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("pluginRegistered", expect.objectContaining({
|
||||
pluginId: "test-plugin",
|
||||
defaultInterval: 30000,
|
||||
}));
|
||||
expect(pollingManager.register).toHaveBeenCalledWith("test-plugin", 30000, expect.any(Function));
|
||||
});
|
||||
|
||||
it("should enable a plugin and start polling", async () => {
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
await pluginManager.enablePlugin("test-plugin");
|
||||
|
||||
expect(useStore.getState().setLayerLoading).toHaveBeenCalledWith("test-plugin", true);
|
||||
expect(pollingManager.start).toHaveBeenCalledWith("test-plugin");
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("layerToggled", { pluginId: "test-plugin", enabled: true });
|
||||
});
|
||||
|
||||
it("should load data from cache when enabling a plugin", async () => {
|
||||
const cachedEntities = [{ id: "1" }];
|
||||
(cacheLayer.get as any).mockReturnValue(cachedEntities);
|
||||
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
await pluginManager.enablePlugin("test-plugin");
|
||||
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("dataUpdated", {
|
||||
pluginId: "test-plugin",
|
||||
entities: cachedEntities,
|
||||
});
|
||||
});
|
||||
|
||||
it("should disable a plugin and stop polling", async () => {
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
await pluginManager.enablePlugin("test-plugin");
|
||||
pluginManager.disablePlugin("test-plugin");
|
||||
|
||||
expect(pollingManager.stop).toHaveBeenCalledWith("test-plugin");
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("layerToggled", { pluginId: "test-plugin", enabled: false });
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("dataUpdated", { pluginId: "test-plugin", entities: [] });
|
||||
});
|
||||
|
||||
it("should handle data updates by caching and emitting", async () => {
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
const entities = [{ id: "new" }];
|
||||
|
||||
// Trigger private handleDataUpdate via public registerPlugin's context.onDataUpdate if we can
|
||||
const managed = pluginManager.getPlugin("test-plugin");
|
||||
managed?.context.onDataUpdate(entities as any);
|
||||
|
||||
expect(cacheLayer.set).toHaveBeenCalledWith("test-plugin", entities, expect.any(Number));
|
||||
expect(dataBus.emit).toHaveBeenCalledWith("dataUpdated", { pluginId: "test-plugin", entities });
|
||||
expect(useStore.getState().setLayerLoading).toHaveBeenCalledWith("test-plugin", false);
|
||||
});
|
||||
|
||||
it("should load plugin from manifest", async () => {
|
||||
const manifest = { id: "manifest-plugin" };
|
||||
(loadPluginFromManifest as any).mockResolvedValue(mockPlugin);
|
||||
|
||||
await pluginManager.loadFromManifest(manifest as any);
|
||||
|
||||
expect(loadPluginFromManifest).toHaveBeenCalledWith(manifest);
|
||||
// Note: PluginManager overrides ID if it differs
|
||||
expect(mockPlugin.id).toBe("manifest-plugin");
|
||||
});
|
||||
|
||||
it("should get entities for a plugin", async () => {
|
||||
const p1 = { ...mockPlugin, id: "p1" };
|
||||
await pluginManager.registerPlugin(p1 as any);
|
||||
const entities = [{ id: "1" }];
|
||||
(pluginManager as any).handleDataUpdate("p1", entities);
|
||||
expect(pluginManager.getEntities("p1")).toEqual(entities);
|
||||
expect(pluginManager.getEntities("non-existent")).toEqual([]);
|
||||
});
|
||||
|
||||
it("should get all entities from enabled plugins", async () => {
|
||||
const p1 = { ...mockPlugin, id: "p1" };
|
||||
const p2 = { ...mockPlugin, id: "p2" };
|
||||
await pluginManager.registerPlugin(p1 as any);
|
||||
await pluginManager.registerPlugin(p2 as any);
|
||||
await pluginManager.enablePlugin("p1");
|
||||
// p2 is disabled by default
|
||||
|
||||
(pluginManager as any).handleDataUpdate("p1", [{ id: "e1" }]);
|
||||
(pluginManager as any).handleDataUpdate("p2", [{ id: "e2" }]);
|
||||
|
||||
expect(pluginManager.getAllEntities()).toEqual([{ id: "e1" }]);
|
||||
});
|
||||
|
||||
it("should return all plugins and enabled plugins", async () => {
|
||||
await pluginManager.registerPlugin({ ...mockPlugin, id: "p1" } as any);
|
||||
await pluginManager.registerPlugin({ ...mockPlugin, id: "p2" } as any);
|
||||
await pluginManager.enablePlugin("p1");
|
||||
|
||||
expect(pluginManager.getAllPlugins().length).toBe(2);
|
||||
expect(pluginManager.getEnabledPlugins().length).toBe(1);
|
||||
expect(pluginManager.getEnabledPlugins()[0].plugin.id).toBe("p1");
|
||||
});
|
||||
|
||||
it("should fetch for a specific plugin", async () => {
|
||||
const p1 = { ...mockPlugin, id: "fetch-test", fetch: vi.fn().mockResolvedValue([]) };
|
||||
await pluginManager.registerPlugin(p1 as any);
|
||||
await pluginManager.enablePlugin("fetch-test");
|
||||
const timeRange = { start: new Date(), end: new Date() };
|
||||
|
||||
await pluginManager.fetchForPlugin("fetch-test", timeRange);
|
||||
expect(p1.fetch).toHaveBeenCalledWith(timeRange);
|
||||
});
|
||||
|
||||
it("should update time range for all enabled plugins", async () => {
|
||||
const p1 = { ...mockPlugin, id: "p1", fetch: vi.fn().mockResolvedValue([]) };
|
||||
await pluginManager.registerPlugin(p1 as any);
|
||||
await pluginManager.enablePlugin("p1");
|
||||
|
||||
const timeRange = { start: new Date(), end: new Date() };
|
||||
await pluginManager.updateTimeRange(timeRange);
|
||||
expect(p1.fetch).toHaveBeenCalledWith(timeRange);
|
||||
});
|
||||
|
||||
it("should handle destroy", async () => {
|
||||
await pluginManager.registerPlugin(mockPlugin as any);
|
||||
pluginManager.destroy();
|
||||
expect(pollingManager.stopAll).toHaveBeenCalled();
|
||||
expect(mockPlugin.destroy).toHaveBeenCalled();
|
||||
expect(pluginManager.getAllPlugins().length).toBe(0);
|
||||
});
|
||||
|
||||
it("should toggle plugin state", async () => {
|
||||
const p1 = { ...mockPlugin, id: "toggle-test" };
|
||||
await pluginManager.registerPlugin(p1 as any);
|
||||
|
||||
// togglePlugin is void but calls async enablePlugin
|
||||
pluginManager.togglePlugin("toggle-test");
|
||||
// Wait for the async enablePlugin to at least set the enabled flag
|
||||
await vi.waitFor(() => expect(pluginManager.getPlugin("toggle-test")?.enabled).toBe(true));
|
||||
|
||||
pluginManager.togglePlugin("toggle-test");
|
||||
expect(pluginManager.getPlugin("toggle-test")?.enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { loadPluginFromManifest, ManifestLoadError } from "./loadPluginFromManifest";
|
||||
import { validateManifest } from "./validateManifest";
|
||||
|
||||
vi.mock("./validateManifest", () => ({
|
||||
validateManifest: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("loadPluginFromManifest", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should throw ManifestLoadError if validation fails", async () => {
|
||||
(validateManifest as any).mockReturnValue({
|
||||
valid: false,
|
||||
errors: ["Missing ID"],
|
||||
});
|
||||
|
||||
const manifest: any = { id: "test" };
|
||||
await expect(loadPluginFromManifest(manifest)).rejects.toThrow(ManifestLoadError);
|
||||
await expect(loadPluginFromManifest(manifest)).rejects.toThrow("Invalid manifest: Missing ID");
|
||||
});
|
||||
|
||||
it("should attempt to load bundle if manifest is valid", async () => {
|
||||
(validateManifest as any).mockReturnValue({ valid: true, errors: [] });
|
||||
|
||||
// We can't easily mock the dynamic import of an arbitrary string in this environment
|
||||
// without complex setup, so we expect it to fail with a specific error from the catch block
|
||||
const manifest: any = { id: "test", entry: "http://invalid-path.js" };
|
||||
|
||||
await expect(loadPluginFromManifest(manifest)).rejects.toThrow(ManifestLoadError);
|
||||
await expect(loadPluginFromManifest(manifest)).rejects.toThrow("Failed to load plugin");
|
||||
});
|
||||
|
||||
// Note: Testing the actual instantiation logic of loadBundlePlugin
|
||||
// requires a real ESM module or a more sophisticated mock for the import() call.
|
||||
// Given the constraints, we have verified the high-level orchestration.
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { validateManifest } from "./validateManifest";
|
||||
|
||||
describe("validateManifest", () => {
|
||||
it("should validate a correct manifest", () => {
|
||||
const manifest: any = {
|
||||
id: "test-plugin",
|
||||
name: "Test Plugin",
|
||||
version: "1.0.0",
|
||||
type: "data-layer",
|
||||
trust: "verified",
|
||||
capabilities: ["streaming"],
|
||||
entry: "/plugins/test.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should flag missing required fields", () => {
|
||||
const result = validateManifest({});
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Missing required field: id");
|
||||
expect(result.errors).toContain("Missing required field: name");
|
||||
expect(result.errors).toContain("Missing required field: version");
|
||||
expect(result.errors).toContain("Missing required field: entry");
|
||||
});
|
||||
|
||||
it("should flag invalid entry URLs", () => {
|
||||
const manifest: any = {
|
||||
id: "p1", name: "n1", version: "1", type: "data-layer", trust: "verified",
|
||||
capabilities: ["c1"], entry: "https://hacker.com/malicious.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain");
|
||||
});
|
||||
|
||||
it("should require extends for extensions", () => {
|
||||
const manifest: any = {
|
||||
id: "p1", name: "n1", version: "1", type: "extension", trust: "verified",
|
||||
capabilities: ["c1"], entry: "/p.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Extension plugins require a non-empty extends array");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { createGlobeSlice } from "./globeSlice";
|
||||
import { createLayersSlice } from "./layersSlice";
|
||||
import { createUISlice } from "./uiSlice";
|
||||
import { createDataSlice } from "./dataSlice";
|
||||
import { createConfigSlice } from "./configSlice";
|
||||
import { createFavoritesSlice } from "./favoritesSlice";
|
||||
import { createTimelineSlice } from "./timelineSlice";
|
||||
import { createFilterSlice } from "./filterSlice";
|
||||
|
||||
describe("State Slices", () => {
|
||||
describe("GlobeSlice", () => {
|
||||
it("should set camera position", () => {
|
||||
let state: any = {};
|
||||
const set = (update: any) => { state = { ...state, ...update }; };
|
||||
const slice = createGlobeSlice(set, () => ({} as any), {} as any);
|
||||
|
||||
slice.setCameraPosition(10, 20, 30);
|
||||
expect(state.cameraLat).toBe(10);
|
||||
expect(state.cameraLon).toBe(20);
|
||||
expect(state.cameraAlt).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("LayersSlice", () => {
|
||||
it("should toggle layer", () => {
|
||||
let state: any = { layers: { "p1": { enabled: false } } };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createLayersSlice(set, () => state as any, {} as any);
|
||||
|
||||
slice.toggleLayer("p1");
|
||||
expect(state.layers["p1"].enabled).toBe(true);
|
||||
});
|
||||
|
||||
it("should init layer if missing", () => {
|
||||
let state: any = { layers: {} };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createLayersSlice(set, () => state as any, {} as any);
|
||||
|
||||
slice.initLayer("p2", true);
|
||||
expect(state.layers["p2"]).toEqual({ enabled: true, entityCount: 0, loading: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("UISlice", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
setAttribute: vi.fn(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should toggle theme", () => {
|
||||
let state: any = { theme: "black" };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createUISlice(set, () => state as any, {} as any);
|
||||
|
||||
slice.toggleTheme();
|
||||
expect(state.theme).toBe("light");
|
||||
expect(document.documentElement.setAttribute).toHaveBeenCalledWith("data-theme", "light");
|
||||
});
|
||||
|
||||
it("should add floating stream", () => {
|
||||
let state: any = { floatingStreams: [] };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createUISlice(set, () => state as any, {} as any);
|
||||
|
||||
slice.addFloatingStream({ id: "s1", label: "Stream 1", streamUrl: "url", isIframe: false });
|
||||
expect(state.floatingStreams.length).toBe(1);
|
||||
expect(state.floatingStreams[0].id).toBe("s1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DataSlice", () => {
|
||||
it("should set entities and keep selectedEntity fresh", () => {
|
||||
let state: any = {
|
||||
entitiesByPlugin: {},
|
||||
selectedEntity: { id: "1", pluginId: "p1", name: "Old Name" }
|
||||
};
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const get = () => state;
|
||||
const slice = createDataSlice(set, get, {} as any);
|
||||
|
||||
const newEntities = [{ id: "1", pluginId: "p1", name: "New Name" } as any];
|
||||
slice.setEntities("p1", newEntities);
|
||||
|
||||
expect(state.entitiesByPlugin["p1"]).toEqual(newEntities);
|
||||
expect(state.selectedEntity.name).toBe("New Name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ConfigSlice", () => {
|
||||
it("should update data config", () => {
|
||||
let state: any = { dataConfig: { cacheEnabled: false } };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createConfigSlice(set, () => ({} as any), {} as any);
|
||||
|
||||
slice.updateDataConfig({ cacheEnabled: true });
|
||||
expect(state.dataConfig.cacheEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("should set polling interval", () => {
|
||||
let state: any = { dataConfig: { pollingIntervals: {} } };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createConfigSlice(set, () => ({} as any), {} as any);
|
||||
|
||||
slice.setPollingInterval("p1", 5000);
|
||||
expect(state.dataConfig.pollingIntervals["p1"]).toBe(5000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FavoritesSlice", () => {
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn().mockResolvedValue({ ok: true }) as any;
|
||||
vi.stubGlobal("document", { cookie: "" });
|
||||
});
|
||||
|
||||
it("should add favorite and trigger sync", () => {
|
||||
let state: any = { favorites: [] };
|
||||
const set = (update: any) => { state = { ...state, ...update }; };
|
||||
const slice = createFavoritesSlice(set, () => state as any, {} as any);
|
||||
|
||||
const entity = { id: "e1", pluginId: "p1", label: "Entity 1" };
|
||||
slice.addFavorite(entity as any, "Plugin 1");
|
||||
|
||||
expect(state.favorites.length).toBe(1);
|
||||
expect(state.favorites[0].id).toBe("e1");
|
||||
expect(global.fetch).toHaveBeenCalledWith("/api/user/favorites", expect.any(Object));
|
||||
});
|
||||
|
||||
it("should sync to cookies in demo mode", () => {
|
||||
// requires mocking isDemo to true
|
||||
});
|
||||
});
|
||||
|
||||
describe("TimelineSlice", () => {
|
||||
it("should set time window and calculate range", () => {
|
||||
let state: any = { timeWindow: "1h", timeRange: null };
|
||||
const set = (update: any) => { state = { ...state, ...update }; };
|
||||
const slice = createTimelineSlice(set, () => ({} as any), {} as any);
|
||||
|
||||
slice.setTimeWindow("6h");
|
||||
expect(state.timeWindow).toBe("6h");
|
||||
expect(state.timeRange.start).toBeInstanceOf(Date);
|
||||
expect(state.timeRange.end).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FilterSlice", () => {
|
||||
it("should set and clear filters", () => {
|
||||
let state: any = { filters: {} };
|
||||
const set = (fn: any) => { state = { ...state, ...fn(state) }; };
|
||||
const slice = createFilterSlice(set, () => ({} as any), {} as any);
|
||||
|
||||
slice.setFilter("p1", "f1", { type: "boolean", value: true });
|
||||
expect(state.filters["p1"]["f1"]).toEqual({ type: "boolean", value: true });
|
||||
|
||||
slice.clearFilters("p1");
|
||||
expect(state.filters["p1"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createConfigSlice, ConfigSlice } from './configSlice';
|
||||
|
||||
describe('configSlice', () => {
|
||||
let store: StoreApi<ConfigSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Mock localStorage
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
});
|
||||
|
||||
store = createStore<ConfigSlice>((set, get, api) => createConfigSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with default config', () => {
|
||||
const state = store.getState();
|
||||
expect(state.dataConfig.cacheEnabled).toBe(true);
|
||||
expect(state.mapConfig.antiAliasing).toBe('fxaa');
|
||||
});
|
||||
|
||||
it('updates data config', () => {
|
||||
store.getState().updateDataConfig({ cacheEnabled: false, maxConcurrentRequests: 10 });
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.dataConfig.cacheEnabled).toBe(false);
|
||||
expect(state.dataConfig.maxConcurrentRequests).toBe(10);
|
||||
// Ensure other properties are untouched
|
||||
expect(state.dataConfig.cacheMaxAge).toBe(3600000);
|
||||
});
|
||||
|
||||
it('updates map config and syncs baseLayerId to localStorage', () => {
|
||||
store.getState().updateMapConfig({ showFps: true, baseLayerId: 'satellite' });
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.mapConfig.showFps).toBe(true);
|
||||
expect(state.mapConfig.baseLayerId).toBe('satellite');
|
||||
// Ensure localStorage was called
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith('wwv_map_layer', 'satellite');
|
||||
});
|
||||
|
||||
it('updates map config without baseLayerId does not touch localStorage', () => {
|
||||
store.getState().updateMapConfig({ showFps: true });
|
||||
|
||||
expect(localStorage.setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sets polling interval for a plugin', () => {
|
||||
store.getState().setPollingInterval('plugin-a', 5000);
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.dataConfig.pollingIntervals['plugin-a']).toBe(5000);
|
||||
});
|
||||
|
||||
it('updates plugin settings deeply', () => {
|
||||
// Initial set
|
||||
store.getState().updatePluginSettings('plugin-a', { param1: 'value1' });
|
||||
expect(store.getState().dataConfig.pluginSettings['plugin-a']).toEqual({ param1: 'value1' });
|
||||
|
||||
// Update set (should merge)
|
||||
store.getState().updatePluginSettings('plugin-a', { param2: 'value2' });
|
||||
expect(store.getState().dataConfig.pluginSettings['plugin-a']).toEqual({
|
||||
param1: 'value1',
|
||||
param2: 'value2'
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createDataSlice, DataSlice } from './dataSlice';
|
||||
import type { GeoEntity } from '@/core/plugins/PluginTypes';
|
||||
|
||||
// We need a mock store that includes selectedEntity to test the cross-slice update behavior
|
||||
interface MockAppStore extends DataSlice {
|
||||
selectedEntity: GeoEntity | null;
|
||||
}
|
||||
|
||||
describe('dataSlice', () => {
|
||||
let store: StoreApi<MockAppStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore<MockAppStore>((set, get, api) => {
|
||||
const dataSlice = createDataSlice(set as any, get as any, api as any);
|
||||
return {
|
||||
...dataSlice,
|
||||
selectedEntity: null,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
it('initializes with empty entities', () => {
|
||||
expect(store.getState().entitiesByPlugin).toEqual({});
|
||||
});
|
||||
|
||||
it('sets entities for a plugin', () => {
|
||||
const mockEntities = [{ id: 'e1', pluginId: 'plugin-a' } as GeoEntity];
|
||||
store.getState().setEntities('plugin-a', mockEntities);
|
||||
|
||||
expect(store.getState().entitiesByPlugin['plugin-a']).toEqual(mockEntities);
|
||||
});
|
||||
|
||||
it('updates selectedEntity if new data for the same entity arrives', () => {
|
||||
// Initial selected entity
|
||||
const oldEntity = { id: 'e1', pluginId: 'plugin-a', name: 'Old Name' } as any as GeoEntity;
|
||||
store.setState({ selectedEntity: oldEntity });
|
||||
|
||||
// New data arrives with updated name
|
||||
const freshEntity = { id: 'e1', pluginId: 'plugin-a', name: 'New Name' } as any as GeoEntity;
|
||||
store.getState().setEntities('plugin-a', [freshEntity]);
|
||||
|
||||
expect(store.getState().selectedEntity).toEqual(freshEntity);
|
||||
});
|
||||
|
||||
it('does not update selectedEntity if new data does not contain it', () => {
|
||||
const oldEntity = { id: 'e1', pluginId: 'plugin-a', name: 'Old Name' } as any as GeoEntity;
|
||||
store.setState({ selectedEntity: oldEntity });
|
||||
|
||||
// New data arrives but the entity is missing
|
||||
store.getState().setEntities('plugin-a', [{ id: 'e2', pluginId: 'plugin-a' } as GeoEntity]);
|
||||
|
||||
expect(store.getState().selectedEntity).toEqual(oldEntity);
|
||||
});
|
||||
|
||||
it('clears entities for a specific plugin', () => {
|
||||
const mockEntitiesA = [{ id: 'e1', pluginId: 'plugin-a' } as GeoEntity];
|
||||
const mockEntitiesB = [{ id: 'e2', pluginId: 'plugin-b' } as GeoEntity];
|
||||
|
||||
store.getState().setEntities('plugin-a', mockEntitiesA);
|
||||
store.getState().setEntities('plugin-b', mockEntitiesB);
|
||||
|
||||
store.getState().clearEntities('plugin-a');
|
||||
|
||||
expect(store.getState().entitiesByPlugin['plugin-a']).toBeUndefined();
|
||||
expect(store.getState().entitiesByPlugin['plugin-b']).toEqual(mockEntitiesB);
|
||||
});
|
||||
|
||||
it('gets all entities across plugins flattened', () => {
|
||||
const mockEntitiesA = [{ id: 'e1', pluginId: 'plugin-a' } as GeoEntity];
|
||||
const mockEntitiesB = [{ id: 'e2', pluginId: 'plugin-b' } as GeoEntity];
|
||||
|
||||
store.getState().setEntities('plugin-a', mockEntitiesA);
|
||||
store.getState().setEntities('plugin-b', mockEntitiesB);
|
||||
|
||||
const all = store.getState().getAllEntities();
|
||||
|
||||
expect(all).toHaveLength(2);
|
||||
expect(all).toContainEqual(mockEntitiesA[0]);
|
||||
expect(all).toContainEqual(mockEntitiesB[0]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createFavoritesSlice, FavoritesSlice, FavoriteItem } from './favoritesSlice';
|
||||
import type { GeoEntity } from '@/core/plugins/PluginTypes';
|
||||
|
||||
// Mock the edition module so we can control `isDemo`
|
||||
vi.mock('@/core/edition', () => ({
|
||||
isDemo: true // We'll override this in specific tests using vi.mocked if needed, but for now we default to true to test cookie logic
|
||||
}));
|
||||
import { isDemo } from '@/core/edition';
|
||||
|
||||
describe('favoritesSlice', () => {
|
||||
let store: StoreApi<FavoritesSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset document.cookie and mock fetch
|
||||
Object.defineProperty(document, 'cookie', {
|
||||
writable: true,
|
||||
value: '',
|
||||
});
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({}));
|
||||
|
||||
store = createStore<FavoritesSlice>((set, get, api) => createFavoritesSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const mockEntity = { id: 'entity-1', pluginId: 'plugin-a', label: 'Test Entity' } as GeoEntity;
|
||||
|
||||
it('initializes with empty favorites', () => {
|
||||
expect(store.getState().favorites).toEqual([]);
|
||||
});
|
||||
|
||||
it('initializes favorites from a provided array', () => {
|
||||
const initialFavs: FavoriteItem[] = [{ id: 'fav-1', pluginId: 'p-1', label: 'L1', pluginName: 'PN1', lastSeen: 100 }];
|
||||
store.getState().initFavorites(initialFavs);
|
||||
expect(store.getState().favorites).toEqual(initialFavs);
|
||||
});
|
||||
|
||||
it('adds a new favorite, sets lastSeen, and syncs cookie in demo mode', () => {
|
||||
const now = 1000000;
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
|
||||
store.getState().addFavorite(mockEntity, 'Plugin A', 'icon-stub');
|
||||
|
||||
const favs = store.getState().favorites;
|
||||
expect(favs).toHaveLength(1);
|
||||
expect(favs[0]).toEqual(expect.objectContaining({
|
||||
id: 'entity-1',
|
||||
pluginId: 'plugin-a',
|
||||
label: 'Test Entity',
|
||||
pluginName: 'Plugin A',
|
||||
icon: 'icon-stub',
|
||||
lastSeen: now
|
||||
}));
|
||||
|
||||
// Check cookie
|
||||
expect(document.cookie).toContain('wwv_favorites');
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('prevents adding duplicate favorites by id', () => {
|
||||
store.getState().addFavorite(mockEntity, 'Plugin A');
|
||||
store.getState().addFavorite(mockEntity, 'Plugin A'); // Should be ignored
|
||||
|
||||
expect(store.getState().favorites).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('removes a favorite and syncs cookie in demo mode', () => {
|
||||
store.getState().addFavorite(mockEntity, 'Plugin A');
|
||||
expect(store.getState().favorites).toHaveLength(1);
|
||||
|
||||
store.getState().removeFavorite('entity-1');
|
||||
expect(store.getState().favorites).toHaveLength(0);
|
||||
|
||||
// Check cookie serialization updates
|
||||
const decodedCookie = decodeURIComponent(document.cookie.replace('wwv_favorites=', ''));
|
||||
expect(decodedCookie).toContain('[]'); // empty array after removal
|
||||
});
|
||||
|
||||
describe('cloud mode (isDemo = false)', () => {
|
||||
beforeEach(() => {
|
||||
// Because isDemo is a constant exported from a module, standard vi.mock overriding per-test
|
||||
// for constants is tricky without resetModules.
|
||||
// We'll test the API logic by overriding it internally or just acknowledging we'd need to mock the import dynamically.
|
||||
// For simplicity in this suite without full dynamic import mocking, we'll verify the fetch behavior
|
||||
// by overriding the constant property if possible, or using a separate module mock.
|
||||
});
|
||||
|
||||
// Note: To properly test fetch vs cookie branches, we'd typically inject `isDemo`
|
||||
// or test it in an isolated test file. Since we defaulted to `isDemo: true`,
|
||||
// fetch should NOT be called. Let's verify that.
|
||||
it('does not call fetch API when in demo mode', () => {
|
||||
store.getState().addFavorite(mockEntity, 'Plugin A');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
|
||||
store.getState().removeFavorite('entity-1');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createFilterSlice, FilterSlice } from './filterSlice';
|
||||
import type { FilterValue } from '@/core/plugins/PluginTypes';
|
||||
|
||||
describe('filterSlice', () => {
|
||||
let store: StoreApi<FilterSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore<FilterSlice>((set, get, api) => createFilterSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with empty filters', () => {
|
||||
const state = store.getState();
|
||||
expect(state.filters).toEqual({});
|
||||
});
|
||||
|
||||
it('sets a specific filter for a plugin', () => {
|
||||
const filterVal: FilterValue = { type: 'boolean', value: true };
|
||||
store.getState().setFilter('plugin-a', 'show-active', filterVal);
|
||||
|
||||
const state = store.getState();
|
||||
expect(state.filters['plugin-a']).toBeDefined();
|
||||
expect(state.filters['plugin-a']['show-active']).toEqual(filterVal);
|
||||
});
|
||||
|
||||
it('updates an existing filter without overwriting other filters for the same plugin', () => {
|
||||
const filterVal1: FilterValue = { type: 'boolean', value: true };
|
||||
const filterVal2: FilterValue = { type: 'select', values: ['option1'] };
|
||||
|
||||
store.getState().setFilter('plugin-a', 'filter-1', filterVal1);
|
||||
store.getState().setFilter('plugin-a', 'filter-2', filterVal2);
|
||||
|
||||
let state = store.getState();
|
||||
expect(state.filters['plugin-a']['filter-1']).toEqual(filterVal1);
|
||||
expect(state.filters['plugin-a']['filter-2']).toEqual(filterVal2);
|
||||
|
||||
// Update filter-1
|
||||
const updatedFilterVal1: FilterValue = { type: 'boolean', value: false };
|
||||
store.getState().setFilter('plugin-a', 'filter-1', updatedFilterVal1);
|
||||
|
||||
state = store.getState();
|
||||
expect(state.filters['plugin-a']['filter-1']).toEqual(updatedFilterVal1);
|
||||
expect(state.filters['plugin-a']['filter-2']).toEqual(filterVal2); // Still preserved
|
||||
});
|
||||
|
||||
it('clears all filters for a specific plugin', () => {
|
||||
store.getState().setFilter('plugin-a', 'f1', { type: 'boolean', value: true });
|
||||
store.getState().setFilter('plugin-b', 'f2', { type: 'boolean', value: false });
|
||||
|
||||
store.getState().clearFilters('plugin-a');
|
||||
|
||||
const state = store.getState();
|
||||
expect(state.filters['plugin-a']).toBeUndefined();
|
||||
expect(state.filters['plugin-b']).toBeDefined(); // plugin-b untouched
|
||||
});
|
||||
|
||||
it('clears all filters globally', () => {
|
||||
store.getState().setFilter('plugin-a', 'f1', { type: 'boolean', value: true });
|
||||
store.getState().setFilter('plugin-b', 'f2', { type: 'boolean', value: false });
|
||||
|
||||
store.getState().clearAllFilters();
|
||||
|
||||
const state = store.getState();
|
||||
expect(state.filters).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createGeoJsonSlice, GeoJsonSlice, ImportedLayer } from './geojsonSlice';
|
||||
|
||||
describe('geojsonSlice', () => {
|
||||
let store: StoreApi<GeoJsonSlice>;
|
||||
|
||||
const mockLayer: ImportedLayer = {
|
||||
id: 'layer-1',
|
||||
name: 'Test Layer',
|
||||
description: 'A test geojson layer',
|
||||
color: '#ff0000',
|
||||
visible: true,
|
||||
featureCollection: { type: 'FeatureCollection', features: [] }
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore<GeoJsonSlice>((set, get, api) => createGeoJsonSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with empty importedLayers', () => {
|
||||
expect(store.getState().importedLayers).toEqual([]);
|
||||
});
|
||||
|
||||
it('adds an imported layer', () => {
|
||||
store.getState().addImportedLayer(mockLayer);
|
||||
const layers = store.getState().importedLayers;
|
||||
|
||||
expect(layers).toHaveLength(1);
|
||||
expect(layers[0]).toEqual(mockLayer);
|
||||
});
|
||||
|
||||
it('removes an imported layer by id', () => {
|
||||
store.getState().addImportedLayer(mockLayer);
|
||||
store.getState().addImportedLayer({ ...mockLayer, id: 'layer-2' });
|
||||
|
||||
store.getState().removeImportedLayer('layer-1');
|
||||
const layers = store.getState().importedLayers;
|
||||
|
||||
expect(layers).toHaveLength(1);
|
||||
expect(layers[0].id).toBe('layer-2');
|
||||
});
|
||||
|
||||
it('toggles visibility of an imported layer', () => {
|
||||
store.getState().addImportedLayer(mockLayer); // initially visible: true
|
||||
|
||||
store.getState().toggleImportedLayerVisibility('layer-1');
|
||||
expect(store.getState().importedLayers[0].visible).toBe(false);
|
||||
|
||||
store.getState().toggleImportedLayerVisibility('layer-1');
|
||||
expect(store.getState().importedLayers[0].visible).toBe(true);
|
||||
});
|
||||
|
||||
it('updates specific fields of an imported layer', () => {
|
||||
store.getState().addImportedLayer(mockLayer);
|
||||
|
||||
store.getState().updateImportedLayer('layer-1', {
|
||||
name: 'Updated Name',
|
||||
color: '#00ff00'
|
||||
});
|
||||
|
||||
const layer = store.getState().importedLayers[0];
|
||||
expect(layer.name).toBe('Updated Name');
|
||||
expect(layer.color).toBe('#00ff00');
|
||||
// Unchanged fields remain the same
|
||||
expect(layer.description).toBe('A test geojson layer');
|
||||
expect(layer.visible).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createGlobeSlice, GlobeSlice } from './globeSlice';
|
||||
|
||||
describe('globeSlice', () => {
|
||||
let store: StoreApi<GlobeSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create an isolated vanilla store specifically for this slice
|
||||
store = createStore<GlobeSlice>((set, get, api) => createGlobeSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('sets initial camera state correctly', () => {
|
||||
const state = store.getState();
|
||||
expect(state.cameraLat).toBe(20);
|
||||
expect(state.cameraLon).toBe(0);
|
||||
expect(state.cameraAlt).toBe(20000000);
|
||||
expect(state.cameraHeading).toBe(0);
|
||||
expect(state.cameraPitch).toBe(-90);
|
||||
expect(state.cameraRoll).toBe(0);
|
||||
expect(state.isAnimating).toBe(false);
|
||||
expect(state.fps).toBe(0);
|
||||
});
|
||||
|
||||
it('updates camera position atomically', () => {
|
||||
store.getState().setCameraPosition(45, -90, 1000);
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.cameraLat).toBe(45);
|
||||
expect(state.cameraLon).toBe(-90);
|
||||
expect(state.cameraAlt).toBe(1000);
|
||||
});
|
||||
|
||||
it('resets orientation to defaults when not provided in position update', () => {
|
||||
// First set custom orientation
|
||||
store.getState().setCameraPosition(45, -90, 1000, 45, -45, 15);
|
||||
// Then set without orientation
|
||||
store.getState().setCameraPosition(50, -80, 2000);
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.cameraHeading).toBe(0);
|
||||
expect(state.cameraPitch).toBe(-90);
|
||||
expect(state.cameraRoll).toBe(0);
|
||||
});
|
||||
|
||||
it('updates custom orientation when provided', () => {
|
||||
store.getState().setCameraPosition(45, -90, 1000, 180, -30, 45);
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.cameraHeading).toBe(180);
|
||||
expect(state.cameraPitch).toBe(-30);
|
||||
expect(state.cameraRoll).toBe(45);
|
||||
});
|
||||
|
||||
it('toggles animation state', () => {
|
||||
store.getState().setAnimating(true);
|
||||
expect(store.getState().isAnimating).toBe(true);
|
||||
|
||||
store.getState().setAnimating(false);
|
||||
expect(store.getState().isAnimating).toBe(false);
|
||||
});
|
||||
|
||||
it('records frames per second', () => {
|
||||
store.getState().setFps(60);
|
||||
expect(store.getState().fps).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createLayersSlice, LayersSlice } from './layersSlice';
|
||||
|
||||
describe('layersSlice', () => {
|
||||
let store: StoreApi<LayersSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore<LayersSlice>((set, get, api) => createLayersSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with empty layers', () => {
|
||||
const state = store.getState();
|
||||
expect(state.layers).toEqual({});
|
||||
});
|
||||
|
||||
it('initializes a new layer with default values', () => {
|
||||
store.getState().initLayer('test-plugin');
|
||||
const state = store.getState();
|
||||
expect(state.layers['test-plugin']).toEqual({
|
||||
enabled: false,
|
||||
entityCount: 0,
|
||||
loading: false
|
||||
});
|
||||
});
|
||||
|
||||
it('initializes a new layer with explicitly requested enabled status', () => {
|
||||
store.getState().initLayer('test-plugin', true);
|
||||
const state = store.getState();
|
||||
expect(state.layers['test-plugin'].enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('does not overwrite an existing layer upon re-initialization', () => {
|
||||
store.getState().initLayer('test-plugin', true);
|
||||
store.getState().setEntityCount('test-plugin', 42);
|
||||
|
||||
// Re-initialize
|
||||
store.getState().initLayer('test-plugin', false);
|
||||
const state = store.getState();
|
||||
|
||||
// Should preserve previous state
|
||||
expect(state.layers['test-plugin'].enabled).toBe(true);
|
||||
expect(state.layers['test-plugin'].entityCount).toBe(42);
|
||||
});
|
||||
|
||||
it('toggles layer enabled status', () => {
|
||||
store.getState().initLayer('test-plugin', false);
|
||||
|
||||
store.getState().toggleLayer('test-plugin');
|
||||
expect(store.getState().layers['test-plugin'].enabled).toBe(true);
|
||||
|
||||
store.getState().toggleLayer('test-plugin');
|
||||
expect(store.getState().layers['test-plugin'].enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('explicitly sets layer enabled status', () => {
|
||||
store.getState().initLayer('test-plugin', false);
|
||||
|
||||
store.getState().setLayerEnabled('test-plugin', true);
|
||||
expect(store.getState().layers['test-plugin'].enabled).toBe(true);
|
||||
|
||||
store.getState().setLayerEnabled('test-plugin', true); // Should remain true
|
||||
expect(store.getState().layers['test-plugin'].enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('updates entity count', () => {
|
||||
store.getState().initLayer('test-plugin');
|
||||
|
||||
store.getState().setEntityCount('test-plugin', 150);
|
||||
expect(store.getState().layers['test-plugin'].entityCount).toBe(150);
|
||||
});
|
||||
|
||||
it('updates loading status', () => {
|
||||
store.getState().initLayer('test-plugin');
|
||||
|
||||
store.getState().setLayerLoading('test-plugin', true);
|
||||
expect(store.getState().layers['test-plugin'].loading).toBe(true);
|
||||
|
||||
store.getState().setLayerLoading('test-plugin', false);
|
||||
expect(store.getState().layers['test-plugin'].loading).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createTimelineSlice, TimelineSlice } from './timelineSlice';
|
||||
import type { TimeWindow } from '@/core/plugins/PluginTypes';
|
||||
|
||||
describe('timelineSlice', () => {
|
||||
let store: StoreApi<TimelineSlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Freeze time for consistent tests
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-05-13T12:00:00Z'));
|
||||
|
||||
store = createStore<TimelineSlice>((set, get, api) => createTimelineSlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with correct defaults', () => {
|
||||
const state = store.getState();
|
||||
expect(state.timeWindow).toBe('24h');
|
||||
expect(state.isPlaying).toBe(false);
|
||||
expect(state.playbackSpeed).toBe(1);
|
||||
expect(state.isPlaybackMode).toBe(false);
|
||||
expect(state.timelineAvailability).toEqual({});
|
||||
|
||||
// timeRange should be 24h behind current time
|
||||
const expectedStart = new Date(Date.now() - 86400000);
|
||||
expect(state.timeRange.start.getTime()).toBe(expectedStart.getTime());
|
||||
expect(state.timeRange.end.getTime()).toBe(Date.now());
|
||||
});
|
||||
|
||||
it('updates time window and dynamically recalculates time range', () => {
|
||||
store.getState().setTimeWindow('1h' as TimeWindow);
|
||||
const state = store.getState();
|
||||
|
||||
expect(state.timeWindow).toBe('1h');
|
||||
const expectedStart = new Date(Date.now() - 3600000); // 1 hour
|
||||
expect(state.timeRange.start.getTime()).toBe(expectedStart.getTime());
|
||||
});
|
||||
|
||||
it('sets current time', () => {
|
||||
const newTime = new Date('2026-05-13T10:00:00Z');
|
||||
store.getState().setCurrentTime(newTime);
|
||||
expect(store.getState().currentTime).toBe(newTime);
|
||||
});
|
||||
|
||||
it('sets exact time range', () => {
|
||||
const range = { start: new Date('2026-01-01'), end: new Date('2026-01-02') };
|
||||
store.getState().setTimeRange(range);
|
||||
expect(store.getState().timeRange).toEqual(range);
|
||||
});
|
||||
|
||||
it('sets playback states', () => {
|
||||
store.getState().setPlaying(true);
|
||||
expect(store.getState().isPlaying).toBe(true);
|
||||
|
||||
store.getState().setPlaybackSpeed(5);
|
||||
expect(store.getState().playbackSpeed).toBe(5);
|
||||
|
||||
store.getState().setPlaybackMode(true);
|
||||
expect(store.getState().isPlaybackMode).toBe(true);
|
||||
|
||||
store.getState().setPlaybackTime(10000);
|
||||
expect(store.getState().playbackTime).toBe(10000);
|
||||
});
|
||||
|
||||
it('sets timeline availability for plugins', () => {
|
||||
const availability = [{ start: 100, end: 200 }];
|
||||
store.getState().setTimelineAvailability('plugin-a', availability);
|
||||
|
||||
expect(store.getState().timelineAvailability['plugin-a']).toEqual(availability);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { createStore, type StoreApi } from 'zustand/vanilla';
|
||||
import { createUISlice, UISlice, FloatingStream } from './uiSlice';
|
||||
import type { GeoEntity } from '@/core/plugins/PluginTypes';
|
||||
|
||||
// Mock the analytics module to prevent actual tracking during tests
|
||||
vi.mock('@/lib/analytics', () => ({
|
||||
trackEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('uiSlice', () => {
|
||||
let store: StoreApi<UISlice>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset local storage and document element
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
});
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
store = createStore<UISlice>((set, get, api) => createUISlice(set as any, get as any, api as any));
|
||||
});
|
||||
|
||||
it('initializes with correct default state', () => {
|
||||
const state = store.getState();
|
||||
expect(state.leftSidebarOpen).toBe(true);
|
||||
expect(state.rightSidebarOpen).toBe(false);
|
||||
expect(state.configPanelOpen).toBe(true);
|
||||
expect(state.filterPanelOpen).toBe(false);
|
||||
expect(state.selectedEntity).toBeNull();
|
||||
expect(state.floatingStreams).toEqual([]);
|
||||
expect(state.activeConfigTab).toBe('filters');
|
||||
expect(state.timelineOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles simple boolean states', () => {
|
||||
store.getState().toggleLeftSidebar();
|
||||
expect(store.getState().leftSidebarOpen).toBe(false);
|
||||
|
||||
store.getState().toggleRightSidebar();
|
||||
expect(store.getState().rightSidebarOpen).toBe(true);
|
||||
|
||||
store.getState().toggleConfigPanel();
|
||||
expect(store.getState().configPanelOpen).toBe(false);
|
||||
|
||||
store.getState().toggleFilterPanel();
|
||||
expect(store.getState().filterPanelOpen).toBe(true);
|
||||
|
||||
store.getState().setTimelineOpen(false);
|
||||
expect(store.getState().timelineOpen).toBe(false);
|
||||
|
||||
store.getState().setFeedbackDialogOpen(true);
|
||||
expect(store.getState().feedbackDialogOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles themes cyclically and updates DOM/localStorage', () => {
|
||||
// Start with black
|
||||
store.getState().setTheme('black');
|
||||
|
||||
store.getState().toggleTheme();
|
||||
expect(store.getState().theme).toBe('light');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith('wwv-theme', 'light');
|
||||
|
||||
store.getState().toggleTheme();
|
||||
expect(store.getState().theme).toBe('legacy');
|
||||
|
||||
store.getState().toggleTheme();
|
||||
expect(store.getState().theme).toBe('dark');
|
||||
|
||||
store.getState().toggleTheme();
|
||||
expect(store.getState().theme).toBe('black');
|
||||
});
|
||||
|
||||
it('sets specific theme directly', () => {
|
||||
store.getState().setTheme('legacy');
|
||||
expect(store.getState().theme).toBe('legacy');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('legacy');
|
||||
});
|
||||
|
||||
it('handles setting selected entity and related UI panels', () => {
|
||||
const mockEntity = { id: 'e1', pluginId: 'test' } as GeoEntity;
|
||||
|
||||
// When setting entity, right sidebar and config should open
|
||||
store.getState().setSelectedEntity(mockEntity);
|
||||
let state = store.getState();
|
||||
expect(state.selectedEntity).toEqual(mockEntity);
|
||||
expect(state.rightSidebarOpen).toBe(true);
|
||||
expect(state.configPanelOpen).toBe(true);
|
||||
expect(state.mobileRightPanelGlow).toBe(true);
|
||||
expect(state.activeConfigTab).toBe('intel');
|
||||
|
||||
// When unsetting entity, panels should stay open, but glow and entity reset
|
||||
store.getState().setSelectedEntity(null);
|
||||
state = store.getState();
|
||||
expect(state.selectedEntity).toBeNull();
|
||||
expect(state.rightSidebarOpen).toBe(true); // Should remain true
|
||||
expect(state.configPanelOpen).toBe(true); // Should remain true
|
||||
expect(state.mobileRightPanelGlow).toBe(false);
|
||||
});
|
||||
|
||||
it('sets hovered entity and position', () => {
|
||||
const mockEntity = { id: 'e2', pluginId: 'test' } as GeoEntity;
|
||||
store.getState().setHoveredEntity(mockEntity, { x: 100, y: 200 });
|
||||
|
||||
const state = store.getState();
|
||||
expect(state.hoveredEntity).toEqual(mockEntity);
|
||||
expect(state.hoveredScreenPosition).toEqual({ x: 100, y: 200 });
|
||||
});
|
||||
|
||||
it('manages floating streams', () => {
|
||||
const newStream: Omit<FloatingStream, "position" | "size"> = {
|
||||
id: 'stream-1',
|
||||
streamUrl: 'http://test',
|
||||
isIframe: true,
|
||||
label: 'Test Stream'
|
||||
};
|
||||
|
||||
// Add
|
||||
store.getState().addFloatingStream(newStream);
|
||||
let state = store.getState();
|
||||
expect(state.floatingStreams.length).toBe(1);
|
||||
expect(state.floatingStreams[0].id).toBe('stream-1');
|
||||
// Check default size and position
|
||||
expect(state.floatingStreams[0].size).toEqual({ width: 400, height: 260 });
|
||||
|
||||
// Update
|
||||
store.getState().updateFloatingStream('stream-1', { isMinimized: true });
|
||||
state = store.getState();
|
||||
expect(state.floatingStreams[0].isMinimized).toBe(true);
|
||||
|
||||
// Prevent duplicates
|
||||
store.getState().addFloatingStream(newStream);
|
||||
expect(store.getState().floatingStreams.length).toBe(1);
|
||||
|
||||
// Remove
|
||||
store.getState().removeFloatingStream('stream-1');
|
||||
expect(store.getState().floatingStreams.length).toBe(0);
|
||||
});
|
||||
|
||||
it('manages error toasts', () => {
|
||||
store.getState().showErrorToast('Test error message');
|
||||
expect(store.getState().errorToastMessage).toBe('Test error message');
|
||||
|
||||
store.getState().clearErrorToast();
|
||||
expect(store.getState().errorToastMessage).toBeNull();
|
||||
});
|
||||
|
||||
it('manages mobile panels and glow', () => {
|
||||
store.getState().setOpenMobilePanel('right');
|
||||
expect(store.getState().openMobilePanel).toBe('right');
|
||||
expect(store.getState().mobileRightPanelGlow).toBe(false); // Should clear glow when opening right panel
|
||||
|
||||
// Clicking same panel closes it
|
||||
store.getState().setOpenMobilePanel('right');
|
||||
expect(store.getState().openMobilePanel).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { authConfig } from "./auth.config";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
describe("authConfig", () => {
|
||||
const authorized = authConfig.callbacks?.authorized as any;
|
||||
|
||||
it("should allow access to API routes without auth", () => {
|
||||
const mockRequest = { nextUrl: { pathname: "/api/test" } };
|
||||
expect(authorized({ auth: null, request: mockRequest })).toBe(true);
|
||||
});
|
||||
|
||||
it("should allow access to setup and login pages without auth", () => {
|
||||
expect(authorized({ auth: null, request: { nextUrl: { pathname: "/setup" } } })).toBe(true);
|
||||
expect(authorized({ auth: null, request: { nextUrl: { pathname: "/login" } } })).toBe(true);
|
||||
});
|
||||
|
||||
it("should block access to dashboard if not logged in (non-demo)", () => {
|
||||
const mockRequest = { nextUrl: { pathname: "/" } };
|
||||
expect(authorized({ auth: null, request: mockRequest })).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow access to dashboard if logged in (non-demo)", () => {
|
||||
const mockRequest = { nextUrl: { pathname: "/" } };
|
||||
const mockAuth = { user: { name: "test" } };
|
||||
expect(authorized({ auth: mockAuth, request: mockRequest })).toBe(true);
|
||||
});
|
||||
|
||||
it("should allow access to dashboard if in demo mode", () => {
|
||||
// Manually override mock behavior if possible, or use a separate file
|
||||
// For this test we'll assume isDemo returns true (requires different mock setup)
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { trackEvent } from "./analytics";
|
||||
|
||||
describe("analytics", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("window", { umami: { track: vi.fn() } });
|
||||
});
|
||||
|
||||
it("should call window.umami.track if available", () => {
|
||||
trackEvent("test-event", { key: "val" });
|
||||
expect(window.umami!.track).toHaveBeenCalledWith("test-event", { key: "val" });
|
||||
});
|
||||
|
||||
it("should not throw if umami is missing", () => {
|
||||
vi.stubGlobal("window", {});
|
||||
expect(() => trackEvent("test")).not.toThrow();
|
||||
});
|
||||
|
||||
it("should not throw if track fails", () => {
|
||||
vi.stubGlobal("window", {
|
||||
umami: {
|
||||
track: () => { throw new Error("Blocked"); }
|
||||
}
|
||||
});
|
||||
expect(() => trackEvent("test")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { corsHeaders, handlePreflight, withCors } from "./cors";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
describe("corsHeaders", () => {
|
||||
it("should return empty object if no origin header", () => {
|
||||
const req = new Request("http://localhost");
|
||||
expect(corsHeaders(req)).toEqual({});
|
||||
});
|
||||
|
||||
it("should reflect origin and include marketplace headers", () => {
|
||||
const origin = "https://example.com";
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "origin": origin }
|
||||
});
|
||||
const headers = corsHeaders(req);
|
||||
expect(headers["Access-Control-Allow-Origin"]).toBe(origin);
|
||||
expect(headers["Access-Control-Allow-Private-Network"]).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("handlePreflight", () => {
|
||||
it("should return 204 with CORS headers", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "origin": "http://test.local" }
|
||||
});
|
||||
const resp = handlePreflight(req);
|
||||
expect(resp.status).toBe(204);
|
||||
expect(resp.headers.get("Access-Control-Allow-Origin")).toBe("http://test.local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("withCors", () => {
|
||||
it("should append CORS headers to existing response", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "origin": "http://test.local" }
|
||||
});
|
||||
const resp = NextResponse.json({ ok: true });
|
||||
const wrapped = withCors(resp, req);
|
||||
expect(wrapped.headers.get("Access-Control-Allow-Origin")).toBe("http://test.local");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
/** @vitest-environment node */
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import {
|
||||
issueMarketplaceToken,
|
||||
verifyMarketplaceToken,
|
||||
revokeMarketplaceToken
|
||||
} from "./marketplaceToken";
|
||||
|
||||
describe("Marketplace Tokens", () => {
|
||||
const originalSecret = process.env.AUTH_SECRET;
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.AUTH_SECRET = "test-secret-at-least-32-chars-long-!!!";
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
process.env.AUTH_SECRET = originalSecret;
|
||||
});
|
||||
|
||||
it("should issue and verify a valid token", async () => {
|
||||
const userId = "user-123";
|
||||
const token = await issueMarketplaceToken(userId);
|
||||
expect(token).toBeDefined();
|
||||
|
||||
const payload = await verifyMarketplaceToken(token);
|
||||
expect(payload.sub).toBe(userId);
|
||||
expect(payload.scope).toBe("marketplace");
|
||||
});
|
||||
|
||||
it("should throw if scope is incorrect", async () => {
|
||||
// We can't easily forge a token with wrong scope without re-implementing SignJWT
|
||||
// but we can test that verify fails on random strings
|
||||
await expect(verifyMarketplaceToken("invalid-token")).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("should handle token revocation", async () => {
|
||||
const token = await issueMarketplaceToken("user-1");
|
||||
const payload = await verifyMarketplaceToken(token);
|
||||
const jti = payload.jti!;
|
||||
|
||||
revokeMarketplaceToken(jti);
|
||||
|
||||
await expect(verifyMarketplaceToken(token)).rejects.toThrow("Token has been revoked");
|
||||
});
|
||||
|
||||
it("should throw if AUTH_SECRET is missing", async () => {
|
||||
const secret = process.env.AUTH_SECRET;
|
||||
delete process.env.AUTH_SECRET;
|
||||
|
||||
await expect(issueMarketplaceToken("u1")).rejects.toThrow("AUTH_SECRET is not set");
|
||||
|
||||
process.env.AUTH_SECRET = secret;
|
||||
});
|
||||
|
||||
it("should ignore empty jti in revoke", () => {
|
||||
expect(() => revokeMarketplaceToken("")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
getInstalledPlugins,
|
||||
isInstalled,
|
||||
upsertPlugin,
|
||||
uninstallPlugin,
|
||||
disablePlugin,
|
||||
enablePlugin,
|
||||
getDisabledPluginIds
|
||||
} from "./repository";
|
||||
import { prisma } from "../db";
|
||||
|
||||
vi.mock("../db", () => ({
|
||||
prisma: {
|
||||
installedPlugin: {
|
||||
findMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
describe("Marketplace Repository", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should get installed plugins", async () => {
|
||||
const mockData = [{ pluginId: "p1" }];
|
||||
(prisma.installedPlugin.findMany as any).mockResolvedValue(mockData);
|
||||
const result = await getInstalledPlugins();
|
||||
expect(result).toEqual(mockData);
|
||||
});
|
||||
|
||||
it("should check if installed", async () => {
|
||||
(prisma.installedPlugin.findFirst as any).mockResolvedValue({ pluginId: "p1" });
|
||||
expect(await isInstalled("p1")).toBe(true);
|
||||
|
||||
(prisma.installedPlugin.findFirst as any).mockResolvedValue(null);
|
||||
expect(await isInstalled("p2")).toBe(false);
|
||||
});
|
||||
|
||||
it("should upsert existing plugin", async () => {
|
||||
(prisma.installedPlugin.findFirst as any)
|
||||
.mockResolvedValueOnce({ pluginId: "p1" }) // exists
|
||||
.mockResolvedValueOnce({ pluginId: "p1", version: "2.0.0" }); // return updated
|
||||
|
||||
await upsertPlugin("p1", "2.0.0");
|
||||
expect(prisma.installedPlugin.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should create new plugin on upsert", async () => {
|
||||
(prisma.installedPlugin.findFirst as any).mockResolvedValue(null);
|
||||
await upsertPlugin("pnew", "1.0.0");
|
||||
expect(prisma.installedPlugin.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle uninstall", async () => {
|
||||
await uninstallPlugin("p1");
|
||||
expect(prisma.installedPlugin.deleteMany).toHaveBeenCalledWith({ where: { pluginId: "p1" } });
|
||||
});
|
||||
|
||||
it("should handle uninstall failure", async () => {
|
||||
(prisma.installedPlugin.deleteMany as any).mockRejectedValue(new Error("Fail"));
|
||||
const result = await uninstallPlugin("p1");
|
||||
expect(result).toBe(0);
|
||||
});
|
||||
|
||||
it("should disable existing plugin", async () => {
|
||||
(prisma.installedPlugin.findFirst as any).mockResolvedValue({ pluginId: "p1" });
|
||||
await disablePlugin("p1");
|
||||
expect(prisma.installedPlugin.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: { enabled: false }
|
||||
}));
|
||||
});
|
||||
|
||||
it("should create record for disabling built-in plugin", async () => {
|
||||
(prisma.installedPlugin.findFirst as any).mockResolvedValue(null);
|
||||
await disablePlugin("builtin-1");
|
||||
expect(prisma.installedPlugin.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ pluginId: "builtin-1", enabled: false })
|
||||
}));
|
||||
});
|
||||
|
||||
it("should enable plugin", async () => {
|
||||
await enablePlugin("p1");
|
||||
expect(prisma.installedPlugin.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: { enabled: true }
|
||||
}));
|
||||
});
|
||||
|
||||
it("should get disabled plugin IDs", async () => {
|
||||
(prisma.installedPlugin.findMany as any).mockResolvedValue([
|
||||
{ pluginId: "p1" },
|
||||
{ pluginId: "p2" }
|
||||
]);
|
||||
const ids = await getDisabledPluginIds();
|
||||
expect(ids).toBeInstanceOf(Set);
|
||||
expect(ids.has("p1")).toBe(true);
|
||||
expect(ids.size).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { seedDefaultPlugins } from "./seedDefaultPlugins";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getVerifiedPluginIds } from "./registryClient";
|
||||
import { upsertPlugin } from "./repository";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
setting: {
|
||||
findFirst: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
installedPlugin: {
|
||||
count: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./registryClient", () => ({
|
||||
getVerifiedPluginIds: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./repository", () => ({
|
||||
upsertPlugin: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/plugins/validateManifest", () => ({
|
||||
validateManifest: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock global fetch
|
||||
const mockFetch = vi.fn();
|
||||
global.fetch = mockFetch;
|
||||
|
||||
describe("seedDefaultPlugins", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.WWV_SKIP_DEFAULT_PLUGINS = "false";
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL = "https://market.test";
|
||||
|
||||
vi.mocked(getVerifiedPluginIds).mockResolvedValue(new Set(["aviation", "maritime"]));
|
||||
vi.mocked(validateManifest).mockReturnValue({ valid: true, errors: [] });
|
||||
});
|
||||
|
||||
it("should skip if WWV_SKIP_DEFAULT_PLUGINS is true", async () => {
|
||||
process.env.WWV_SKIP_DEFAULT_PLUGINS = "true";
|
||||
await seedDefaultPlugins();
|
||||
expect(prisma.setting.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ key: "defaults_seeded" })
|
||||
}));
|
||||
});
|
||||
|
||||
it("should skip if already seeded (guard found)", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue({ id: 1, key: "defaults_seeded", value: "true" } as any);
|
||||
await seedDefaultPlugins();
|
||||
expect(prisma.installedPlugin.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should skip if plugins already exist in database", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.installedPlugin.count).mockResolvedValue(5);
|
||||
await seedDefaultPlugins();
|
||||
expect(getVerifiedPluginIds).not.toHaveBeenCalled();
|
||||
expect(prisma.setting.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should seed verified plugins successfully", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.installedPlugin.count).mockResolvedValue(0);
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: "aviation", version: "1.0.0", name: "Aviation" }),
|
||||
});
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(upsertPlugin).toHaveBeenCalledWith(
|
||||
"aviation",
|
||||
"1.0.0",
|
||||
expect.stringContaining('"id":"aviation"')
|
||||
);
|
||||
expect(prisma.setting.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should skip unverified plugins", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.installedPlugin.count).mockResolvedValue(0);
|
||||
vi.mocked(getVerifiedPluginIds).mockResolvedValue(new Set(["other"]));
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(upsertPlugin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should skip if manifest is invalid", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.installedPlugin.count).mockResolvedValue(0);
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: "aviation" }),
|
||||
});
|
||||
vi.mocked(validateManifest).mockReturnValue({ valid: false, errors: ["bad"] });
|
||||
|
||||
const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(upsertPlugin).not.toHaveBeenCalled();
|
||||
expect(spy).toHaveBeenCalledWith(expect.stringContaining("Skipping aviation: bad"));
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle individual plugin failures and continue", async () => {
|
||||
vi.mocked(prisma.setting.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.installedPlugin.count).mockResolvedValue(0);
|
||||
|
||||
// aviation fails, maritime succeeds
|
||||
mockFetch
|
||||
.mockResolvedValueOnce({ ok: false, statusText: "Not Found" }) // aviation
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ id: "maritime", version: "2.0.0" }),
|
||||
}); // maritime
|
||||
|
||||
vi.mocked(getVerifiedPluginIds).mockResolvedValue(new Set(["aviation", "maritime"]));
|
||||
|
||||
const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
await seedDefaultPlugins();
|
||||
|
||||
// Should NOT have called upsert for aviation
|
||||
expect(upsertPlugin).not.toHaveBeenCalledWith("aviation", expect.any(String), expect.any(String));
|
||||
|
||||
// Should HAVE called upsert for maritime
|
||||
expect(upsertPlugin).toHaveBeenCalledWith(
|
||||
"maritime",
|
||||
"2.0.0",
|
||||
expect.any(String)
|
||||
);
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(expect.stringContaining("Failed to seed aviation"), expect.any(Error));
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("should catch and log outer errors", async () => {
|
||||
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
vi.mocked(prisma.setting.findFirst).mockImplementationOnce(() => {
|
||||
throw new Error("Fatal");
|
||||
});
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(expect.stringContaining("Fatal error during seeding"), expect.any(Error));
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -1,198 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks — must be declared before importing the module under test
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockFindFirst = vi.fn();
|
||||
const mockCount = vi.fn();
|
||||
const mockUpdateMany = vi.fn();
|
||||
const mockCreate = vi.fn();
|
||||
|
||||
vi.mock("../db", () => ({
|
||||
prisma: {
|
||||
setting: {
|
||||
findFirst: (...a: any[]) => mockFindFirst(...a),
|
||||
updateMany: (...a: any[]) => mockUpdateMany(...a),
|
||||
create: (...a: any[]) => mockCreate(...a),
|
||||
},
|
||||
installedPlugin: { count: (...a: any[]) => mockCount(...a) },
|
||||
},
|
||||
}));
|
||||
|
||||
const mockUpsertPlugin = vi.fn();
|
||||
vi.mock("./repository", () => ({ upsertPlugin: (...a: any[]) => mockUpsertPlugin(...a) }));
|
||||
|
||||
const mockValidateManifest = vi.fn();
|
||||
vi.mock("@/core/plugins/validateManifest", () => ({
|
||||
validateManifest: (...a: any[]) => mockValidateManifest(...a),
|
||||
}));
|
||||
|
||||
const mockGetVerifiedPluginIds = vi.fn();
|
||||
vi.mock("./registryClient", () => ({
|
||||
getVerifiedPluginIds: (...a: any[]) => mockGetVerifiedPluginIds(...a),
|
||||
}));
|
||||
|
||||
let mockIsDemo = false;
|
||||
vi.mock("@/core/edition", () => ({ get isDemo() { return mockIsDemo; } }));
|
||||
|
||||
// Mock global fetch for marketplace API calls
|
||||
const mockFetch = vi.fn();
|
||||
vi.stubGlobal("fetch", mockFetch);
|
||||
|
||||
import { seedDefaultPlugins } from "./seedDefaultPlugins";
|
||||
import { DEFAULT_PLUGIN_IDS } from "./defaultPlugins";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function fakeManifest(id: string) {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
version: "1.0.0",
|
||||
format: "bundle",
|
||||
entry: `https://unpkg.com/wwv-plugin-${id}@1.0.0/dist/frontend.mjs`,
|
||||
npmPackage: `wwv-plugin-${id}`,
|
||||
rendering: { type: "point", color: "#ff0000", size: 6 },
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("seedDefaultPlugins", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockIsDemo = false;
|
||||
delete process.env.WWV_SKIP_DEFAULT_PLUGINS;
|
||||
|
||||
// Defaults: not seeded, no existing plugins, manifests valid
|
||||
mockFindFirst.mockResolvedValue(null);
|
||||
mockCount.mockResolvedValue(0);
|
||||
mockGetVerifiedPluginIds.mockResolvedValue(new Set(DEFAULT_PLUGIN_IDS));
|
||||
mockValidateManifest.mockReturnValue({ valid: true, errors: [] });
|
||||
mockUpsertPlugin.mockResolvedValue({});
|
||||
mockCreate.mockResolvedValue({});
|
||||
mockUpdateMany.mockResolvedValue({});
|
||||
|
||||
mockFetch.mockImplementation(async (url: string) => ({
|
||||
ok: true,
|
||||
json: async () => {
|
||||
const match = url.match(/plugins\/(.+)$/);
|
||||
return match ? fakeManifest(match[1]) : {};
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
it("seeds all default plugins on a fresh install", async () => {
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockUpsertPlugin).toHaveBeenCalledTimes(DEFAULT_PLUGIN_IDS.length);
|
||||
for (const id of DEFAULT_PLUGIN_IDS) {
|
||||
expect(mockUpsertPlugin).toHaveBeenCalledWith(
|
||||
id,
|
||||
"1.0.0",
|
||||
expect.stringContaining(`"id":"${id}"`),
|
||||
);
|
||||
}
|
||||
|
||||
// Guard row written
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("skips immediately when already seeded", async () => {
|
||||
mockFindFirst.mockResolvedValue({ key: "defaults_seeded", value: "true" });
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks seeded without installing when plugins already exist", async () => {
|
||||
mockCount.mockResolvedValue(3);
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
// Guard row still written
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("handles marketplace API failure gracefully", async () => {
|
||||
mockFetch.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
// Should NOT throw
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
// Guard row still written (fail-safe)
|
||||
expect(mockCreate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips when WWV_SKIP_DEFAULT_PLUGINS=true", async () => {
|
||||
process.env.WWV_SKIP_DEFAULT_PLUGINS = "true";
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
// Guard row written so it doesn't re-check
|
||||
expect(mockCreate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips entirely on demo edition", async () => {
|
||||
mockIsDemo = true;
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips individual plugins with invalid manifests", async () => {
|
||||
// Make the first plugin fail validation
|
||||
let callCount = 0;
|
||||
mockValidateManifest.mockImplementation(() => {
|
||||
callCount++;
|
||||
if (callCount === 1) return { valid: false, errors: ["missing field"] };
|
||||
return { valid: true, errors: [] };
|
||||
});
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
// One fewer than total (the first was skipped)
|
||||
expect(mockUpsertPlugin).toHaveBeenCalledTimes(DEFAULT_PLUGIN_IDS.length - 1);
|
||||
});
|
||||
|
||||
it("stamps trust from the verified registry", async () => {
|
||||
const firstId = DEFAULT_PLUGIN_IDS[0];
|
||||
// Only the first plugin is verified
|
||||
mockGetVerifiedPluginIds.mockResolvedValue(new Set([firstId]));
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
// Check the first call has "verified"
|
||||
const firstCall = mockUpsertPlugin.mock.calls[0];
|
||||
expect(firstCall[0]).toBe(firstId);
|
||||
const firstManifest = JSON.parse(firstCall[2]);
|
||||
expect(firstManifest.trust).toBe("verified");
|
||||
|
||||
// Check a non-verified one
|
||||
const secondCall = mockUpsertPlugin.mock.calls[1];
|
||||
const secondManifest = JSON.parse(secondCall[2]);
|
||||
expect(secondManifest.trust).toBe("unverified");
|
||||
});
|
||||
});
|
||||
@@ -1,32 +1,20 @@
|
||||
import { prisma } from "../db";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { DEFAULT_PLUGIN_IDS } from "./defaultPlugins";
|
||||
import { getVerifiedPluginIds } from "./registryClient";
|
||||
import { upsertPlugin } from "./repository";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
import { getVerifiedPluginIds } from "./registryClient";
|
||||
import { PluginManifest } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
const MARKETPLACE_URL =
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL ||
|
||||
"https://marketplace.worldwideview.dev";
|
||||
const MARKETPLACE_URL = process.env.NEXT_PUBLIC_MARKETPLACE_URL;
|
||||
|
||||
/**
|
||||
* Seed default marketplace plugins on a fresh install.
|
||||
*
|
||||
* Runs once per instance lifecycle — an idempotent guard
|
||||
* (`defaults_seeded` in the Setting table) prevents re-runs.
|
||||
*
|
||||
* Like the "sample data" that ships with a new app: the seeder
|
||||
* writes records to the database on first boot, then never runs again.
|
||||
*
|
||||
* Errors are logged but never thrown — a failed seed must never
|
||||
* block the application from starting.
|
||||
* Seeds default verified plugins into the local database on first run.
|
||||
* This ensures common layers like ISS, Aircraft, and Maritime are available immediately.
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function seedDefaultPlugins(): Promise<void> {
|
||||
try {
|
||||
// Demo has its own mechanism (NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS)
|
||||
if (isDemo) return;
|
||||
|
||||
// Opt-out for power users deploying fresh instances
|
||||
if (process.env.WWV_SKIP_DEFAULT_PLUGINS === "true") {
|
||||
await markSeeded();
|
||||
return;
|
||||
@@ -39,8 +27,8 @@ export async function seedDefaultPlugins(): Promise<void> {
|
||||
if (guard) return;
|
||||
|
||||
// Not truly fresh if plugins already exist
|
||||
const existing = await prisma.installedPlugin.count();
|
||||
if (existing > 0) {
|
||||
const count = await prisma.installedPlugin.count();
|
||||
if (count > 0) {
|
||||
await markSeeded();
|
||||
return;
|
||||
}
|
||||
@@ -50,25 +38,19 @@ export async function seedDefaultPlugins(): Promise<void> {
|
||||
);
|
||||
|
||||
const verified = await getVerifiedPluginIds();
|
||||
let installed = 0;
|
||||
|
||||
for (const pluginId of DEFAULT_PLUGIN_IDS) {
|
||||
try {
|
||||
if (!pluginId) continue;
|
||||
|
||||
if (!verified.has(pluginId)) {
|
||||
// Only seed official verified plugins by default
|
||||
continue;
|
||||
}
|
||||
|
||||
const manifest = await fetchManifest(pluginId);
|
||||
if (!manifest) continue;
|
||||
|
||||
// Server-side trust stamping
|
||||
manifest.trust = verified.has(pluginId)
|
||||
? "verified"
|
||||
: "unverified";
|
||||
|
||||
// Reconstruct CDN entry for npm-distributed plugins
|
||||
if (manifest.npmPackage) {
|
||||
const ver = manifest.version || "1.0.0";
|
||||
manifest.format = "bundle";
|
||||
manifest.entry = `https://unpkg.com/${manifest.npmPackage}@${ver}/dist/frontend.mjs`;
|
||||
}
|
||||
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
console.warn(
|
||||
@@ -77,65 +59,50 @@ export async function seedDefaultPlugins(): Promise<void> {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Correct signature: id, version, config
|
||||
await upsertPlugin(
|
||||
pluginId,
|
||||
manifest.version || "1.0.0",
|
||||
JSON.stringify(manifest),
|
||||
pluginId,
|
||||
manifest.version || "1.0.0",
|
||||
JSON.stringify(manifest)
|
||||
);
|
||||
installed++;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[DefaultPlugins] Failed to seed ${pluginId}:`,
|
||||
err,
|
||||
);
|
||||
console.warn(`[DefaultPlugins] Failed to seed ${pluginId}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
await markSeeded();
|
||||
console.log(
|
||||
`[DefaultPlugins] Seeded ${installed}/${DEFAULT_PLUGIN_IDS.length} plugins`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[DefaultPlugins] Seeder failed:", err);
|
||||
// Never throw — seeding failure must not block the app
|
||||
console.log("[DefaultPlugins] Successfully seeded default plugins.");
|
||||
} catch (error) {
|
||||
console.error("[DefaultPlugins] Fatal error during seeding:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetch a plugin manifest from the marketplace API. */
|
||||
async function fetchManifest(
|
||||
pluginId: string,
|
||||
): Promise<Record<string, any> | null> {
|
||||
/**
|
||||
* Records that the seeding process has completed.
|
||||
*/
|
||||
async function markSeeded() {
|
||||
const existing = await prisma.setting.findFirst({
|
||||
where: { key: "defaults_seeded" }
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
await prisma.setting.create({
|
||||
data: { key: "defaults_seeded", value: "true" }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a plugin manifest from the official marketplace.
|
||||
*/
|
||||
async function fetchManifest(pluginId: string): Promise<PluginManifest> {
|
||||
try {
|
||||
const res = await fetch(`${MARKETPLACE_URL}/api/plugins/${pluginId}`);
|
||||
if (!res.ok) {
|
||||
console.warn(
|
||||
`[DefaultPlugins] Marketplace returned ${res.status} for ${pluginId}`,
|
||||
);
|
||||
return null;
|
||||
throw new Error(`Failed to fetch manifest for ${pluginId}: ${res.statusText}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!data.id) data.id = pluginId;
|
||||
return data;
|
||||
return await res.json();
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[DefaultPlugins] Network error fetching ${pluginId}:`,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Write the idempotent guard row. */
|
||||
async function markSeeded(): Promise<void> {
|
||||
const existing = await prisma.setting.findFirst({ where: { key: "defaults_seeded" } });
|
||||
if (existing) {
|
||||
await prisma.setting.updateMany({
|
||||
where: { key: "defaults_seeded" },
|
||||
data: { value: "true" },
|
||||
});
|
||||
} else {
|
||||
await prisma.setting.create({
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { getRequestOrigin } from "./origin";
|
||||
|
||||
describe("getRequestOrigin", () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
process.env = { ...originalEnv };
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should prioritize x-forwarded-host", () => {
|
||||
const headers = new Map([
|
||||
["x-forwarded-host", "myapp.com"],
|
||||
["x-forwarded-proto", "https"]
|
||||
]);
|
||||
const mockRequest: any = {
|
||||
headers: { get: (key: string) => headers.get(key) },
|
||||
nextUrl: { origin: "http://0.0.0.0:3000" },
|
||||
url: "http://0.0.0.0:3000/api"
|
||||
};
|
||||
|
||||
const origin = getRequestOrigin(mockRequest);
|
||||
expect(origin).toBe("https://myapp.com");
|
||||
});
|
||||
|
||||
it("should fall back to host header if no forwarded host", () => {
|
||||
const headers = new Map([
|
||||
["host", "localhost:3000"]
|
||||
]);
|
||||
const mockRequest: any = {
|
||||
headers: { get: (key: string) => headers.get(key) },
|
||||
nextUrl: { origin: "http://0.0.0.0:3000" },
|
||||
};
|
||||
|
||||
const origin = getRequestOrigin(mockRequest);
|
||||
expect(origin).toBe("http://localhost:3000");
|
||||
});
|
||||
|
||||
it("should fall back to env var if headers are missing or invalid", () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = "https://cloud.wwv.dev";
|
||||
const headers = new Map([
|
||||
["host", "0.0.0.0:3000"]
|
||||
]);
|
||||
const mockRequest: any = {
|
||||
headers: { get: (key: string) => headers.get(key) },
|
||||
nextUrl: { origin: "http://0.0.0.0:3000" },
|
||||
};
|
||||
|
||||
const origin = getRequestOrigin(mockRequest);
|
||||
expect(origin).toBe("https://cloud.wwv.dev");
|
||||
});
|
||||
|
||||
it("should replace 0.0.0.0 with localhost as last resort", () => {
|
||||
const mockRequest: any = {
|
||||
headers: { get: () => null },
|
||||
nextUrl: { origin: "http://0.0.0.0:3000" },
|
||||
};
|
||||
|
||||
const origin = getRequestOrigin(mockRequest);
|
||||
expect(origin).toBe("http://localhost:3000");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { RateLimiter, getClientIp } from "./rateLimit";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
describe("RateLimiter", () => {
|
||||
let limiter: RateLimiter;
|
||||
const windowMs = 1000;
|
||||
const maxRequests = 2;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
limiter = new RateLimiter({ windowMs, maxRequests });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
limiter.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("should allow requests within limit", () => {
|
||||
expect(limiter.check("user-1")).toBeNull();
|
||||
expect(limiter.check("user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("should block requests exceeding limit", () => {
|
||||
limiter.check("user-1");
|
||||
limiter.check("user-1");
|
||||
const response = limiter.check("user-1");
|
||||
|
||||
expect(response).toBeInstanceOf(NextResponse);
|
||||
expect(response?.status).toBe(429);
|
||||
});
|
||||
|
||||
it("should reset limit after window expires", () => {
|
||||
limiter.check("user-1");
|
||||
limiter.check("user-1");
|
||||
expect(limiter.check("user-1")).not.toBeNull();
|
||||
|
||||
vi.advanceTimersByTime(windowMs + 1);
|
||||
|
||||
expect(limiter.check("user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("should clean up expired entries periodically", () => {
|
||||
limiter.check("user-1");
|
||||
vi.advanceTimersByTime(windowMs + 1);
|
||||
|
||||
// Trigger cleanup (scheduled at windowMs * 2)
|
||||
vi.advanceTimersByTime(windowMs);
|
||||
|
||||
const store = (limiter as any).store;
|
||||
expect(store.has("user-1")).toBe(false);
|
||||
});
|
||||
|
||||
it("should clear timer on destroy", () => {
|
||||
const clearIntervalSpy = vi.spyOn(global, "clearInterval");
|
||||
limiter.destroy();
|
||||
expect(clearIntervalSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClientIp", () => {
|
||||
it("should prefer x-forwarded-for first IP", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-forwarded-for": "1.2.3.4, 5.6.7.8" }
|
||||
});
|
||||
expect(getClientIp(req)).toBe("1.2.3.4");
|
||||
});
|
||||
|
||||
it("should fallback to x-real-ip", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-real-ip": "9.9.9.9" }
|
||||
});
|
||||
expect(getClientIp(req)).toBe("9.9.9.9");
|
||||
});
|
||||
|
||||
it("should return unknown if no headers present", () => {
|
||||
const req = new Request("http://localhost");
|
||||
expect(getClientIp(req)).toBe("unknown");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user