Skip to content

Build your personal knowledge base with Trilium Notes

feat(resources): list what else is in the resources folder

Elian Doranbf82d931f72e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 6825e03fb2..417788a18d 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4651,6 +4651,13 @@
"no_resources": "Nothing has been downloaded yet.",
"delete": "Delete",
"delete_confirmation": "Delete {{title}}? It is downloaded again the next time a feature needs it.",
- "open_folder": "Open folder"
+ "open_folder": "Open folder",
+ "outdated": "Older version",
+ "outdated_description": "Files of an earlier version of this resource, which its current version does not use.",
+ "unregistered": "Not used",
+ "unregistered_description": "A downloaded resource that no feature of this app uses.",
+ "unknown": "Unknown",
+ "unknown_description": "Not downloaded by Trilium.",
+ "delete_foreign_confirmation": "Delete {{name}}? No feature of this app uses it."
}
}
diff --git a/apps/client/src/widgets/type_widgets/options/resources.css b/apps/client/src/widgets/type_widgets/options/resources.css
index be42853711..8e409b3ef2 100644
--- a/apps/client/src/widgets/type_widgets/options/resources.css
+++ b/apps/client/src/widgets/type_widgets/options/resources.css
@@ -18,6 +18,14 @@
text-align: end;
}
+ .resources-foreign {
+ .resources-icon,
+ .tn-card-option-label,
+ .resources-status {
+ opacity: 0.6;
+ }
+ }
+
.resources-actions {
--resources-actions-gap: 12px;
diff --git a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx b/apps/client/src/widgets/type_widgets/options/resources.spec.tsx
index 91ea656b70..9026d205f5 100644
--- a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/resources.spec.tsx
@@ -1,16 +1,18 @@
-import type { ResourceInfo, WebSocketMessage } from "@triliumnext/commons";
+import type { ForeignResourceEntry, ResourceInfo, WebSocketMessage } from "@triliumnext/commons";
import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
resources: [] as ResourceInfo[],
+ foreign: [] as ForeignResourceEntry[],
freeBytes: null as number | null,
requests: 0,
confirmed: true,
removed: [] as string[],
electron: true,
opened: [] as string[],
+ revealed: [] as string[],
handlers: [] as ((message: WebSocketMessage) => void)[]
}));
@@ -21,7 +23,9 @@ vi.mock("../../../services/server", () => ({
return [];
}
mocks.requests++;
- return { resources: mocks.resources, freeBytes: mocks.freeBytes, download: null };
+ return {
+ resources: mocks.resources, foreign: mocks.foreign, freeBytes: mocks.freeBytes, download: null
+ };
},
remove: async (url: string) => {
mocks.removed.push(url);
@@ -58,6 +62,9 @@ vi.mock("../../../services/open", () => ({
default: {
openDirectory: async (directory: string) => {
mocks.opened.push(directory);
+ },
+ revealFile: async (filePath: string) => {
+ mocks.revealed.push(filePath);
}
}
}));
@@ -78,6 +85,8 @@ beforeEach(() => {
resource({ id: "test.partial", downloadedSize: 4 * MIB }),
resource({ id: "test.missing" })
];
+ mocks.foreign = [];
+ mocks.revealed = [];
mocks.requests = 0;
mocks.freeBytes = null;
mocks.confirmed = true;
@@ -161,6 +170,46 @@ describe("ResourcesSettings", () => {
expect(description()).toBeNull();
});
+ it("lists the foreign entries after the resources, counting them in the space used", async () => {
+ mocks.foreign = [
+ foreign({ name: "notes.txt", kind: "unknown", size: 1 * MIB, isDirectory: false }),
+ foreign({
+ name: "test.installed-000000000000", kind: "outdated", resourceId: "test.installed",
+ title: "Old model", icon: "bx bx-captions", size: 1024 * MIB
+ })
+ ];
+ await open();
+
+ const rows = [ ...host.querySelectorAll(".resources-item") ];
+ expect(rows.map((row) => row.querySelector(".tn-card-option-title")?.textContent))
+ .toEqual([ "test.installed", "test.partial", "notes.txt", "Old model" ]);
+ expect(rows.slice(2).map((row) => row.querySelector(".resources-status small")?.textContent))
+ .toEqual([ "resources_options.unknown", "resources_options.outdated" ]);
+ expect(rows.map((row) => row.classList.contains("resources-foreign")))
+ .toEqual([ false, false, true, true ]);
+ expect(rows[2].querySelector(".resources-icon")?.className).toContain("bx-file");
+ expect(rows[3].querySelector(".resources-icon")?.className).toContain("bx-captions");
+ expect(host.querySelector(".resources-total .resources-size")?.textContent).toBe("3.00 GiB");
+ });
+
+ it("opens and deletes a foreign entry by its name", async () => {
+ mocks.resources = [];
+ mocks.foreign = [
+ foreign({ name: "notes.txt", kind: "unknown", isDirectory: false }),
+ foreign({ name: "stray" })
+ ];
+ await open();
+ const [ file, directory ] = [ ...host.querySelectorAll(".resources-item") ];
+
+ await act(async () => file.querySelector<HTMLElement>(".bx-folder-open")?.click());
+ await act(async () => directory.querySelector<HTMLElement>(".bx-folder-open")?.click());
+ expect(mocks.revealed).toEqual([ "/data/resources/notes.txt" ]);
+ expect(mocks.opened).toEqual([ "/data/resources/stray" ]);
+
+ await act(async () => directory.querySelector<HTMLElement>(".destructive-action-icon")?.click());
+ expect(mocks.removed).toEqual([ "resources/foreign/stray" ]);
+ });
+
it("shows an empty state when nothing is downloaded", async () => {
mocks.resources = [ resource({ id: "test.missing" }) ];
await open();
@@ -187,6 +236,19 @@ describe("ResourcesSettings", () => {
});
});
+function foreign(overrides: Partial<ForeignResourceEntry> & { name: string }): ForeignResourceEntry {
+ return {
+ path: `/data/resources/${overrides.name}`,
+ kind: "unknown",
+ resourceId: null,
+ title: null,
+ icon: null,
+ size: MIB,
+ isDirectory: true,
+ ...overrides
+ };
+}
+
function resource(overrides: Partial<ResourceInfo> & { id: string }): ResourceInfo {
return {
title: overrides.id,
diff --git a/apps/client/src/widgets/type_widgets/options/resources.tsx b/apps/client/src/widgets/type_widgets/options/resources.tsx
index 66f59a4727..74509f5a9b 100644
--- a/apps/client/src/widgets/type_widgets/options/resources.tsx
+++ b/apps/client/src/widgets/type_widgets/options/resources.tsx
@@ -1,6 +1,10 @@
import "./resources.css";
-import type { ResourceInfo, ResourcesStatusResponse, WebSocketMessage } from "@triliumnext/commons";
+import type {
+ ForeignResourceEntry, ResourceInfo, ResourcesStatusResponse, WebSocketMessage
+} from "@triliumnext/commons";
+import clsx from "clsx";
+import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useState } from "preact/hooks";
import dialogService from "../../../services/dialog";
@@ -15,7 +19,10 @@ import Icon from "../../react/Icon";
import NoItems from "../../react/NoItems";
import OptionsPageHeader from "./components/OptionsPageHeader";
-/** Lists the resources installed on this device, and the ones an interrupted download left partly fetched. */
+/**
+ * Lists the resources installed on this device, the ones an interrupted download left partly
+ * fetched, and whatever else is in the resources directory.
+ */
export default function ResourcesSettings() {
const [ status, refresh ] = useResources();
@@ -28,12 +35,8 @@ export default function ResourcesSettings() {
heading={t("resources_options.list_title")}
description={t("resources_options.list_description")}
>
- {status.resources.length > 0 ? (
- <ResourceRows
- resources={status.resources}
- freeBytes={status.freeBytes}
- onDeleted={refresh}
- />
+ {status.resources.length > 0 || status.foreign.length > 0 ? (
+ <ResourceRows {...status} onDeleted={refresh} />
) : (
<CardSection>
<NoItems icon="bx bx-download" text={t("resources_options.no_resources")} size="small" />
@@ -45,15 +48,22 @@ export default function ResourcesSettings() {
);
}
+interface ResourcesStatus {
+ resources: ResourceInfo[];
+ foreign: ForeignResourceEntry[];
+ freeBytes: number | null;
+}
+
/**
- * The resources installed or partly downloaded and the free space where they are stored, fetched
- * again whenever a download ends.
+ * The resources installed or partly downloaded, the foreign entries and the free space where they
+ * are stored, fetched again whenever a download ends.
*/
function useResources() {
- const [ status, setStatus ] = useState<Pick<ResourcesStatusResponse, "resources" | "freeBytes">>();
+ const [ status, setStatus ] = useState<ResourcesStatus>();
const refresh = useCallback(() => {
- void server.get<ResourcesStatusResponse>("resources").then(({ resources, freeBytes }) => setStatus({
+ void server.get<ResourcesStatusResponse>("resources").then(({ resources, foreign, freeBytes }) => setStatus({
resources: resources.filter(({ downloadedSize }) => downloadedSize > 0),
+ foreign: foreign ?? [],
freeBytes
}));
}, []);
@@ -72,21 +82,23 @@ function useResources() {
return [ status, refresh ] as const;
}
-/** The resources and the space they use, every size in one unit so that the column adds up. */
-interface ResourceRowsProps {
- resources: ResourceInfo[];
- freeBytes: number | null;
+interface ResourceRowsProps extends ResourcesStatus {
onDeleted: () => void;
}
-function ResourceRows({ resources, freeBytes, onDeleted }: ResourceRowsProps) {
- const used = resources.reduce((total, { downloadedSize }) => total + downloadedSize, 0);
+/** The entries and the space they use, every size in one unit so that the column adds up. */
+function ResourceRows({ resources, foreign, freeBytes, onDeleted }: ResourceRowsProps) {
+ const used = resources.reduce((total, { downloadedSize }) => total + downloadedSize, 0)
+ + foreign.reduce((total, { size }) => total + size, 0);
const unitOf = Math.max(used, ...resources.map(({ size }) => size));
return (
<>
{resources.map((resource) => (
<ResourceRow key={resource.id} resource={resource} unitOf={unitOf} onDeleted={onDeleted} />
))}
+ {foreign.map((entry) => (
+ <ForeignRow key={entry.name} entry={entry} unitOf={unitOf} onDeleted={onDeleted} />
+ ))}
<CardSection className="tn-card-option resources-total">
<div className="tn-card-option-label">
<span className="tn-card-option-title">{t("resources_options.space_used")}</span>
@@ -120,34 +132,101 @@ function ResourceRow({ resource, unitOf, onDeleted }: ResourceRowProps) {
}
return (
- <CardSection className="tn-card-option resources-item">
- <Icon icon={resource.icon} className="resources-icon" />
+ <EntryRow
+ icon={resource.icon}
+ title={resource.title}
+ size={formatSize(resource.size, 2, unitOf)}
+ status={getStatusText(resource)}
+ onOpen={directory ? () => void openService.openDirectory(directory) : undefined}
+ onDelete={() => void remove()}
+ >
+ <small className="tn-card-option-description">{resource.description}</small>
+ <small className="tn-card-option-description">
+ {t("resource_download.sources", { sources: resource.sources.join(", ") })}
+ {" · "}
+ {t("resource_download.license", { license: resource.license })}
+ </small>
+ </EntryRow>
+ );
+}
+
+interface ForeignRowProps {
+ entry: ForeignResourceEntry;
+ unitOf: number;
+ onDeleted: () => void;
+}
+
+/** An entry of the resources directory that no registered resource accounts for. */
+function ForeignRow({ entry, unitOf, onDeleted }: ForeignRowProps) {
+ async function remove() {
+ if (!await dialogService.confirm(t("resources_options.delete_foreign_confirmation", { name: entry.name }))) {
+ return;
+ }
+ await server.remove(`resources/foreign/${encodeURIComponent(entry.name)}`);
+ onDeleted();
+ }
+
+ function open() {
+ void (entry.isDirectory ? openService.openDirectory(entry.path) : openService.revealFile(entry.path));
+ }
+
+ return (
+ <EntryRow
+ className="resources-foreign"
+ icon={entry.icon ?? (entry.isDirectory ? "bx bx-folder" : "bx bx-file")}
+ title={entry.title ?? entry.name}
+ size={formatSize(entry.size, 2, unitOf)}
+ status={t(`resources_options.${entry.kind}`)}
+ onOpen={open}
+ onDelete={() => void remove()}
+ >
+ <small className="tn-card-option-description">
+ {t(`resources_options.${entry.kind}_description`)}
+ </small>
+ {entry.title && <small className="tn-card-option-description">{entry.name}</small>}
+ </EntryRow>
+ );
+}
+
+interface EntryRowProps {
+ className?: string;
+ icon: string;
+ title: string;
+ /** The lines below the title. */
+ children: ComponentChildren;
+ size: string;
+ status: string;
+ /** Opens the entry in the file manager, which only the desktop app can do. */
+ onOpen?: () => void;
+ onDelete: () => void;
+}
+
+/** One row of the list: icon, title and description, size and status, then its actions. */
+function EntryRow({ className, icon, title, children, size, status, onOpen, onDelete }: EntryRowProps) {
+ return (
+ <CardSection className={clsx("tn-card-option resources-item", className)}>
+ <Icon icon={icon} className="resources-icon" />
<div className="tn-card-option-label">
- <span className="tn-card-option-title">{resource.title}</span>
- <small className="tn-card-option-description">{resource.description}</small>
- <small className="tn-card-option-description">
- {t("resource_download.sources", { sources: resource.sources.join(", ") })}
- {" · "}
- {t("resource_download.license", { license: resource.license })}
- </small>
+ <span className="tn-card-option-title">{title}</span>
+ {children}
</div>
<div className="tn-card-option-value resources-status">
- <span className="resources-size">{formatSize(resource.size, 2, unitOf)}</span>
- <small className="tn-card-option-description">{getStatusText(resource)}</small>
+ <span className="resources-size">{size}</span>
+ <small className="tn-card-option-description">{status}</small>
</div>
<div className="resources-actions">
- {directory && isElectron() && (
+ {onOpen && isElectron() && (
<ActionButton
icon="bx bx-folder-open"
text={t("resources_options.open_folder")}
- onClick={() => void openService.openDirectory(directory)}
+ onClick={onOpen}
/>
)}
<ActionButton
className="destructive-action-icon"
icon="bx bx-trash"
text={t("resources_options.delete")}
- onClick={() => void remove()}
+ onClick={onDelete}
/>
</div>
</CardSection>
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index d06dfedb52..1be60dd31b 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -587,6 +587,7 @@
"http-error": "Downloading {{name}} failed with HTTP status {{status}}.",
"size-mismatch": "{{name}} does not have the expected size.",
"hash-mismatch": "{{name}} does not match its expected checksum, so it was discarded.",
- "delete-while-downloading": "{{- title}} is being downloaded. Cancel the download before deleting it."
+ "delete-while-downloading": "{{- title}} is being downloaded. Cancel the download before deleting it.",
+ "not-foreign": "{{- name}} is not an unused entry of the resources folder."
}
}
diff --git a/apps/server/src/routes/api/resources.ts b/apps/server/src/routes/api/resources.ts
index cd05a41807..479550ae6d 100644
--- a/apps/server/src/routes/api/resources.ts
+++ b/apps/server/src/routes/api/resources.ts
@@ -27,6 +27,11 @@ async function deleteResource(req: Request<{ id: string }>) {
await resources.delete(req.params.id);
}
+/** `DELETE /api/resources/foreign/:name`: deletes an entry of the resources directory that is no resource. */
+async function deleteForeign(req: Request<{ name: string }>) {
+ await resources.deleteForeign(req.params.name);
+}
+
function parseIds(ids: unknown) {
const list = typeof ids === "string" ? ids.split(",") : ids;
if (!Array.isArray(list) || !list.length || !list.every((id) => typeof id === "string")) {
@@ -39,5 +44,6 @@ export default {
getStatus,
startDownload,
cancelDownload,
- deleteResource
+ deleteResource,
+ deleteForeign
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 2a63ff4fbd..78d138a82b 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -201,6 +201,7 @@ function register(app: express.Application) {
asyncApiRoute(GET, "/api/resources", resourcesRoute.getStatus);
apiRoute(PST, "/api/resources/download", resourcesRoute.startDownload);
apiRoute(PST, "/api/resources/download/:downloadId/cancel", resourcesRoute.cancelDownload);
+ asyncApiRoute(DEL, "/api/resources/foreign/:name", resourcesRoute.deleteForeign);
asyncApiRoute(DEL, "/api/resources/:id", resourcesRoute.deleteResource);
app.use("", router);
diff --git a/apps/server/src/services/resources.spec.ts b/apps/server/src/services/resources.spec.ts
index ec674b0498..e8b2d94b79 100644
--- a/apps/server/src/services/resources.spec.ts
+++ b/apps/server/src/services/resources.spec.ts
@@ -321,6 +321,44 @@ describe("ResourceManager", () => {
expect((await manager.getStatus([ "test.stalled" ])).resources[0].downloadedSize).toBe(0);
});
+ it("lists the entries of its directory that are no registered resource, and deletes them", async () => {
+ manager.register(defineModel());
+ manager.startDownload([ "test.model" ]);
+ expect((await waitForEnd()).status).toBe("succeeded");
+ const write = (name: string, size: number) => {
+ fs.mkdirSync(path.join(baseDir, path.dirname(name)), { recursive: true });
+ fs.writeFileSync(path.join(baseDir, name), Buffer.alloc(size));
+ };
+ write("test.model-000000000000/nested/model.bin", 300);
+ write("test.removed-123456789abc/model.bin", 200);
+ write("stray/a.bin", 50);
+ write("stray/b.bin", 25);
+ write("notes.txt", 10);
+
+ const { foreign } = await manager.getStatus();
+ expect(foreign?.map(({ name, kind, resourceId, size, isDirectory }) => ({
+ name, kind, resourceId, size, isDirectory
+ }))).toEqual([
+ { name: "notes.txt", kind: "unknown", resourceId: null, size: 10, isDirectory: false },
+ { name: "stray", kind: "unknown", resourceId: null, size: 75, isDirectory: true },
+ { name: "test.model-000000000000", kind: "outdated", resourceId: "test.model", size: 300, isDirectory: true },
+ { name: "test.removed-123456789abc", kind: "unregistered", resourceId: "test.removed", size: 200, isDirectory: true }
+ ]);
+ expect(foreign?.[1].path).toBe(path.join(baseDir, "stray"));
+ expect((await manager.getStatus([ "test.model" ])).foreign).toBeUndefined();
+
+ await manager.deleteForeign("stray");
+ await manager.deleteForeign("notes.txt");
+ expect(fs.existsSync(path.join(baseDir, "stray"))).toBe(false);
+ expect(fs.existsSync(path.join(baseDir, "notes.txt"))).toBe(false);
+
+ const installed = path.basename(manager.getPath("test.model") ?? "");
+ for (const name of [ installed, "..", "missing", "stray/../notes.txt", "" ]) {
+ await expect(manager.deleteForeign(name)).rejects.toThrow();
+ }
+ expect(manager.getPath("test.model")).not.toBeNull();
+ });
+
it("refuses invalid or unknown resources", () => {
manager.register(defineModel());
expect(() => manager.register(defineModel())).toThrow(/already registered/);
diff --git a/apps/server/src/services/resources.ts b/apps/server/src/services/resources.ts
index fb0119337c..7dc4ad5844 100644
--- a/apps/server/src/services/resources.ts
+++ b/apps/server/src/services/resources.ts
@@ -1,4 +1,6 @@
-import type { ResourceDownloadProgress, ResourceInfo, ResourcesStatusResponse } from "@triliumnext/commons";
+import type {
+ ForeignResourceEntry, ResourceDownloadProgress, ResourceInfo, ResourcesStatusResponse
+} from "@triliumnext/commons";
import { getLog, utils, ValidationError, ws } from "@triliumnext/core";
import { t } from "i18next";
import { createHash, type Hash } from "node:crypto";
@@ -41,6 +43,7 @@ interface Download {
type VerifiedFiles = Record<string, { size: number; mtimeMs: number }>;
const ID_PATTERN = /^[a-z0-9-]+(\.[a-z0-9-]+)*$/;
+const CONTENT_HASH_PATTERN = /^[0-9a-f]{12}$/;
const PROGRESS_INTERVAL_MS = 250;
/** How many hex digits of the files' combined hash a resource's directory name carries. */
const CONTENT_HASH_LENGTH = 12;
@@ -88,13 +91,17 @@ export class ResourceManager {
return isInstalled ? directory : null;
}
- /** Reports the resources `ids`, or every registered one when `ids` is left out. */
+ /**
+ * Reports the resources `ids`, or every registered one when `ids` is left out, together with
+ * the entries of the resources directory that are none of them.
+ */
async getStatus(ids?: string[]): Promise<ResourcesStatusResponse> {
const definitions = ids
? ids.map((id) => this.getDefinition(id))
: [ ...this.definitions.values() ];
return {
resources: definitions.map((definition) => this.getInfo(definition)),
+ ...(ids ? {} : { foreign: await this.getForeignEntries() }),
freeBytes: await this.getFreeBytes(),
download: this.findDownload(definitions.map(({ id }) => id))?.progress ?? null
};
@@ -211,6 +218,53 @@ export class ResourceManager {
}
}
+ /** Deletes `name` from the resources directory, which must be one of its foreign entries. */
+ async deleteForeign(name: string) {
+ const entries = await this.getForeignEntries();
+ const entry = entries.find((foreign) => foreign.name === name);
+ if (!entry) {
+ throw new ValidationError(t("resources.not-foreign", { name }));
+ }
+ await fs.promises.rm(entry.path, { recursive: true, force: true });
+ getLog().info(`Resources: deleted ${entry.path}.`);
+ }
+
+ /**
+ * The entries of the resources directory that are not the directory of a registered resource,
+ * sorted by name. A directory named `<id>-<hash>` is `outdated` when `id` is registered and
+ * `unregistered` otherwise.
+ */
+ private async getForeignEntries(): Promise<ForeignResourceEntry[]> {
+ let dirents: fs.Dirent[];
+ try {
+ dirents = await fs.promises.readdir(this.baseDir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const current = new Set([ ...this.directories.values() ].map((directory) => path.basename(directory)));
+ const entries: ForeignResourceEntry[] = [];
+ for (const dirent of dirents) {
+ if (current.has(dirent.name)) {
+ continue;
+ }
+ const entryPath = path.join(this.baseDir, dirent.name);
+ const isDirectory = dirent.isDirectory();
+ const resourceId = isDirectory ? parseDirectoryName(dirent.name) : null;
+ const definition = resourceId ? this.definitions.get(resourceId) : undefined;
+ entries.push({
+ name: dirent.name,
+ path: entryPath,
+ kind: definition ? "outdated" : resourceId ? "unregistered" : "unknown",
+ resourceId,
+ title: definition?.title() ?? null,
+ icon: definition?.icon ?? null,
+ size: await getEntrySize(entryPath),
+ isDirectory
+ });
+ }
+ return entries.sort((a, b) => a.name.localeCompare(b.name));
+ }
+
private getDefinition(id: string) {
const definition = this.definitions.get(id);
if (!definition) {
@@ -350,6 +404,27 @@ function validateDefinition({ id, files }: ResourceDefinition) {
}
}
+/** The resource ID a directory named `<id>-<hash>` carries, or `null` for any other name. */
+function parseDirectoryName(name: string) {
+ const separator = name.lastIndexOf("-");
+ const id = name.slice(0, separator);
+ const hash = name.slice(separator + 1);
+ return separator > 0 && ID_PATTERN.test(id) && CONTENT_HASH_PATTERN.test(hash) ? id : null;
+}
+
+/** The size of a file, or of every file under a directory, without following symbolic links. */
+async function getEntrySize(entryPath: string): Promise<number> {
+ const stats = await fs.promises.lstat(entryPath);
+ if (!stats.isDirectory()) {
+ return stats.isFile() ? stats.size : 0;
+ }
+ let total = 0;
+ for (const name of await fs.promises.readdir(entryPath)) {
+ total += await getEntrySize(path.join(entryPath, name));
+ }
+ return total;
+}
+
/** The start of a SHA-256 over every file's path and hash, which names a resource's directory. */
function getContentHash(files: ResourceFile[]) {
const hash = createHash("sha256");
diff --git a/packages/commons/src/lib/resources.ts b/packages/commons/src/lib/resources.ts
index e297286af6..1eda3621a6 100644
--- a/packages/commons/src/lib/resources.ts
+++ b/packages/commons/src/lib/resources.ts
@@ -47,8 +47,32 @@ export interface ResourceDownloadProgress {
resources: ResourceDownloadState[];
}
+/**
+ * A file or directory in the resources directory that is not the directory of a registered
+ * resource as it is now:
+ * - `outdated`: a registered resource's directory for files it no longer has;
+ * - `unregistered`: the directory of a resource that no feature registers;
+ * - `unknown`: anything else, such as a file put there by hand.
+ */
+export interface ForeignResourceEntry {
+ /** Its name in the resources directory. */
+ name: string;
+ path: string;
+ kind: "outdated" | "unregistered" | "unknown";
+ /** The ID its name carries, for `outdated` and `unregistered`. */
+ resourceId: string | null;
+ /** The title and icon of the registered resource, for `outdated`. */
+ title: string | null;
+ icon: string | null;
+ /** The size of its files, in bytes. */
+ size: number;
+ isDirectory: boolean;
+}
+
export interface ResourcesStatusResponse {
resources: ResourceInfo[];
+ /** The entries of the resources directory that are no registered resource, when listing all. */
+ foreign?: ForeignResourceEntry[];
/** The free space where resources are stored, in bytes, or `null` when it cannot be read. */
freeBytes: number | null;
/** The download that already fetches some of the resources, if one runs. */