perf: optimize dashboard loading and builds
This commit is contained in:
135 files changed
+8521
-1718
No files matched your search
@@ -11,8 +11,9 @@
|
||||
"./client": "./src/client.ts",
|
||||
"./board-server": "./src/board-server.ts",
|
||||
"./query-cache": "./src/query-cache.ts",
|
||||
"./server-settings-server": "./src/server-settings-server.ts",
|
||||
"./user-server": "./src/user-server.ts",
|
||||
"./server": "./src/server.ts",
|
||||
"./widget-prefetch-server": "./src/widget-prefetch-server.ts",
|
||||
"./websocket": "./src/websocket.ts",
|
||||
"./shared": "./src/shared.ts",
|
||||
"./open-api": "./src/open-api.ts",
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { createRscTrpcContext } from "./rsc-context";
|
||||
import { boardRouter } from "./router/board";
|
||||
|
||||
const createBoardCallerAsync = async () => boardRouter.createCaller(await createRscTrpcContext());
|
||||
|
||||
export const getBoardByNameAsync = async (name: string) => {
|
||||
export const getBoardByNameAsync = cache(async (name: string) => {
|
||||
const caller = await createBoardCallerAsync();
|
||||
return await caller.getBoardByName({ name });
|
||||
};
|
||||
});
|
||||
|
||||
export const getHomeBoardAsync = async () => {
|
||||
export const getHomeBoardAsync = cache(async () => {
|
||||
const caller = await createBoardCallerAsync();
|
||||
return await caller.getHomeBoard();
|
||||
};
|
||||
});
|
||||
@@ -1,22 +1,54 @@
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
|
||||
export const queryCacheDefaultStaleTimeMs = 0;
|
||||
// RSC-prefetched data must survive the hydration pass without an immediate
|
||||
// duplicate fetch. Widget-specific intervals still control live refreshes.
|
||||
export const queryCacheDefaultStaleTimeMs = 30_000;
|
||||
export const queryCacheDefaultRefetchIntervalMs = 30_000;
|
||||
export const queryCacheDefaultGcTimeMs = 1000 * 60 * 60 * 24;
|
||||
export const queryCacheMaxValueBytes = 1024 * 1024;
|
||||
export const queryCacheStoragePrefix = "homarr-widget-query";
|
||||
export const queryCacheBuster = "v2-superjson";
|
||||
export const queryCacheDefaultGcTimeMs = 1000 * 60 * 5;
|
||||
export const queryCacheMetadataStaleTimeMs = 1000 * 60 * 5;
|
||||
|
||||
let activeQueryCacheBoardId: string | null = null;
|
||||
const widgetDataQueryPaths = new Set(["app.byId", "app.byIds", "docker.getContainers", "integration.byIds"]);
|
||||
const excludedWidgetPaths = new Set(["widget.app.ping", "widget.beszel.getSystemStats"]);
|
||||
|
||||
export const setActiveQueryCacheBoardId = (boardId: string | null) => {
|
||||
activeQueryCacheBoardId = boardId;
|
||||
export const isWidgetDataTrpcPath = (path: string) => {
|
||||
if (path.startsWith("widget.")) return !excludedWidgetPaths.has(path);
|
||||
return widgetDataQueryPaths.has(path);
|
||||
};
|
||||
|
||||
export const getActiveQueryCacheBoardId = () => activeQueryCacheBoardId;
|
||||
|
||||
const persistableQueryPaths = new Set(["app.byId", "app.byIds", "docker.getContainers", "integration.byIds"]);
|
||||
const excludedWidgetPaths = new Set(["widget.app.ping", "widget.beszel.getSystemStats"]);
|
||||
// These supporting queries can be numerous on a dashboard. Give them a
|
||||
// predictable refresh policy instead of refetching all of them after every tab
|
||||
// focus/reconnect event. Metadata can refresh after a bounded stale window;
|
||||
// Docker state remains live on a single shared timer.
|
||||
export const dashboardSupportingQueryPolicies = [
|
||||
{
|
||||
queryKey: [["app", "byId"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["app", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["integration", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["docker", "getContainers"]],
|
||||
refetchInterval: queryCacheDefaultRefetchIntervalMs,
|
||||
staleTime: queryCacheDefaultStaleTimeMs,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
},
|
||||
] as const;
|
||||
|
||||
const getTrpcPathFromQueryKey = (queryKey: QueryKey) => {
|
||||
const first = queryKey[0];
|
||||
@@ -26,11 +58,9 @@ const getTrpcPathFromQueryKey = (queryKey: QueryKey) => {
|
||||
return parts.length > 0 ? parts : null;
|
||||
};
|
||||
|
||||
export const isPersistableWidgetQueryKey = (queryKey: QueryKey) => {
|
||||
export const isWidgetDataQueryKey = (queryKey: QueryKey) => {
|
||||
const path = getTrpcPathFromQueryKey(queryKey);
|
||||
if (!path) return false;
|
||||
|
||||
if (path[0] === "widget") return !excludedWidgetPaths.has(path.join("."));
|
||||
|
||||
return persistableQueryPaths.has(path.join("."));
|
||||
return isWidgetDataTrpcPath(path.join("."));
|
||||
};
|
||||
@@ -24,7 +24,6 @@ export const appRouter = createTRPCRouter({
|
||||
cronJobs: lazy(() => import("./router/cron-jobs").then((mod) => mod.cronJobsRouter)),
|
||||
apiKeys: lazy(() => import("./router/apiKeys").then((mod) => mod.apiKeysRouter)),
|
||||
media: lazy(() => import("./router/medias/media-router").then((mod) => mod.mediaRouter)),
|
||||
queryCache: lazy(() => import("./router/query-cache").then((mod) => mod.queryCacheRouter)),
|
||||
updateChecker: lazy(() => import("./router/update-checker").then((mod) => mod.updateCheckerRouter)),
|
||||
certificates: lazy(() => import("./router/certificates/certificate-router").then((mod) => mod.certificateRouter)),
|
||||
bangs: lazy(() => import("./router/bangs/bangs-router").then((mod) => mod.bangsRouter)),
|
||||
|
||||
@@ -1757,9 +1757,12 @@ const getElementsForLayout = (board: Awaited<ReturnType<typeof getFullBoardWithW
|
||||
};
|
||||
|
||||
const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, userId: string | null) => {
|
||||
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, userId ?? ""),
|
||||
});
|
||||
const groupPermissionWhere = userId
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
db.select({ groupId: groupMembers.groupId }).from(groupMembers).where(eq(groupMembers.userId, userId)),
|
||||
)
|
||||
: eq(boardGroupPermissions.groupId, "");
|
||||
const board = await db.query.boards.findFirst({
|
||||
where,
|
||||
with: {
|
||||
@@ -1782,8 +1785,8 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
items: {
|
||||
with: {
|
||||
integrations: {
|
||||
with: {
|
||||
integration: true,
|
||||
columns: {
|
||||
integrationId: true,
|
||||
},
|
||||
},
|
||||
layouts: true,
|
||||
@@ -1797,7 +1800,7 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
},
|
||||
},
|
||||
groupPermissions: {
|
||||
where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1845,7 +1848,7 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
layoutId: layout.layoutId,
|
||||
sectionId: layout.sectionId,
|
||||
})),
|
||||
integrationIds: itemIntegrations.map((item) => item.integration.id),
|
||||
integrationIds: itemIntegrations.map((item) => item.integrationId),
|
||||
advancedOptions: superjson.parse<BoardItemAdvancedOptions>(item.advancedOptions),
|
||||
options: superjson.parse<Record<string, unknown>>(item.options),
|
||||
}),
|
||||
|
||||
@@ -19,9 +19,12 @@ export const throwIfActionForbiddenAsync = async (
|
||||
permission: BoardPermission,
|
||||
) => {
|
||||
const { db, session } = ctx;
|
||||
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, session?.user.id ?? ""),
|
||||
});
|
||||
const groupPermissionWhere = session
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
db.select({ groupId: groupMembers.groupId }).from(groupMembers).where(eq(groupMembers.userId, session.user.id)),
|
||||
)
|
||||
: eq(boardGroupPermissions.groupId, "");
|
||||
const board = await db.query.boards.findFirst({
|
||||
where: boardWhere,
|
||||
columns: {
|
||||
@@ -34,7 +37,7 @@ export const throwIfActionForbiddenAsync = async (
|
||||
where: eq(boardUserPermissions.userId, session?.user.id ?? ""),
|
||||
},
|
||||
groupPermissions: {
|
||||
where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards } from "@homarr/db/schema";
|
||||
import { removeQueryCacheAsync, setQueryCacheAsync } from "@homarr/redis";
|
||||
|
||||
import { queryCacheDefaultGcTimeMs, queryCacheMaxValueBytes } from "../query-cache";
|
||||
import { createTRPCRouter, internalProcedure } from "../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "./board/board-access";
|
||||
|
||||
const queryCacheBoardInput = z.object({
|
||||
boardId: z.string().min(1),
|
||||
});
|
||||
|
||||
const queryCacheSetInput = queryCacheBoardInput.extend({
|
||||
value: z.string().max(queryCacheMaxValueBytes * 2),
|
||||
});
|
||||
|
||||
const validateBoardAccessAsync = async (ctx: Parameters<typeof throwIfActionForbiddenAsync>[0], boardId: string) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, boardId), "view");
|
||||
};
|
||||
|
||||
export const queryCacheRouter = createTRPCRouter({
|
||||
setItem: internalProcedure.input(queryCacheSetInput).mutation(async ({ ctx, input }) => {
|
||||
await validateBoardAccessAsync(ctx, input.boardId);
|
||||
const userId = ctx.session?.user.id ?? "anonymous";
|
||||
return {
|
||||
stored: await setQueryCacheAsync(
|
||||
userId,
|
||||
input.boardId,
|
||||
input.value,
|
||||
queryCacheDefaultGcTimeMs,
|
||||
queryCacheMaxValueBytes,
|
||||
),
|
||||
};
|
||||
}),
|
||||
removeItem: internalProcedure.input(queryCacheBoardInput).mutation(async ({ ctx, input }) => {
|
||||
await validateBoardAccessAsync(ctx, input.boardId);
|
||||
const userId = ctx.session?.user.id ?? "anonymous";
|
||||
await removeQueryCacheAsync(userId, input.boardId);
|
||||
}),
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import SuperJSON from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { env } from "@homarr/common/env";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { eq } from "@homarr/db";
|
||||
import { items, users } from "@homarr/db/schema";
|
||||
@@ -20,6 +21,8 @@ const feedsInput = z.object({
|
||||
|
||||
export const rssFeedRouter = createTRPCRouter({
|
||||
getFeeds: publicProcedure.input(feedsInput).query(async ({ ctx, input }) => {
|
||||
if (env.NO_EXTERNAL_CONNECTION) return [];
|
||||
|
||||
const urls = (await canAccessAllFeedsAsync(ctx.db, ctx.session))
|
||||
? input.urls
|
||||
: await restrictUrlsAsync(ctx.db, input.urls);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { env } from "@homarr/common/env";
|
||||
import { weatherRequestHandler } from "@homarr/request-handler/weather";
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
@@ -11,6 +12,8 @@ const atLocationInput = z.object({
|
||||
|
||||
export const weatherRouter = createTRPCRouter({
|
||||
atLocation: publicProcedure.input(atLocationInput).query(async ({ input }) => {
|
||||
if (env.NO_EXTERNAL_CONNECTION) return null;
|
||||
|
||||
const handler = weatherRequestHandler.handler(input);
|
||||
return await handler.getDataAsync().then((result) => result.data);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { db } from "@homarr/db";
|
||||
import { getServerSettingsAsync } from "@homarr/db/queries";
|
||||
|
||||
// One settings snapshot per RSC request, shared by the root layout, theme, and
|
||||
// widget prefetching. React invalidates this cache between requests.
|
||||
export const getRscServerSettingsAsync = cache(async () => await getServerSettingsAsync(db));
|
||||
@@ -1,65 +1,20 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { boards, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import {
|
||||
isPersistableWidgetQueryKey,
|
||||
dashboardSupportingQueryPolicies,
|
||||
isWidgetDataQueryKey,
|
||||
isWidgetDataTrpcPath,
|
||||
queryCacheDefaultRefetchIntervalMs,
|
||||
queryCacheDefaultStaleTimeMs,
|
||||
queryCacheMaxValueBytes,
|
||||
queryCacheMetadataStaleTimeMs,
|
||||
} from "@homarr/api/query-cache";
|
||||
|
||||
import { queryCacheRouter } from "../router/query-cache";
|
||||
|
||||
const redisMock = vi.hoisted(() => {
|
||||
const values = new Map<string, string>();
|
||||
|
||||
return {
|
||||
values,
|
||||
setQueryCacheAsync: vi.fn(
|
||||
async (_userId: string, _boardId: string, value: string, _ttlMs: number, maxValueBytes: number) => {
|
||||
if (Buffer.byteLength(value, "utf8") > maxValueBytes) return false;
|
||||
values.set(`${_userId}:${_boardId}`, value);
|
||||
return true;
|
||||
},
|
||||
),
|
||||
removeQueryCacheAsync: vi.fn(async (_userId: string, _boardId: string) => {
|
||||
values.delete(`${_userId}:${_boardId}`);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@homarr/redis", () => ({
|
||||
setQueryCacheAsync: redisMock.setQueryCacheAsync,
|
||||
removeQueryCacheAsync: redisMock.removeQueryCacheAsync,
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
redisMock.values.clear();
|
||||
redisMock.setQueryCacheAsync.mockClear();
|
||||
redisMock.removeQueryCacheAsync.mockClear();
|
||||
});
|
||||
|
||||
const createSession = (userId = createId()): Session => ({
|
||||
user: {
|
||||
id: userId,
|
||||
permissions: [],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const insertUserAsync = async (db: Database, id: string) => {
|
||||
await db.insert(users).values({ id });
|
||||
};
|
||||
|
||||
describe("isPersistableWidgetQueryKey", () => {
|
||||
describe("isWidgetDataQueryKey", () => {
|
||||
test.each([
|
||||
[[["widget", "calendar", "findAllEvents"], { type: "query" }], true],
|
||||
[[["app", "byId"], { type: "query" }], true],
|
||||
@@ -72,77 +27,22 @@ describe("isPersistableWidgetQueryKey", () => {
|
||||
[[["app", "selectable"], { type: "query" }], false],
|
||||
[[["board", "getBoardByName"], { type: "query" }], false],
|
||||
[["widget"], false],
|
||||
])("matches persist filter for %j", (queryKey, expected) => {
|
||||
expect(isPersistableWidgetQueryKey(queryKey)).toBe(expected);
|
||||
])("matches widget data queries for %j", (queryKey, expected) => {
|
||||
expect(isWidgetDataQueryKey(queryKey)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("queryCacheRouter", () => {
|
||||
test("stores and removes data for a board viewer", async () => {
|
||||
const db = createDb();
|
||||
const session = createSession();
|
||||
await insertUserAsync(db, session.user.id);
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: session.user.id, isPublic: false });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session });
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value: "cached-value" })).resolves.toEqual({
|
||||
stored: true,
|
||||
});
|
||||
expect(redisMock.setQueryCacheAsync).toHaveBeenCalledWith(
|
||||
session.user.id,
|
||||
"board-1",
|
||||
"cached-value",
|
||||
expect.any(Number),
|
||||
queryCacheMaxValueBytes,
|
||||
);
|
||||
|
||||
await caller.removeItem({ boardId: "board-1" });
|
||||
expect(redisMock.removeQueryCacheAsync).toHaveBeenCalledWith(session.user.id, "board-1");
|
||||
});
|
||||
|
||||
test("does not touch Redis when board access is denied", async () => {
|
||||
const db = createDb();
|
||||
await insertUserAsync(db, "owner");
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: "owner", isPublic: false });
|
||||
|
||||
redisMock.setQueryCacheAsync.mockClear();
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session: createSession("other-user") });
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value: "cached-value" })).rejects.toThrow("Board not found");
|
||||
expect(redisMock.setQueryCacheAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("scopes anonymous public-board cache entries by anonymous user", async () => {
|
||||
const db = createDb();
|
||||
await insertUserAsync(db, "owner");
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: "owner", isPublic: true });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await caller.setItem({ boardId: "board-1", value: "cached-value" });
|
||||
|
||||
expect(redisMock.setQueryCacheAsync).toHaveBeenCalledWith(
|
||||
"anonymous",
|
||||
"board-1",
|
||||
"cached-value",
|
||||
expect.any(Number),
|
||||
queryCacheMaxValueBytes,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects oversized values", async () => {
|
||||
const db = createDb();
|
||||
const session = createSession("user-1");
|
||||
await insertUserAsync(db, session.user.id);
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: session.user.id, isPublic: false });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session });
|
||||
const value = "x".repeat(queryCacheMaxValueBytes + 1);
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value })).resolves.toEqual({
|
||||
stored: false,
|
||||
});
|
||||
describe("isWidgetDataTrpcPath", () => {
|
||||
test.each([
|
||||
["widget.calendar.findAllEvents", true],
|
||||
["app.byIds", true],
|
||||
["integration.byIds", true],
|
||||
["docker.getContainers", true],
|
||||
["widget.app.ping", false],
|
||||
["widget.beszel.getSystemStats", false],
|
||||
["board.getBoardByName", false],
|
||||
])("classifies dashboard data path %s", (path, expected) => {
|
||||
expect(isWidgetDataTrpcPath(path)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -176,3 +76,38 @@ describe("query cache stale handling", () => {
|
||||
expect(queryFn).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dashboard supporting query policies", () => {
|
||||
test("bounds metadata staleness without adding per-widget timers", () => {
|
||||
expect(dashboardSupportingQueryPolicies).toEqual([
|
||||
{
|
||||
queryKey: [["app", "byId"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["app", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["integration", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["docker", "getContainers"]],
|
||||
refetchInterval: queryCacheDefaultRefetchIntervalMs,
|
||||
staleTime: queryCacheDefaultStaleTimeMs,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { db, eq } from "@homarr/db";
|
||||
import { users } from "@homarr/db/schema";
|
||||
|
||||
// Keep the authenticated user lookup shared across nested RSC layouts. React
|
||||
// clears this memo between requests, so authorization changes cannot leak.
|
||||
export const getRscUserSettingsAsync = cache(async (userId: string) =>
|
||||
db.query.users.findFirst({
|
||||
columns: {
|
||||
homeBoardId: true,
|
||||
mobileHomeBoardId: true,
|
||||
firstDayOfWeek: true,
|
||||
pingIconsEnabled: true,
|
||||
enableRightClickOnWidgets: true,
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
},
|
||||
where: eq(users.id, userId),
|
||||
}),
|
||||
);
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createRscTrpcContext } from "./rsc-context";
|
||||
import { downloadsRouter } from "./router/widgets/downloads";
|
||||
|
||||
export const getDownloadJobsAndStatusesAsync = async (input: {
|
||||
integrationIds: string[];
|
||||
limitPerIntegration: number;
|
||||
}) => {
|
||||
// Keep this leaf caller narrow: the shared server caller imports the complete app router into every widget-prefetch build.
|
||||
const caller = downloadsRouter.createCaller(await createRscTrpcContext());
|
||||
return await caller.getJobsAndStatuses(input);
|
||||
};
|
||||
+13
-16
@@ -3,24 +3,18 @@ import type { NextAuthConfig } from "next-auth";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { eq, inArray } from "@homarr/db";
|
||||
import { eq } from "@homarr/db";
|
||||
import { groupMembers, groupPermissions, users } from "@homarr/db/schema";
|
||||
import { getPermissionsWithChildren } from "@homarr/definitions";
|
||||
|
||||
export const getCurrentUserPermissionsAsync = async (db: Database, userId: string) => {
|
||||
const dbGroupMembers = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, userId),
|
||||
});
|
||||
const groupIds = dbGroupMembers.map((groupMember) => groupMember.groupId);
|
||||
|
||||
if (groupIds.length === 0) return [];
|
||||
|
||||
const dbGroupPermissions = await db
|
||||
.selectDistinct({
|
||||
permission: groupPermissions.permission,
|
||||
})
|
||||
.from(groupPermissions)
|
||||
.where(inArray(groupPermissions.groupId, groupIds));
|
||||
.innerJoin(groupMembers, eq(groupPermissions.groupId, groupMembers.groupId))
|
||||
.where(eq(groupMembers.userId, userId));
|
||||
const permissionKeys = dbGroupPermissions.map(({ permission }) => permission);
|
||||
|
||||
return getPermissionsWithChildren(permissionKeys);
|
||||
@@ -43,12 +37,15 @@ export const createSessionAsync = async (
|
||||
|
||||
export const createSessionCallback = (db: Database): NextAuthCallbackOf<"session"> => {
|
||||
return async ({ session, user }) => {
|
||||
const additionalProperties = await db.query.users.findFirst({
|
||||
where: eq(users.id, user.id),
|
||||
columns: {
|
||||
colorScheme: true,
|
||||
},
|
||||
});
|
||||
const [additionalProperties, permissions] = await Promise.all([
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, user.id),
|
||||
columns: {
|
||||
colorScheme: true,
|
||||
},
|
||||
}),
|
||||
getCurrentUserPermissionsAsync(db, user.id),
|
||||
]);
|
||||
|
||||
return {
|
||||
...session,
|
||||
@@ -57,7 +54,7 @@ export const createSessionCallback = (db: Database): NextAuthCallbackOf<"session
|
||||
...additionalProperties,
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
permissions: await getCurrentUserPermissionsAsync(db, user.id),
|
||||
permissions,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -3,14 +3,9 @@
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
import type { IntegrationKind } from "@homarr/definitions";
|
||||
|
||||
interface IntegrationContextProps {
|
||||
integrations: {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
kind: IntegrationKind;
|
||||
permissions: {
|
||||
hasFullAccess: boolean;
|
||||
hasInteractAccess: boolean;
|
||||
|
||||
@@ -6,31 +6,28 @@ import { groupMembers, integrationGroupPermissions, integrationUserPermissions }
|
||||
import { constructIntegrationPermissions } from "./integration-permissions";
|
||||
|
||||
export const getIntegrationsWithPermissionsAsync = async (session: Session | null) => {
|
||||
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, session?.user.id ?? ""),
|
||||
});
|
||||
const integrations = await db.query.integrations.findMany({
|
||||
const groupPermissionWhere = session
|
||||
? inArray(
|
||||
integrationGroupPermissions.groupId,
|
||||
db.select({ groupId: groupMembers.groupId }).from(groupMembers).where(eq(groupMembers.userId, session.user.id)),
|
||||
)
|
||||
: eq(integrationGroupPermissions.groupId, "");
|
||||
const integrationRows = await db.query.integrations.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
url: true,
|
||||
kind: true,
|
||||
},
|
||||
with: {
|
||||
userPermissions: {
|
||||
where: eq(integrationUserPermissions.userId, session?.user.id ?? ""),
|
||||
},
|
||||
groupPermissions: {
|
||||
where: inArray(
|
||||
integrationGroupPermissions.groupId,
|
||||
groupsOfCurrentUser.map((group) => group.groupId),
|
||||
),
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return integrations.map(({ userPermissions, groupPermissions, ...integration }) => ({
|
||||
...integration,
|
||||
return integrationRows.map(({ id, userPermissions, groupPermissions }) => ({
|
||||
id,
|
||||
permissions: constructIntegrationPermissions({ userPermissions, groupPermissions }, session),
|
||||
}));
|
||||
};
|
||||
@@ -6,7 +6,6 @@ import { usePathname } from "next/navigation";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getActiveQueryCacheBoardId, setActiveQueryCacheBoardId } from "@homarr/api/query-cache";
|
||||
|
||||
import { updateBoardName } from "./updater";
|
||||
|
||||
@@ -36,16 +35,6 @@ export const BoardProvider = ({
|
||||
};
|
||||
}, [pathname, utils, initialBoard.name]);
|
||||
|
||||
useEffect(() => {
|
||||
setActiveQueryCacheBoardId(data.id);
|
||||
|
||||
return () => {
|
||||
if (getActiveQueryCacheBoardId() === data.id) {
|
||||
setActiveQueryCacheBoardId(null);
|
||||
}
|
||||
};
|
||||
}, [data.id]);
|
||||
|
||||
return (
|
||||
<BoardContext.Provider
|
||||
value={{
|
||||
|
||||
@@ -27,7 +27,7 @@ export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly Integ
|
||||
healthMonitoring: getIntegrationKindsByCategory("healthMonitoring").filter((kind) => kind !== "patchmon"),
|
||||
firewall: getIntegrationKindsByCategory("firewall"),
|
||||
notifications: getIntegrationKindsByCategory("notifications"),
|
||||
mediaReleases: ["emby", "jellyfin", "plex"],
|
||||
mediaReleases: ["mock", "emby", "jellyfin", "plex"],
|
||||
systemResources: ["dashDot", "openmediavault", "truenas", "unraid", "glances", "synology"],
|
||||
systemDisks: ["dashDot", "openmediavault", "truenas", "unraid", "synology"],
|
||||
coolify: ["coolify"],
|
||||
@@ -40,7 +40,13 @@ export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly Integ
|
||||
speedtestTracker: ["speedtestTracker"],
|
||||
uptimeKuma: ["uptimeKuma"],
|
||||
audioStats: ["navidrome", "audiobookshelf"],
|
||||
umami: ["umami"],
|
||||
vpn: getIntegrationKindsByCategory("vpn"),
|
||||
ups: getIntegrationKindsByCategory("ups"),
|
||||
beszelSystemTable: ["beszel", "mock"],
|
||||
beszelSystemGrid: ["beszel", "mock"],
|
||||
beszelAlerts: ["beszel", "mock"],
|
||||
beszelSystemStats: ["beszel", "mock"],
|
||||
archiveTeamWarrior: ["archiveTeamWarrior"],
|
||||
anchorNote: ["anchor"],
|
||||
traefik: ["traefik"],
|
||||
|
||||
@@ -7,9 +7,6 @@ export {
|
||||
createSubPubChannel,
|
||||
createGetSetChannel,
|
||||
createLockChannel,
|
||||
setQueryCacheAsync,
|
||||
getQueryCacheAsync,
|
||||
removeQueryCacheAsync,
|
||||
invalidateIntegrationCacheAsync,
|
||||
} from "./lib/channel";
|
||||
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
|
||||
import { ChannelSubscriptionTracker } from "./channel-subscription-tracker";
|
||||
import { createRedisConnection } from "./connection";
|
||||
|
||||
const logger = createLogger({ module: "redisChannel" });
|
||||
|
||||
const publisher = createRedisConnection();
|
||||
const lastDataClient = createRedisConnection();
|
||||
|
||||
@@ -159,34 +156,6 @@ export const createLockChannel = (name: string) => {
|
||||
};
|
||||
};
|
||||
|
||||
const queryCacheKey = (userId: string, boardId: string) => `qc:${userId}:${boardId}`;
|
||||
|
||||
export const setQueryCacheAsync = async (
|
||||
userId: string,
|
||||
boardId: string,
|
||||
value: string,
|
||||
ttlMs: number,
|
||||
maxValueBytes: number,
|
||||
) => {
|
||||
if (Buffer.byteLength(value, "utf8") > maxValueBytes) {
|
||||
logger.warn("Query cache value exceeded maximum size", {
|
||||
key: queryCacheKey(userId, boardId),
|
||||
valueBytes: Buffer.byteLength(value, "utf8"),
|
||||
maxValueBytes,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
await getSetClient.set(queryCacheKey(userId, boardId), value, "PX", ttlMs);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const getQueryCacheAsync = async (userId: string, boardId: string) =>
|
||||
await getSetClient.get(queryCacheKey(userId, boardId));
|
||||
|
||||
export const removeQueryCacheAsync = async (userId: string, boardId: string) => {
|
||||
await getSetClient.del(queryCacheKey(userId, boardId));
|
||||
};
|
||||
|
||||
export const invalidateIntegrationCacheAsync = async (integrationId: string): Promise<void> => {
|
||||
const client = getSetClient as typeof getSetClient | null;
|
||||
if (!client) return;
|
||||
|
||||
@@ -14,6 +14,7 @@ interface Options<TData, TKind extends IntegrationKind, TInput extends Record<st
|
||||
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
||||
cacheTtlMs?: number;
|
||||
fallbackToStaleOnError?: boolean;
|
||||
staleIfErrorTtlMs?: number;
|
||||
}
|
||||
|
||||
export const createIntegrationRequestHandler = <
|
||||
@@ -23,24 +24,18 @@ export const createIntegrationRequestHandler = <
|
||||
>(
|
||||
options: Options<TData, TKind, TInput>,
|
||||
) => {
|
||||
const integrationMap = new Map<string, IntegrationOfKind<TKind>>();
|
||||
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
|
||||
requestAsync: async (input) => {
|
||||
const integration = integrationMap.get(input.integrationId);
|
||||
if (!integration) {
|
||||
throw new Error(`Integration ${input.integrationId} not found in cache`);
|
||||
}
|
||||
return options.requestAsync(integration, input.options);
|
||||
},
|
||||
const inner = createRequestHandler<TData, { integration: IntegrationOfKind<TKind>; options: TInput }>({
|
||||
requestAsync: async ({ integration, options: itemOptions }) => options.requestAsync(integration, itemOptions),
|
||||
getCacheKey: ({ integration, options: itemOptions }) =>
|
||||
JSON.stringify({ integrationId: integration.id, itemOptions }),
|
||||
cacheTtlMs: options.cacheTtlMs,
|
||||
fallbackToStaleOnError: options.fallbackToStaleOnError,
|
||||
staleIfErrorTtlMs: options.staleIfErrorTtlMs,
|
||||
});
|
||||
|
||||
return {
|
||||
invalidateCache: inner.invalidateCache,
|
||||
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
|
||||
integrationMap.set(integration.id, integration);
|
||||
return inner.handler({ integrationId: integration.id, options: itemOptions });
|
||||
},
|
||||
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) =>
|
||||
inner.handler({ integration, options: itemOptions }),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,224 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { Integration, IntegrationSecret } from "@homarr/db/schema";
|
||||
|
||||
import { createIntegrationRequestHandler } from "./integration-request-handler";
|
||||
import { createRequestHandler } from "./request-handler";
|
||||
import { createWidgetRequestHandler } from "./widget-request-handler";
|
||||
|
||||
const deferred = <T>() => {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
const createIntegration = (secret: string) =>
|
||||
({
|
||||
id: "integration-id",
|
||||
kind: "sonarr",
|
||||
decryptedSecrets: [{ kind: "apiKey", value: secret }],
|
||||
}) as Omit<Integration, "kind"> & {
|
||||
kind: "sonarr";
|
||||
decryptedSecrets: Pick<IntegrationSecret, "kind" | "value">[];
|
||||
externalUrl: string | null;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("createRequestHandler", () => {
|
||||
it("deduplicates in-flight work and caches completed data", async () => {
|
||||
let calls = 0;
|
||||
const request = deferred<string>();
|
||||
const handler = createRequestHandler({
|
||||
requestAsync: async () => {
|
||||
calls += 1;
|
||||
return await request.promise;
|
||||
},
|
||||
});
|
||||
|
||||
const first = handler.handler({ id: "same" }).getDataAsync();
|
||||
const second = handler.handler({ id: "same" }).getDataAsync();
|
||||
expect(calls).toBe(1);
|
||||
|
||||
request.resolve("value");
|
||||
await expect(Promise.all([first, second])).resolves.toMatchObject([{ data: "value" }, { data: "value" }]);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({ data: "value" });
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps in-flight deduplication but retains no payload when ttl is zero", async () => {
|
||||
let calls = 0;
|
||||
const request = deferred<{ call: number }>();
|
||||
const handler = createRequestHandler({
|
||||
cacheTtlMs: 0,
|
||||
requestAsync: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) return await request.promise;
|
||||
return { call: calls };
|
||||
},
|
||||
});
|
||||
|
||||
const first = handler.handler({ id: "same" }).getDataAsync();
|
||||
const second = handler.handler({ id: "same" }).getDataAsync();
|
||||
expect(calls).toBe(1);
|
||||
|
||||
request.resolve({ call: 1 });
|
||||
await expect(Promise.all([first, second])).resolves.toMatchObject([{ data: { call: 1 } }, { data: { call: 1 } }]);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({ data: { call: 2 } });
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("releases positive-ttl entries after expiry without another request", async () => {
|
||||
vi.useFakeTimers();
|
||||
let calls = 0;
|
||||
const handler = createRequestHandler({
|
||||
cacheTtlMs: 25,
|
||||
requestAsync: async () => ({ call: ++calls }),
|
||||
});
|
||||
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({ data: { call: 1 } });
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({ data: { call: 2 } });
|
||||
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("cancels scheduled expiry work when the cache is invalidated", async () => {
|
||||
vi.useFakeTimers();
|
||||
const handler = createRequestHandler({ cacheTtlMs: 25, requestAsync: async () => "value" });
|
||||
await handler.handler({ id: "same" }).getDataAsync();
|
||||
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
handler.invalidateCache();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("bounds stale-on-error fallback and releases it while idle", async () => {
|
||||
vi.useFakeTimers();
|
||||
let calls = 0;
|
||||
const handler = createRequestHandler({
|
||||
cacheTtlMs: 25,
|
||||
fallbackToStaleOnError: true,
|
||||
staleIfErrorTtlMs: 50,
|
||||
requestAsync: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) return "last-known-good";
|
||||
throw new Error("upstream unavailable");
|
||||
},
|
||||
});
|
||||
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({
|
||||
data: "last-known-good",
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({
|
||||
data: "last-known-good",
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(51);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).rejects.toThrow("upstream unavailable");
|
||||
expect(calls).toBe(3);
|
||||
});
|
||||
|
||||
it("reschedules staggered stale entries by their retirement deadline without spinning", async () => {
|
||||
vi.useFakeTimers();
|
||||
const handler = createRequestHandler({
|
||||
cacheTtlMs: 10,
|
||||
fallbackToStaleOnError: true,
|
||||
staleIfErrorTtlMs: 100,
|
||||
requestAsync: async ({ id }: { id: string }) => id,
|
||||
});
|
||||
|
||||
await handler.handler({ id: "first" }).getDataAsync();
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
await handler.handler({ id: "second" }).getDataAsync();
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(90);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("evicts an empty-string cache key at the size limit", async () => {
|
||||
let calls = 0;
|
||||
const handler = createRequestHandler({
|
||||
cacheTtlMs: 60_000,
|
||||
getCacheKey: ({ id }: { id: string }) => id,
|
||||
requestAsync: async () => ++calls,
|
||||
});
|
||||
|
||||
await handler.handler({ id: "" }).getDataAsync();
|
||||
for (let index = 0; index < 1000; index += 1) {
|
||||
await handler.handler({ id: String(index) }).getDataAsync();
|
||||
}
|
||||
await handler.handler({ id: "" }).getDataAsync();
|
||||
|
||||
expect(calls).toBe(1002);
|
||||
});
|
||||
|
||||
it("does not let a pre-invalidation request repopulate or clear newer work", async () => {
|
||||
const staleRequest = deferred<string>();
|
||||
const freshRequest = deferred<string>();
|
||||
const requests = [staleRequest, freshRequest];
|
||||
let calls = 0;
|
||||
const handler = createRequestHandler({
|
||||
requestAsync: async () => {
|
||||
const request = requests[calls++];
|
||||
if (!request) throw new Error("Unexpected request");
|
||||
return await request.promise;
|
||||
},
|
||||
});
|
||||
|
||||
const stale = handler.handler({ id: "same" }).getDataAsync();
|
||||
handler.invalidateCache();
|
||||
const fresh = handler.handler({ id: "same" }).getDataAsync();
|
||||
|
||||
staleRequest.resolve("stale");
|
||||
await expect(stale).resolves.toMatchObject({ data: "stale" });
|
||||
const joinsFresh = handler.handler({ id: "same" }).getDataAsync();
|
||||
expect(calls).toBe(2);
|
||||
|
||||
freshRequest.resolve("fresh");
|
||||
await expect(Promise.all([fresh, joinsFresh])).resolves.toMatchObject([{ data: "fresh" }, { data: "fresh" }]);
|
||||
await expect(handler.handler({ id: "same" }).getDataAsync()).resolves.toMatchObject({ data: "fresh" });
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createIntegrationRequestHandler", () => {
|
||||
it("keys requests by integration id and options without retaining secret values", async () => {
|
||||
let calls = 0;
|
||||
const request = deferred<string>();
|
||||
const handler = createIntegrationRequestHandler<string, "sonarr", { page: number }>({
|
||||
requestAsync: async () => {
|
||||
calls += 1;
|
||||
return await request.promise;
|
||||
},
|
||||
});
|
||||
const first = handler.handler(createIntegration("first-secret"), { page: 1 }).getDataAsync();
|
||||
const second = handler.handler(createIntegration("rotated-secret"), { page: 1 }).getDataAsync();
|
||||
expect(calls).toBe(1);
|
||||
|
||||
request.resolve("value");
|
||||
await expect(Promise.all([first, second])).resolves.toMatchObject([{ data: "value" }, { data: "value" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createWidgetRequestHandler", () => {
|
||||
it("shares its cache across calls while keeping distinct inputs separate", async () => {
|
||||
let calls = 0;
|
||||
const handler = createWidgetRequestHandler({ requestAsync: async ({ id }: { id: string }) => `${id}-${++calls}` });
|
||||
|
||||
await expect(handler.handler({ id: "one" }).getDataAsync()).resolves.toMatchObject({ data: "one-1" });
|
||||
await expect(handler.handler({ id: "one" }).getDataAsync()).resolves.toMatchObject({ data: "one-1" });
|
||||
await expect(handler.handler({ id: "two" }).getDataAsync()).resolves.toMatchObject({ data: "two-2" });
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,21 @@
|
||||
interface Options<TData, TInput extends Record<string, unknown>> {
|
||||
requestAsync: (input: TInput) => Promise<TData>;
|
||||
getCacheKey?: (input: TInput) => string;
|
||||
cacheTtlMs?: number;
|
||||
fallbackToStaleOnError?: boolean;
|
||||
staleIfErrorTtlMs?: number;
|
||||
}
|
||||
|
||||
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
|
||||
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number; staleUntil: number };
|
||||
|
||||
const MAX_CACHE_SIZE = 1000;
|
||||
const DEFAULT_TTL_MS = 10_000;
|
||||
const DEFAULT_STALE_IF_ERROR_TTL_MS = 5 * 60_000;
|
||||
|
||||
const evictExpired = <TData>(cache: Map<string, CacheEntry<TData>>) => {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of cache) {
|
||||
if (now >= entry.expiresAt) cache.delete(key);
|
||||
if (now >= entry.staleUntil) cache.delete(key);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -21,44 +24,98 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
|
||||
) => {
|
||||
const cache = new Map<string, CacheEntry<TData>>();
|
||||
const inflight = new Map<string, Promise<CacheEntry<TData>>>();
|
||||
let expiryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let expiryTimerAt: number | undefined;
|
||||
let generation = 0;
|
||||
|
||||
const scheduleExpiry = (candidateExpiryAt?: number) => {
|
||||
if (candidateExpiryAt !== undefined && expiryTimerAt !== undefined && expiryTimerAt <= candidateExpiryAt) return;
|
||||
if (expiryTimer) clearTimeout(expiryTimer);
|
||||
expiryTimer = undefined;
|
||||
expiryTimerAt = undefined;
|
||||
if (cache.size === 0) return;
|
||||
|
||||
const nextExpiryAt = candidateExpiryAt ?? Math.min(...[...cache.values()].map(({ staleUntil }) => staleUntil));
|
||||
expiryTimerAt = nextExpiryAt;
|
||||
expiryTimer = setTimeout(
|
||||
() => {
|
||||
expiryTimer = undefined;
|
||||
expiryTimerAt = undefined;
|
||||
evictExpired(cache);
|
||||
scheduleExpiry();
|
||||
},
|
||||
Math.max(0, nextExpiryAt - Date.now()),
|
||||
);
|
||||
expiryTimer.unref?.();
|
||||
};
|
||||
|
||||
return {
|
||||
invalidateCache: () => {
|
||||
generation += 1;
|
||||
cache.clear();
|
||||
inflight.clear();
|
||||
if (expiryTimer) clearTimeout(expiryTimer);
|
||||
expiryTimer = undefined;
|
||||
expiryTimerAt = undefined;
|
||||
},
|
||||
handler: (input: TInput) => ({
|
||||
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
||||
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||
const key = JSON.stringify(input);
|
||||
const key = options.getCacheKey?.(input) ?? JSON.stringify(input);
|
||||
|
||||
const cached = cache.get(key);
|
||||
if (cached && Date.now() < cached.expiresAt) {
|
||||
let cached = cache.get(key);
|
||||
const now = Date.now();
|
||||
if (cached && now < cached.expiresAt) {
|
||||
return { data: cached.data, timestamp: cached.timestamp };
|
||||
}
|
||||
if (cached && now >= cached.staleUntil) {
|
||||
cache.delete(key);
|
||||
scheduleExpiry();
|
||||
cached = undefined;
|
||||
}
|
||||
|
||||
const existing = inflight.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const promise = options
|
||||
const requestGeneration = generation;
|
||||
let promise: Promise<CacheEntry<TData>>;
|
||||
promise = options
|
||||
.requestAsync(input)
|
||||
.then((data) => {
|
||||
if (cache.size >= MAX_CACHE_SIZE) evictExpired(cache);
|
||||
if (cache.size >= MAX_CACHE_SIZE) {
|
||||
const oldest = cache.keys().next().value;
|
||||
if (oldest) cache.delete(oldest);
|
||||
const expiresAt = Date.now() + ttl;
|
||||
const staleIfErrorTtlMs = options.fallbackToStaleOnError
|
||||
? Math.max(0, options.staleIfErrorTtlMs ?? DEFAULT_STALE_IF_ERROR_TTL_MS)
|
||||
: 0;
|
||||
const entry: CacheEntry<TData> = {
|
||||
data,
|
||||
timestamp: new Date(),
|
||||
expiresAt,
|
||||
staleUntil: expiresAt + staleIfErrorTtlMs,
|
||||
};
|
||||
if (ttl > 0 && generation === requestGeneration) {
|
||||
evictExpired(cache);
|
||||
if (cache.size >= MAX_CACHE_SIZE) {
|
||||
const oldest = cache.keys().next().value;
|
||||
if (oldest !== undefined) cache.delete(oldest);
|
||||
}
|
||||
cache.set(key, entry);
|
||||
scheduleExpiry(entry.staleUntil);
|
||||
}
|
||||
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
||||
cache.set(key, entry);
|
||||
inflight.delete(key);
|
||||
return entry;
|
||||
})
|
||||
.catch((err) => {
|
||||
inflight.delete(key);
|
||||
if (options.fallbackToStaleOnError && cached) {
|
||||
if (
|
||||
options.fallbackToStaleOnError &&
|
||||
cached &&
|
||||
Date.now() < cached.staleUntil &&
|
||||
generation === requestGeneration
|
||||
) {
|
||||
return cached;
|
||||
}
|
||||
throw err;
|
||||
})
|
||||
.finally(() => {
|
||||
if (inflight.get(key) === promise) inflight.delete(key);
|
||||
});
|
||||
|
||||
inflight.set(key, promise);
|
||||
|
||||
@@ -6,9 +6,7 @@ interface Options<TData, TInput extends Record<string, unknown>> {
|
||||
|
||||
export const createWidgetRequestHandler = <TData, TInput extends Record<string, unknown>>(
|
||||
options: Options<TData, TInput>,
|
||||
) => ({
|
||||
handler: (widgetOptions: TInput) =>
|
||||
createRequestHandler<TData, TInput>({
|
||||
requestAsync: options.requestAsync,
|
||||
}).handler(widgetOptions),
|
||||
});
|
||||
) => {
|
||||
const inner = createRequestHandler<TData, TInput>({ requestAsync: options.requestAsync });
|
||||
return inner;
|
||||
};
|
||||
@@ -20,13 +20,28 @@ const mocks = vi.hoisted(() => {
|
||||
values,
|
||||
locks,
|
||||
removeFreshResult() {
|
||||
values.delete("update-checker:fresh:v1");
|
||||
for (const key of values.keys()) {
|
||||
if (key.startsWith("update-checker:fresh:")) values.delete(key);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@homarr/common/env", () => ({ env: mocks.env }));
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/http", () => ({
|
||||
fetchWithTrustedCertificatesAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/logs", () => ({
|
||||
createLogger: () => ({
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/redis", () => ({
|
||||
createGetSetChannel: (name: string) => ({
|
||||
getAsync: async () => {
|
||||
@@ -181,6 +196,20 @@ describe("persisted update checker cache", () => {
|
||||
expect(mocks.listReleases).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("ignores update results created for an older application version", async () => {
|
||||
mocks.values.set("update-checker:fresh:v1", {
|
||||
value: { availableUpdates: [], attemptedAt: 1, checkedAt: 1 },
|
||||
expiresAt: null,
|
||||
});
|
||||
mocks.listReleases.mockResolvedValue(successfulResponse);
|
||||
|
||||
const handler = await loadHandlerAsync();
|
||||
const result = await handler.getDataAsync();
|
||||
|
||||
expect(result.data.availableUpdates).toHaveLength(1);
|
||||
expect(mocks.listReleases).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("serves stale data and retries only after 24 hours following a provider failure", async () => {
|
||||
let now = 1_000;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
|
||||
@@ -22,9 +22,14 @@ type UpdateCheckCacheEntry = {
|
||||
checkedAt: number | null;
|
||||
};
|
||||
|
||||
const freshUpdateCheckChannel = createGetSetChannel<UpdateCheckCacheEntry>("update-checker:fresh:v1");
|
||||
const staleUpdateCheckChannel = createGetSetChannel<UpdateCheckCacheEntry>("update-checker:stale:v1");
|
||||
const updateCheckLock = createLockChannel("update-checker:lock:v1");
|
||||
const updateCheckCacheVersion = `v2:${packageJson.version}`;
|
||||
const freshUpdateCheckChannel = createGetSetChannel<UpdateCheckCacheEntry>(
|
||||
`update-checker:fresh:${updateCheckCacheVersion}`,
|
||||
);
|
||||
const staleUpdateCheckChannel = createGetSetChannel<UpdateCheckCacheEntry>(
|
||||
`update-checker:stale:${updateCheckCacheVersion}`,
|
||||
);
|
||||
const updateCheckLock = createLockChannel(`update-checker:lock:${updateCheckCacheVersion}`);
|
||||
|
||||
const waitAsync = async (durationMs: number) =>
|
||||
await new Promise<void>((resolve) => {
|
||||
@@ -53,8 +58,10 @@ const getCachedAvailableUpdatesAsync = async (): Promise<UpdateCheckCacheEntry>
|
||||
const cached = await freshUpdateCheckChannel.getAsync();
|
||||
if (cached) return cached;
|
||||
|
||||
const staleBeforeRefresh = await staleUpdateCheckChannel.getAsync();
|
||||
const lockToken = await updateCheckLock.acquireAsync(updateCheckLockTtlSeconds);
|
||||
if (!lockToken) {
|
||||
if (staleBeforeRefresh) return staleBeforeRefresh;
|
||||
const concurrentResult = await waitForConcurrentUpdateCheckAsync();
|
||||
if (concurrentResult) return concurrentResult;
|
||||
throw new Error("Timed out waiting for the update check");
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
},
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./component": "./src/component.ts",
|
||||
"./open": "./src/open.ts",
|
||||
"./styles.css": "./src/styles.css"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"use client";
|
||||
|
||||
export { Spotlight } from "./components/spotlight";
|
||||
@@ -11,18 +11,18 @@ import { hotkeys } from "@homarr/definitions";
|
||||
import type { TranslationObject } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { OpenMediaRequestSearchOptions } from "../index";
|
||||
import {
|
||||
consumePendingMediaRequestSearch,
|
||||
consumePendingSpotlightOpen,
|
||||
mediaRequestSearchEvent,
|
||||
spotlightOpenEvent,
|
||||
} from "../open";
|
||||
import type { OpenMediaRequestSearchOptions } from "../open";
|
||||
import type { inferSearchInteractionOptions } from "../lib/interaction";
|
||||
import type { SearchMode } from "../lib/mode";
|
||||
import { searchModes } from "../modes";
|
||||
import { useHomeEmptyGroupsWithPreferences } from "../modes/help/home-empty-groups";
|
||||
import {
|
||||
mediaRequestSearchEvent,
|
||||
mediaRequestSearchScopeAtom,
|
||||
selectAction,
|
||||
spotlightActions,
|
||||
spotlightStore,
|
||||
} from "../spotlight-store";
|
||||
import { mediaRequestSearchScopeAtom, selectAction, spotlightActions, spotlightStore } from "../spotlight-store";
|
||||
import { SpotlightChildrenActions } from "./actions/children-actions";
|
||||
import { SpotlightActionGroups } from "./actions/groups/action-group";
|
||||
|
||||
@@ -64,6 +64,17 @@ const SpotlightWithActiveMode = ({ modeState, queryState, activeMode }: Spotligh
|
||||
const homeEmptyGroups = useHomeEmptyGroupsWithPreferences();
|
||||
const hasModeCharacter = activeMode.modeKey !== defaultMode && activeMode.character !== undefined;
|
||||
|
||||
useEffect(() => {
|
||||
const handleOpen = () => {
|
||||
consumePendingSpotlightOpen();
|
||||
spotlightActions.open();
|
||||
};
|
||||
|
||||
window.addEventListener(spotlightOpenEvent, handleOpen);
|
||||
if (consumePendingSpotlightOpen()) spotlightActions.open();
|
||||
return () => window.removeEventListener(spotlightOpenEvent, handleOpen);
|
||||
}, []);
|
||||
|
||||
const clearChildrenStack = useCallback(() => {
|
||||
setChildrenStack([]);
|
||||
}, []);
|
||||
@@ -84,17 +95,24 @@ const SpotlightWithActiveMode = ({ modeState, queryState, activeMode }: Spotligh
|
||||
}, [setQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleMediaRequestSearch = (event: Event) => {
|
||||
const { integrationIds, query } = (event as CustomEvent<OpenMediaRequestSearchOptions>).detail ?? {};
|
||||
const applyMediaRequestSearch = ({ integrationIds, query: searchQuery }: OpenMediaRequestSearchOptions) => {
|
||||
setMediaRequestSearchScope({ integrationIds });
|
||||
setMode("media");
|
||||
clearChildrenStack();
|
||||
setQuery(query ?? "");
|
||||
setQuery(searchQuery ?? "");
|
||||
spotlightActions.open();
|
||||
setTimeout(() => selectAction(0, spotlightStore));
|
||||
};
|
||||
|
||||
const handleMediaRequestSearch = (event: Event) => {
|
||||
consumePendingMediaRequestSearch();
|
||||
const { integrationIds, query: searchQuery } = (event as CustomEvent<OpenMediaRequestSearchOptions>).detail ?? {};
|
||||
applyMediaRequestSearch({ integrationIds, query: searchQuery });
|
||||
};
|
||||
|
||||
window.addEventListener(mediaRequestSearchEvent, handleMediaRequestSearch);
|
||||
const pendingSearch = consumePendingMediaRequestSearch();
|
||||
if (pendingSearch) applyMediaRequestSearch(pendingSearch);
|
||||
return () => {
|
||||
window.removeEventListener(mediaRequestSearchEvent, handleMediaRequestSearch);
|
||||
};
|
||||
|
||||
@@ -1,28 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { mediaRequestSearchEvent, spotlightActions } from "./spotlight-store";
|
||||
|
||||
export { Spotlight } from "./components/spotlight";
|
||||
export { openSpotlight, openMediaRequestSearch };
|
||||
export { openSpotlight, openMediaRequestSearch, mediaRequestSearchEvent } from "./open";
|
||||
export {
|
||||
SpotlightProvider,
|
||||
useRegisterSpotlightContextResults,
|
||||
useRegisterSpotlightContextActions,
|
||||
} from "./modes/home/context";
|
||||
|
||||
const openSpotlight = spotlightActions.open;
|
||||
|
||||
export interface OpenMediaRequestSearchOptions {
|
||||
integrationIds?: string[];
|
||||
query?: string;
|
||||
}
|
||||
|
||||
const openMediaRequestSearch = (options: OpenMediaRequestSearchOptions = {}) => {
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent<OpenMediaRequestSearchOptions>(mediaRequestSearchEvent, { detail: options }));
|
||||
}
|
||||
|
||||
spotlightActions.open();
|
||||
};
|
||||
|
||||
export { mediaRequestSearchEvent };
|
||||
@@ -0,0 +1,54 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
consumePendingMediaRequestSearch,
|
||||
consumePendingSpotlightOpen,
|
||||
hasPendingSpotlightOpen,
|
||||
mediaRequestSearchEvent,
|
||||
openMediaRequestSearch,
|
||||
openSpotlight,
|
||||
spotlightOpenEvent,
|
||||
} from "./open";
|
||||
|
||||
describe("lazy Spotlight open bridge", () => {
|
||||
beforeEach(() => {
|
||||
consumePendingSpotlightOpen();
|
||||
consumePendingMediaRequestSearch();
|
||||
});
|
||||
|
||||
it("keeps a pre-mount open request until the lazy component consumes it", () => {
|
||||
const listener = vi.fn();
|
||||
window.addEventListener(spotlightOpenEvent, listener);
|
||||
|
||||
openSpotlight();
|
||||
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
expect(consumePendingSpotlightOpen()).toBe(true);
|
||||
expect(consumePendingSpotlightOpen()).toBe(false);
|
||||
window.removeEventListener(spotlightOpenEvent, listener);
|
||||
});
|
||||
|
||||
it("lets a listener installed after the request discover the pending open", () => {
|
||||
openSpotlight();
|
||||
|
||||
expect(hasPendingSpotlightOpen()).toBe(true);
|
||||
expect(consumePendingSpotlightOpen()).toBe(true);
|
||||
expect(hasPendingSpotlightOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it("retains media options while dispatching both mount and media events", () => {
|
||||
const openListener = vi.fn();
|
||||
const mediaListener = vi.fn();
|
||||
window.addEventListener(spotlightOpenEvent, openListener);
|
||||
window.addEventListener(mediaRequestSearchEvent, mediaListener);
|
||||
|
||||
openMediaRequestSearch({ integrationIds: ["integration-a"], query: "movie" });
|
||||
|
||||
expect(openListener).toHaveBeenCalledOnce();
|
||||
expect(mediaListener).toHaveBeenCalledOnce();
|
||||
expect(consumePendingSpotlightOpen()).toBe(true);
|
||||
expect(consumePendingMediaRequestSearch()).toEqual({ integrationIds: ["integration-a"], query: "movie" });
|
||||
window.removeEventListener(spotlightOpenEvent, openListener);
|
||||
window.removeEventListener(mediaRequestSearchEvent, mediaListener);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
export const spotlightOpenEvent = "homarr:spotlight:open";
|
||||
export const mediaRequestSearchEvent = "homarr:spotlight:media-request-search";
|
||||
|
||||
export interface OpenMediaRequestSearchOptions {
|
||||
integrationIds?: string[];
|
||||
query?: string;
|
||||
}
|
||||
|
||||
let pendingMediaRequestSearch: OpenMediaRequestSearchOptions | null = null;
|
||||
let pendingSpotlightOpen = false;
|
||||
|
||||
const requestSpotlightMount = () => {
|
||||
if (typeof window !== "undefined") window.dispatchEvent(new Event(spotlightOpenEvent));
|
||||
};
|
||||
|
||||
export const openSpotlight = () => {
|
||||
pendingSpotlightOpen = true;
|
||||
requestSpotlightMount();
|
||||
};
|
||||
|
||||
export const consumePendingSpotlightOpen = () => {
|
||||
const pending = pendingSpotlightOpen;
|
||||
pendingSpotlightOpen = false;
|
||||
return pending;
|
||||
};
|
||||
|
||||
export const hasPendingSpotlightOpen = () => pendingSpotlightOpen;
|
||||
|
||||
export const consumePendingMediaRequestSearch = () => {
|
||||
const pending = pendingMediaRequestSearch;
|
||||
pendingMediaRequestSearch = null;
|
||||
return pending;
|
||||
};
|
||||
|
||||
export const openMediaRequestSearch = (options: OpenMediaRequestSearchOptions = {}) => {
|
||||
pendingMediaRequestSearch = options;
|
||||
openSpotlight();
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent<OpenMediaRequestSearchOptions>(mediaRequestSearchEvent, { detail: options }));
|
||||
}
|
||||
};
|
||||
@@ -12,7 +12,6 @@ export interface MediaRequestSearchScope {
|
||||
}
|
||||
|
||||
export const mediaRequestSearchScopeAtom = atom<MediaRequestSearchScope>({});
|
||||
export const mediaRequestSearchEvent = "homarr:spotlight:media-request-search";
|
||||
|
||||
export const setSelectedAction = (index: number, store: SpotlightStore) => {
|
||||
store.updateState((state) => ({ ...state, selected: index }));
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"./_inputs/json-path-tree-picker": "./src/_inputs/json-path-tree-picker.tsx",
|
||||
"./custom-api/component": "./src/custom-api/component.tsx",
|
||||
"./custom-api/extract-display-data": "./src/custom-api/extract-display-data.ts",
|
||||
"./client": "./src/client.tsx",
|
||||
"./catalog": "./src/catalog.ts",
|
||||
"./definition": "./src/definition.ts",
|
||||
"./errors": "./src/errors/component.tsx",
|
||||
"./manifest": "./src/manifest.ts",
|
||||
|
||||
@@ -5,6 +5,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("anchorNote", {
|
||||
icon: IconNotes,
|
||||
queryKey: [["widget", "anchorNotes"]],
|
||||
supportedIntegrations: ["anchor"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
|
||||
@@ -15,6 +15,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("app", {
|
||||
icon: IconApps,
|
||||
queryKeys: [[["app", "byId"]], [["widget", "app"]]],
|
||||
createOptions(settings) {
|
||||
return optionsBuilder.from(
|
||||
(factory) => ({
|
||||
|
||||
@@ -6,6 +6,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("beszelAlerts", {
|
||||
icon: IconBell,
|
||||
queryKey: [["widget", "beszel"]],
|
||||
supportedIntegrations: ["beszel", "mock"],
|
||||
integrationsRequired: true,
|
||||
createOptions() {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { BookmarkAddButton } from "./add-button";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("bookmarks", {
|
||||
icon: IconBookmark,
|
||||
queryKeys: [[["app", "byIds"]]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
title: factory.text(),
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import {
|
||||
IconActivityHeartbeat,
|
||||
IconAd,
|
||||
IconApi,
|
||||
IconApps,
|
||||
IconArchive,
|
||||
IconBadgeCc,
|
||||
IconBatteryCharging,
|
||||
IconBell,
|
||||
IconBinaryTree,
|
||||
IconBookmark,
|
||||
IconBrandDocker,
|
||||
IconBrandMinecraft,
|
||||
IconBrowser,
|
||||
IconBuildingBank,
|
||||
IconBusStop,
|
||||
IconCalendar,
|
||||
IconChartAreaLine,
|
||||
IconChartBar,
|
||||
IconClock,
|
||||
IconCloud,
|
||||
IconDeviceCctv,
|
||||
IconDeviceGamepad,
|
||||
IconDownload,
|
||||
IconFileText,
|
||||
IconGraphFilled,
|
||||
IconHeadphones,
|
||||
IconHeartRateMonitor,
|
||||
IconHeartbeat,
|
||||
IconLayoutGrid,
|
||||
IconMessage,
|
||||
IconMovie,
|
||||
IconNotes,
|
||||
IconPhoto,
|
||||
IconReportSearch,
|
||||
IconRocket,
|
||||
IconRoute,
|
||||
IconRss,
|
||||
IconServer2,
|
||||
IconShieldCheck,
|
||||
IconShieldLock,
|
||||
IconSpeedboat,
|
||||
IconTable,
|
||||
IconTicket,
|
||||
IconTopologyFull,
|
||||
IconTransform,
|
||||
IconVideo,
|
||||
IconWall,
|
||||
IconZoomQuestion,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
|
||||
export const widgetCatalogIcons: Record<WidgetKind, TablerIcon> = {
|
||||
clock: IconClock,
|
||||
weather: IconCloud,
|
||||
app: IconApps,
|
||||
iframe: IconBrowser,
|
||||
video: IconDeviceCctv,
|
||||
notebook: IconNotes,
|
||||
anchorNote: IconNotes,
|
||||
dnsHoleSummary: IconAd,
|
||||
dnsHoleControls: IconDeviceGamepad,
|
||||
"smartHome-entityState": IconBinaryTree,
|
||||
"smartHome-executeAutomation": IconBinaryTree,
|
||||
stockPrice: IconBuildingBank,
|
||||
mediaServer: IconVideo,
|
||||
calendar: IconCalendar,
|
||||
downloads: IconDownload,
|
||||
"mediaRequests-requestList": IconZoomQuestion,
|
||||
"mediaRequests-requestStats": IconChartBar,
|
||||
mediaTranscoding: IconTransform,
|
||||
mediaMissing: IconMovie,
|
||||
minecraftServerStatus: IconBrandMinecraft,
|
||||
networkControllerSummary: IconTopologyFull,
|
||||
networkControllerStatus: IconTopologyFull,
|
||||
rssFeed: IconRss,
|
||||
bookmarks: IconBookmark,
|
||||
indexerManager: IconReportSearch,
|
||||
healthMonitoring: IconHeartRateMonitor,
|
||||
releases: IconRocket,
|
||||
mediaReleases: IconTicket,
|
||||
dockerContainers: IconBrandDocker,
|
||||
firewall: IconWall,
|
||||
notifications: IconMessage,
|
||||
systemResources: IconGraphFilled,
|
||||
coolify: IconCloud,
|
||||
systemDisks: IconServer2,
|
||||
timetable: IconBusStop,
|
||||
"immich-serverStats": IconGraphFilled,
|
||||
"immich-albumCarousel": IconPhoto,
|
||||
paperlessNgx: IconFileText,
|
||||
patchmon: IconShieldCheck,
|
||||
bazarr: IconBadgeCc,
|
||||
tracearr: IconActivityHeartbeat,
|
||||
speedtestTracker: IconSpeedboat,
|
||||
uptimeKuma: IconHeartbeat,
|
||||
audioStats: IconHeadphones,
|
||||
umami: IconChartBar,
|
||||
vpn: IconShieldLock,
|
||||
archiveTeamWarrior: IconArchive,
|
||||
ups: IconBatteryCharging,
|
||||
beszelSystemTable: IconTable,
|
||||
beszelSystemGrid: IconLayoutGrid,
|
||||
beszelAlerts: IconBell,
|
||||
beszelSystemStats: IconChartAreaLine,
|
||||
traefik: IconRoute,
|
||||
customApi: IconApi,
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { Center, Loader as UiLoader } from "@mantine/core";
|
||||
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
|
||||
import type { WidgetComponentProps } from "./definition";
|
||||
import { loadWidgetModule, widgetKinds } from "./manifest";
|
||||
|
||||
const createWidgetComponent = (kind: WidgetKind) =>
|
||||
dynamic<WidgetComponentProps<WidgetKind>>(
|
||||
async () => {
|
||||
const { componentLoader } = await loadWidgetModule(kind);
|
||||
return await componentLoader();
|
||||
},
|
||||
{
|
||||
loading: () => (
|
||||
<Center w="100%" h="100%">
|
||||
<UiLoader />
|
||||
</Center>
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
// Creating every dynamic wrapper at module scope lets Next register stable
|
||||
// client boundaries and preload metadata. Widget implementation modules remain
|
||||
// behind their manifest loaders.
|
||||
const widgetComponents = Object.fromEntries(widgetKinds.map((kind) => [kind, createWidgetComponent(kind)])) as Record<
|
||||
WidgetKind,
|
||||
ComponentType<WidgetComponentProps<WidgetKind>>
|
||||
>;
|
||||
|
||||
export const getWidgetComponent = <TKind extends WidgetKind>(kind: TKind) => {
|
||||
return widgetComponents[kind] as ComponentType<WidgetComponentProps<TKind>>;
|
||||
};
|
||||
@@ -6,6 +6,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
icon: IconClock,
|
||||
queryKey: [["widget", "weather"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from(
|
||||
(factory) => ({
|
||||
|
||||
@@ -70,6 +70,7 @@ export const createWidgetDefinition = <TKind extends WidgetKind, TDefinition ext
|
||||
export interface WidgetDefinition {
|
||||
icon: TablerIcon;
|
||||
queryKey?: QueryKey;
|
||||
queryKeys?: QueryKey[];
|
||||
refetchInterval?: number | null;
|
||||
supportedIntegrations?: IntegrationKind[];
|
||||
integrationsRequired?: boolean;
|
||||
@@ -90,6 +91,9 @@ export interface WidgetDefinition {
|
||||
contextActions?: (props: Omit<WidgetContextActionProps<WidgetKind>, "kind">) => WidgetContextMenuAction[];
|
||||
}
|
||||
|
||||
export const getWidgetQueryKeys = (definition: WidgetDefinition, kind: WidgetKind): QueryKey[] =>
|
||||
definition.queryKeys ?? [definition.queryKey ?? [["widget", kind]]];
|
||||
|
||||
export interface WidgetProps<TKind extends WidgetKind> {
|
||||
options: inferOptionsFromCreator<WidgetOptionsRecordOf<TKind>>;
|
||||
integrationIds: string[];
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { getDownloadJobsAndStatusesAsync } from "@homarr/api/widget-prefetch-server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
|
||||
import type { Prefetch } from "../definition";
|
||||
import { createTrpcQueryKey } from "../trpc-query-key";
|
||||
|
||||
const logger = createLogger({ module: "downloadsWidgetPrefetch" });
|
||||
|
||||
const prefetchAllAsync: Prefetch<"downloads"> = async (queryClient, items) => {
|
||||
await Promise.all(
|
||||
items.map(async (item) => {
|
||||
if (item.integrationIds.length === 0) return;
|
||||
|
||||
const input = {
|
||||
integrationIds: item.integrationIds,
|
||||
limitPerIntegration: Number(item.options.limitPerIntegration) || 50,
|
||||
};
|
||||
|
||||
try {
|
||||
const data = await getDownloadJobsAndStatusesAsync(input);
|
||||
queryClient.setQueryData(createTrpcQueryKey("widget.downloads.getJobsAndStatuses", input), data);
|
||||
logger.info("Prefetched downloads widget data", { integrations: item.integrationIds.length });
|
||||
} catch (error) {
|
||||
logger.warn("Failed to prefetch downloads widget data", { error });
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export default prefetchAllAsync;
|
||||
@@ -17,7 +17,7 @@ export const BaseWidgetError = (props: BaseWidgetErrorProps) => {
|
||||
const t = useI18n();
|
||||
|
||||
return (
|
||||
<Stack h="100%" align="center" justify="center" gap="md">
|
||||
<Stack h="100%" align="center" justify="center" gap="md" data-homarr-widget-error>
|
||||
<props.icon size={40} />
|
||||
<Stack gap={0}>
|
||||
<Text ta="center">{translateIfNecessary(t, props.message)}</Text>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createStorageVolumeMultiSelectOptions } from "../storage-volume-options
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("healthMonitoring", {
|
||||
icon: IconHeartRateMonitor,
|
||||
queryKeys: [[["widget", "healthMonitoring"]], [["integration", "byIds"]]],
|
||||
refetchInterval: 5,
|
||||
createOptions() {
|
||||
return optionsBuilder.from(
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { widgetKinds as definedWidgetKinds } from "@homarr/definitions";
|
||||
import { widgetIntegrationSupport, widgetKinds as definedWidgetKinds } from "@homarr/definitions";
|
||||
|
||||
import {
|
||||
createRetryableLoader,
|
||||
loadAllWidgetDefinitions,
|
||||
loadWidgetComponent,
|
||||
loadWidgetDefinition,
|
||||
loadWidgetModule,
|
||||
loadWidgetResources,
|
||||
reduceWidgetOptionsWithDefinition,
|
||||
widgetKinds,
|
||||
} from "./manifest";
|
||||
import { widgetQueryRefetchIntervals } from "./refetch-intervals";
|
||||
import { widgetCatalogIcons } from "./catalog";
|
||||
|
||||
describe("widget manifest promise stability", () => {
|
||||
it("returns the same module promise for every render", () => {
|
||||
@@ -22,6 +25,11 @@ describe("widget manifest promise stability", () => {
|
||||
expect(loadWidgetDefinition("clock")).toBe(loadWidgetDefinition("clock"));
|
||||
});
|
||||
|
||||
it("returns stable component and combined resource promises", () => {
|
||||
expect(loadWidgetComponent("clock")).toBe(loadWidgetComponent("clock"));
|
||||
expect(loadWidgetResources("clock")).toBe(loadWidgetResources("clock"));
|
||||
});
|
||||
|
||||
it("returns the same all-definitions promise for every modal render", () => {
|
||||
expect(loadAllWidgetDefinitions()).toBe(loadAllWidgetDefinitions());
|
||||
});
|
||||
@@ -56,9 +64,14 @@ describe("widget manifest promise stability", () => {
|
||||
await Promise.all(
|
||||
widgetKinds.map(async (kind) => {
|
||||
const module = await loadWidgetModule(kind);
|
||||
const component = await module.componentLoader();
|
||||
const canonicalComponent = await module.componentLoader();
|
||||
const component = await loadWidgetComponent(kind);
|
||||
const resources = await loadWidgetResources(kind);
|
||||
expect(definitions.get(kind)).toBe(module.definition);
|
||||
expect(component.default).toBe(canonicalComponent.default);
|
||||
expect(component.default).toBeDefined();
|
||||
expect(resources.definition).toBe(module.definition);
|
||||
expect(resources.Component).toBe(component.default);
|
||||
}),
|
||||
);
|
||||
}, 30_000);
|
||||
@@ -75,6 +88,42 @@ describe("widget manifest promise stability", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the lightweight integration support map aligned with widget definitions", async () => {
|
||||
const definitions = await loadAllWidgetDefinitions();
|
||||
|
||||
for (const kind of widgetKinds) {
|
||||
const definition = definitions.get(kind);
|
||||
const supportedIntegrations =
|
||||
definition && "supportedIntegrations" in definition ? (definition.supportedIntegrations ?? []) : [];
|
||||
expect([...(widgetIntegrationSupport[kind] ?? [])].toSorted()).toEqual([...supportedIntegrations].toSorted());
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the lightweight catalog icons aligned with widget definitions", async () => {
|
||||
const definitions = await loadAllWidgetDefinitions();
|
||||
|
||||
for (const kind of widgetKinds) {
|
||||
expect(widgetCatalogIcons[kind]).toBe(definitions.get(kind)?.icon);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares the real query prefix for widget kinds that share a router", async () => {
|
||||
const definitions = await loadAllWidgetDefinitions();
|
||||
const expectedQueryKeys = new Map([
|
||||
["anchorNote", [["widget", "anchorNotes"]]],
|
||||
["beszelAlerts", [["widget", "beszel"]]],
|
||||
["clock", [["widget", "weather"]]],
|
||||
["mediaMissing", [["widget", "mediaOrganizer"]]],
|
||||
["mediaRequests-requestList", [["widget", "mediaRequests"]]],
|
||||
["mediaRequests-requestStats", [["widget", "mediaRequests"]]],
|
||||
["smartHome-entityState", [["widget", "smartHome"]]],
|
||||
] as const);
|
||||
|
||||
for (const [kind, queryKey] of expectedQueryKeys) {
|
||||
expect(definitions.get(kind)?.queryKey).toEqual(queryKey);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the client polling policy aligned with widget definitions", async () => {
|
||||
const definitions = await loadAllWidgetDefinitions();
|
||||
type PollingPolicy = { queryKey: QueryKey; intervalSeconds: number | null };
|
||||
|
||||
@@ -12,6 +12,15 @@ type WidgetModule = {
|
||||
componentLoader: () => Promise<{ default: ComponentType<WidgetComponentProps<WidgetKind>> }>;
|
||||
};
|
||||
|
||||
type WidgetComponentModule = {
|
||||
default: ComponentType<WidgetComponentProps<WidgetKind>>;
|
||||
};
|
||||
|
||||
export type WidgetResources = {
|
||||
definition: WidgetDefinition;
|
||||
Component: ComponentType<WidgetComponentProps<WidgetKind>>;
|
||||
};
|
||||
|
||||
const moduleLoaders: Record<WidgetKind, () => Promise<WidgetModule>> = {
|
||||
clock: () => import("./clock") as Promise<WidgetModule>,
|
||||
weather: () => import("./weather") as Promise<WidgetModule>,
|
||||
@@ -69,6 +78,67 @@ const moduleLoaders: Record<WidgetKind, () => Promise<WidgetModule>> = {
|
||||
customApi: () => import("./custom-api") as Promise<WidgetModule>,
|
||||
};
|
||||
|
||||
// Keep these imports explicit so Turbopack can create one discoverable chunk per
|
||||
// widget implementation. Loading this registry does not load the implementations.
|
||||
const componentLoaders: Record<WidgetKind, () => Promise<WidgetComponentModule>> = {
|
||||
clock: () => import("./clock/component") as Promise<WidgetComponentModule>,
|
||||
weather: () => import("./weather/component") as Promise<WidgetComponentModule>,
|
||||
app: () => import("./app/component") as Promise<WidgetComponentModule>,
|
||||
archiveTeamWarrior: () => import("./archive-team-warrior/component") as Promise<WidgetComponentModule>,
|
||||
anchorNote: () => import("./anchor-note/component") as Promise<WidgetComponentModule>,
|
||||
notebook: () => import("./notebook/component") as Promise<WidgetComponentModule>,
|
||||
iframe: () => import("./iframe/component") as Promise<WidgetComponentModule>,
|
||||
video: () => import("./video/component") as Promise<WidgetComponentModule>,
|
||||
dnsHoleSummary: () => import("./dns-hole/summary/component") as Promise<WidgetComponentModule>,
|
||||
dnsHoleControls: () => import("./dns-hole/controls/component") as Promise<WidgetComponentModule>,
|
||||
"smartHome-entityState": () => import("./smart-home/entity-state/component") as Promise<WidgetComponentModule>,
|
||||
"smartHome-executeAutomation": () =>
|
||||
import("./smart-home/execute-automation/component") as Promise<WidgetComponentModule>,
|
||||
stockPrice: () => import("./stocks/component") as Promise<WidgetComponentModule>,
|
||||
mediaServer: () => import("./media-server/component") as Promise<WidgetComponentModule>,
|
||||
calendar: () => import("./calendar/component") as Promise<WidgetComponentModule>,
|
||||
downloads: () => import("./downloads/component") as Promise<WidgetComponentModule>,
|
||||
"mediaRequests-requestList": () => import("./media-requests/list/component") as Promise<WidgetComponentModule>,
|
||||
"mediaRequests-requestStats": () => import("./media-requests/stats/component") as Promise<WidgetComponentModule>,
|
||||
mediaMissing: () => import("./media-missing/component") as Promise<WidgetComponentModule>,
|
||||
networkControllerSummary: () => import("./network-controller/summary/component") as Promise<WidgetComponentModule>,
|
||||
networkControllerStatus: () =>
|
||||
import("./network-controller/network-status/component") as Promise<WidgetComponentModule>,
|
||||
rssFeed: () => import("./rssFeed/component") as Promise<WidgetComponentModule>,
|
||||
bookmarks: () => import("./bookmarks/component") as Promise<WidgetComponentModule>,
|
||||
bazarr: () => import("./bazarr/component") as Promise<WidgetComponentModule>,
|
||||
indexerManager: () => import("./indexer-manager/component") as Promise<WidgetComponentModule>,
|
||||
healthMonitoring: () => import("./health-monitoring/component") as Promise<WidgetComponentModule>,
|
||||
mediaTranscoding: () => import("./media-transcoding/component") as Promise<WidgetComponentModule>,
|
||||
minecraftServerStatus: () => import("./minecraft/server-status/component") as Promise<WidgetComponentModule>,
|
||||
dockerContainers: () => import("./docker/component") as Promise<WidgetComponentModule>,
|
||||
releases: () => import("./releases/component") as Promise<WidgetComponentModule>,
|
||||
firewall: () => import("./firewall/component") as Promise<WidgetComponentModule>,
|
||||
notifications: () => import("./notifications/component") as Promise<WidgetComponentModule>,
|
||||
mediaReleases: () => import("./media-releases/component") as Promise<WidgetComponentModule>,
|
||||
systemResources: () => import("./system-resources/component") as Promise<WidgetComponentModule>,
|
||||
coolify: () => import("./coolify/component") as Promise<WidgetComponentModule>,
|
||||
systemDisks: () => import("./system-disks/component") as Promise<WidgetComponentModule>,
|
||||
timetable: () => import("./timetable/component") as Promise<WidgetComponentModule>,
|
||||
"immich-serverStats": () => import("./immich/server-stats/component") as Promise<WidgetComponentModule>,
|
||||
"immich-albumCarousel": () => import("./immich/album-carousel/component") as Promise<WidgetComponentModule>,
|
||||
paperlessNgx: () => import("./paperless-ngx/component") as Promise<WidgetComponentModule>,
|
||||
patchmon: () => import("./patchmon/component") as Promise<WidgetComponentModule>,
|
||||
tracearr: () => import("./tracearr/component") as Promise<WidgetComponentModule>,
|
||||
speedtestTracker: () => import("./speedtest-tracker/component") as Promise<WidgetComponentModule>,
|
||||
uptimeKuma: () => import("./uptime-kuma/component") as Promise<WidgetComponentModule>,
|
||||
audioStats: () => import("./audio-stats/component") as Promise<WidgetComponentModule>,
|
||||
umami: () => import("./umami/component") as Promise<WidgetComponentModule>,
|
||||
vpn: () => import("./vpn/component") as Promise<WidgetComponentModule>,
|
||||
ups: () => import("./ups/component") as Promise<WidgetComponentModule>,
|
||||
beszelSystemTable: () => import("./beszel-system-table/component") as Promise<WidgetComponentModule>,
|
||||
beszelSystemGrid: () => import("./beszel-system-grid/component") as Promise<WidgetComponentModule>,
|
||||
beszelAlerts: () => import("./beszel-alerts/component") as Promise<WidgetComponentModule>,
|
||||
beszelSystemStats: () => import("./beszel-system-stats/component") as Promise<WidgetComponentModule>,
|
||||
traefik: () => import("./traefik/component") as Promise<WidgetComponentModule>,
|
||||
customApi: () => import("./custom-api/component") as Promise<WidgetComponentModule>,
|
||||
};
|
||||
|
||||
const definitionPromises = new Map<WidgetKind, Promise<WidgetDefinition>>();
|
||||
|
||||
export const widgetKinds = Object.keys(moduleLoaders) as WidgetKind[];
|
||||
@@ -96,6 +166,25 @@ export const loadWidgetModule = createRetryableLoader(
|
||||
new Map(Object.entries(moduleLoaders) as [WidgetKind, () => Promise<WidgetModule>][]),
|
||||
);
|
||||
|
||||
export const loadWidgetComponent = createRetryableLoader(
|
||||
new Map(Object.entries(componentLoaders) as [WidgetKind, () => Promise<WidgetComponentModule>][]),
|
||||
);
|
||||
|
||||
export const loadWidgetResources = createRetryableLoader(
|
||||
new Map(
|
||||
(Object.keys(moduleLoaders) as WidgetKind[]).map((kind) => [
|
||||
kind,
|
||||
async () => {
|
||||
const [{ definition }, { default: Component }] = await Promise.all([
|
||||
loadWidgetModule(kind),
|
||||
loadWidgetComponent(kind),
|
||||
]);
|
||||
return { definition, Component } satisfies WidgetResources;
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
export const loadWidgetDefinition = (kind: WidgetKind) => {
|
||||
const existing = definitionPromises.get(kind);
|
||||
if (existing) return existing;
|
||||
|
||||
@@ -9,6 +9,7 @@ const pageSizeOptions = ["10", "20", "30", "50"] as const;
|
||||
|
||||
export const { componentLoader, definition } = createWidgetDefinition("mediaMissing", {
|
||||
icon: IconMovie,
|
||||
queryKey: [["widget", "mediaOrganizer"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showMissing: factory.switch({ defaultValue: true }),
|
||||
|
||||
@@ -11,6 +11,7 @@ const mediaRequestStatusValues = ["pending", "approved", "declined", "failed", "
|
||||
|
||||
export const { componentLoader, definition } = createWidgetDefinition("mediaRequests-requestList", {
|
||||
icon: IconZoomQuestion,
|
||||
queryKey: [["widget", "mediaRequests"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
linksTargetNewTab: factory.switch({
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createWidgetDefinition } from "../../definition";
|
||||
|
||||
export const { componentLoader, definition } = createWidgetDefinition("mediaRequests-requestStats", {
|
||||
icon: IconChartBar,
|
||||
queryKey: [["widget", "mediaRequests"]],
|
||||
createOptions() {
|
||||
return {};
|
||||
},
|
||||
|
||||
@@ -14,11 +14,11 @@ import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zodErrorMap } from "@homarr/validation/form/i18n";
|
||||
|
||||
import { widgetImports } from "..";
|
||||
import { getInputForType } from "../_inputs";
|
||||
import { FormProvider, useForm } from "../_inputs/form";
|
||||
import type { BoardItemAdvancedOptions } from "../../../validation/src/shared";
|
||||
import type { OptionsBuilderResult } from "../options";
|
||||
import type { WidgetDefinition } from "../definition";
|
||||
import { OPTIONS_SUPER_REFINE } from "../options";
|
||||
import type { IntegrationSelectOption } from "../widget-integration-select";
|
||||
import { WidgetIntegrationSelect } from "../widget-integration-select";
|
||||
@@ -32,8 +32,9 @@ export interface WidgetEditModalState {
|
||||
advancedOptions: BoardItemAdvancedOptions;
|
||||
}
|
||||
|
||||
interface ModalProps<TSort extends WidgetKind> {
|
||||
export interface WidgetEditModalProps<TSort extends WidgetKind> {
|
||||
kind: TSort;
|
||||
definition: WidgetDefinition;
|
||||
value: WidgetEditModalState;
|
||||
onSuccessfulEdit: (value: WidgetEditModalState) => void;
|
||||
integrationData: IntegrationSelectOption[];
|
||||
@@ -43,7 +44,7 @@ interface ModalProps<TSort extends WidgetKind> {
|
||||
appId?: string;
|
||||
}
|
||||
|
||||
export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, innerProps }) => {
|
||||
export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const { data: session } = useSession();
|
||||
const [advancedOptions, setAdvancedOptions] = useState<BoardItemAdvancedOptions>(innerProps.value.advancedOptions);
|
||||
@@ -53,7 +54,7 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
z.config({
|
||||
customError: zodErrorMap(t),
|
||||
});
|
||||
const { definition } = widgetImports[innerProps.kind];
|
||||
const { definition } = innerProps;
|
||||
const options = definition.createOptions(innerProps.settings) as Record<string, OptionsBuilderResult[string]>;
|
||||
const optionsSuperRefine = (options as Record<symbol, unknown>)[OPTIONS_SUPER_REFINE] as
|
||||
| ((data: Record<string, unknown>, ctx: z.RefinementCtx) => void)
|
||||
@@ -124,10 +125,7 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
<WidgetIntegrationSelect
|
||||
label={t("item.edit.field.integrations.label")}
|
||||
data={innerProps.integrationData}
|
||||
canSelectMultiple={
|
||||
((widgetImports[innerProps.kind].definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity) >
|
||||
1
|
||||
}
|
||||
canSelectMultiple={((definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity) > 1}
|
||||
{...form.getInputProps("integrationIds")}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
import { cache } from "react";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { db } from "@homarr/db";
|
||||
import { getServerSettingsAsync } from "@homarr/db/queries";
|
||||
import { getRscServerSettingsAsync } from "@homarr/api/server-settings-server";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import { createSettings } from "@homarr/settings/creator";
|
||||
|
||||
import { loadWidgetDefinition, reduceWidgetOptionsWithDefinition } from "./manifest";
|
||||
import prefetchForApps from "./app/prefetch";
|
||||
import prefetchForBookmarks from "./bookmarks/prefetch";
|
||||
import prefetchForDownloads from "./downloads/prefetch";
|
||||
import type { Prefetch, WidgetOptionsRecordOf } from "./definition";
|
||||
import type { inferOptionsFromCreator } from "./options";
|
||||
|
||||
const cachedGetServerSettingsAsync = cache(getServerSettingsAsync);
|
||||
|
||||
const prefetchCallbacks: Partial<{
|
||||
[TKind in WidgetKind]: Prefetch<TKind>;
|
||||
}> = {
|
||||
bookmarks: prefetchForBookmarks,
|
||||
app: prefetchForApps,
|
||||
downloads: prefetchForDownloads,
|
||||
};
|
||||
|
||||
export const prefetchForKindAsync = async <TKind extends WidgetKind>(
|
||||
@@ -36,8 +30,7 @@ export const prefetchForKindAsync = async <TKind extends WidgetKind>(
|
||||
return;
|
||||
}
|
||||
|
||||
const serverSettings = await cachedGetServerSettingsAsync(db);
|
||||
const definition = await loadWidgetDefinition(kind);
|
||||
const [serverSettings, definition] = await Promise.all([getRscServerSettingsAsync(), loadWidgetDefinition(kind)]);
|
||||
|
||||
const itemsWithDefaultOptions = items.map((item) => ({
|
||||
...item,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { optionsBuilder } from "../../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("smartHome-entityState", {
|
||||
icon: IconBinaryTree,
|
||||
queryKey: [["widget", "smartHome"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
entityId: factory.text({
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
import { createLanguageMapping } from "@homarr/translation";
|
||||
|
||||
import { widgetImports } from "..";
|
||||
import { loadAllWidgetDefinitions } from "../manifest";
|
||||
|
||||
describe("Widget properties with description should have matching translations", async () => {
|
||||
const enTranslation = await createLanguageMapping().en();
|
||||
objectEntries(widgetImports).forEach(([key, value]) => {
|
||||
Object.entries(value.definition.createOptions({} as SettingsContextProps)).forEach(([optionKey, optionValue_]) => {
|
||||
const widgetDefinitions = await loadAllWidgetDefinitions();
|
||||
const enTranslation = await createLanguageMapping().en();
|
||||
|
||||
describe("Widget properties with description should have matching translations", () => {
|
||||
for (const [key, definition] of widgetDefinitions) {
|
||||
Object.entries(definition.createOptions({} as SettingsContextProps)).forEach(([optionKey, optionValue_]) => {
|
||||
const optionValue = optionValue_ as { withDescription: boolean };
|
||||
it(`should have matching translations for ${optionKey} option description of ${key} widget`, () => {
|
||||
const option = enTranslation.default.widget[key].option;
|
||||
@@ -21,13 +22,12 @@ describe("Widget properties with description should have matching translations",
|
||||
expect("description" in value).toBe(optionValue.withDescription);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("Widget properties should have matching name translations", async () => {
|
||||
const enTranslation = await createLanguageMapping().en();
|
||||
objectEntries(widgetImports).forEach(([key, value]) => {
|
||||
Object.keys(value.definition.createOptions({} as SettingsContextProps)).forEach((optionKey) => {
|
||||
describe("Widget properties should have matching name translations", () => {
|
||||
for (const [key, definition] of widgetDefinitions) {
|
||||
Object.keys(definition.createOptions({} as SettingsContextProps)).forEach((optionKey) => {
|
||||
it(`should have matching translations for ${optionKey} option name of ${key} widget`, () => {
|
||||
const option = enTranslation.default.widget[key].option;
|
||||
if (!(optionKey in option)) {
|
||||
@@ -38,5 +38,5 @@ describe("Widget properties should have matching name translations", async () =>
|
||||
expect("label" in value).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -43,7 +43,7 @@ export default function WeatherWidget({ isEditMode, options }: WidgetComponentPr
|
||||
}
|
||||
|
||||
interface WeatherProps extends Pick<WidgetComponentProps<"weather">, "options"> {
|
||||
weather: RouterOutputs["widget"]["weather"]["atLocation"];
|
||||
weather: NonNullable<RouterOutputs["widget"]["weather"]["atLocation"]>;
|
||||
}
|
||||
|
||||
const DailyWeather = ({ options, weather }: WeatherProps) => {
|
||||
|
||||
Reference in new issue
Block a user