refactor: consolidate widget workbench modules

This commit is contained in:
ajnart committed 2026-09-12 16:06:18 +02:00
1 parent 29c94be821
commit 84058544a4
50 files changed
+1529 -1597

No files matched your search

@@ -1,3 +1,4 @@
import { HOST_WIDGET_MODULES } from "../package/schema";
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
import { customJsxAuthoringCatalog } from "./component-catalog";
import {
@@ -284,3 +285,22 @@ function truncatePromptText(value: string, limit: number) {
const marker = "\n... [content omitted to fit the prompt budget]";
return `${value.slice(0, Math.max(0, limit - marker.length))}${marker}`;
}
/** Public authoring context only. Local bindings and runtime response data never belong here. */
export const packageAssistantSdkContext = {
schema: "homarr-widget-package-v3",
sdkVersion: "1",
hostModules: HOST_WIDGET_MODULES,
package:
"widget.json contains $schema, manifest, dependencies, connections, options; files are edited separately. manifest requires id, name, version (exact semver), sdkVersion:'1', entrypoints:{tile,advanced?,configuration?,server?}. Each client surface default-exports a React component. Local relative modules and CSS imports work. dependencies maps npm names to exact versions. No request, connection or server file is required for static widgets. Declare connections as named {label,kind:'http'|'integration'|'service',optional?}; service requirements also declare serviceType. Owners bind local settings and encrypted secrets. Never embed credentials, local addresses or connection IDs in portable source.",
styling:
"Use normal TSX, React hooks, imported Mantine components, CSS and reusable modules. manifest.styles defaults to scoped CSS; 'global' is an explicit package choice. Build dashboard tiles and advanced views; there is no standalone application route. Respect host.visibleWidth/visibleHeight, colorScheme, locale, reducedMotion and isEditMode. Entry points may reuse the same component and branch on displayMode.",
client:
"Import @homarr/widget-sdk. useWidgetHost() returns displayMode:'compact'|'advanced',width,height,visibleWidth,visibleHeight,displayScale,visible,isPreview,isEditMode,locale,timeZone,colorScheme,reducedMotion. useWidgetOptions<T>() returns option values. useWidgetState<T>(key,initial) shares instance state between tile and advanced. useWidgetClock(intervalMs=1000) returns epoch milliseconds or null, pauses when hidden. useWidgetQuery<T>(name,input?,{enabled?,refetchInterval?,staleTime?}) returns query state. useWidgetAction<Output,Input>(name) returns mutation (mutate/mutateAsync). useWidgetSubscription<T>(name,input?,{enabled?,maximumEvents?}) returns data,events,error,connected,reconnect. useWidgetStorage<T>('user'|'instance'|'installation',key,initial) returns data,set,saving,saveError. useWidgetCommands([{id,label,run,disabled?,destructive?}]) registers native menu commands. WidgetScope name/handlerPrefix/options isolates composed components.",
services:
"useWidgetServices() exposes notify({title,message?,color?}), navigate(href), openAdvanced(), closeAdvanced(), openDetail({title,content:ReactNode}), closeDetail(), confirm({title,message,destructive?}):Promise<boolean>, updateOptions(record):Promise<void>. Use updateOptions from an authored configuration surface. Managed storage is isolated memory in preview. Query results and local options are not part of Assistant context.",
server:
"Optional server.ts imports @homarr/widget-sdk/server and default-exports defineWidgetServer({handler:async(input,context)=>value}). Declare every handler in manifest.handlers with kind:'query'|'action'|'subscription'|'migration', permission:'view'|'modify'|'full', inputSchema? (JSON Schema), guestAccess?; actions default to modify. fetchWidgetConnection<T>(context,{connection:'slot',path,method?,query?,body?,responseType?}) returns {data,ok,status,contentType,durationMs,updatedAt}. getWidgetConnection<TSettings>(context,{connection,serviceType?}) returns {configuration:{kind,serviceType?,settings?:TSettings,...},secrets:Record<string,string>} only to trusted server code for Node SQL, MQTT, SSH, files or other service clients; never return secrets to browser queries. getWidgetServerContext(context) returns options,installationId,bindingNames,bindingLabels,isPreview. Declare connections with multiple:true for a repeatable group, and integrationKind (for example sonarr) to filter compatible native integrations. getWidgetConnectionGroup(context,slot) returns all {connection,label} members for queries and actions; do not hard-code first/second server slots. callWidgetIntegration(context,{connection,capability,input?}) invokes native adapters; subscribeWidgetIntegration yields native stream events. callWidgetRunner and subscribeWidgetRunner address owner-managed remote runners. Server modules have trusted Node capabilities. Secrets stay in owner-bound connections. Do not invent integration capabilities: use reference packages or declared capability docs.",
lifecycle:
"Proposals only change the visible draft after explicit review; they never save, trust, run or activate code. The owner saves the draft, reviews dependencies and trust, runs exact-candidate Preview, then explicitly activates the saved release for all placements. SDK actions are simulated in default previews, but arbitrary trusted browser/Node code still executes. A preview session proves compilation/session creation only, not successful UI rendering, live action success or all application behavior. Any source/options/binding edit invalidates preview evidence.",
};
@@ -0,0 +1,184 @@
import { useEffect, useRef, useState } from "react";
import { createId, downloadJson, isRecord } from "@homarr/common";
import { redactCustomWidgetCredentialLiterals } from "../core/definition-security";
export interface PackageDocument {
name: string;
metadata: string;
files: Record<string, string>;
}
export function documentFromSource(name: string, source: unknown): PackageDocument {
if (!isRecord(source)) return { name, metadata: "{}", files: {} };
const { files, _draftMetadata, ...metadata } = source;
const document = { name, metadata: JSON.stringify(metadata, null, 2), files: {} as Record<string, string> };
if (typeof _draftMetadata === "string") document.metadata = _draftMetadata;
if (isRecord(files)) {
for (const [path, content] of Object.entries(files))
if (typeof content === "string") document.files[path] = content;
}
return document;
}
export function documentFromTemplate(name: string, source: unknown): PackageDocument {
if (!isRecord(source) || !isRecord(source.manifest)) return documentFromSource(name, source);
return documentFromSource(name, {
...source,
manifest: { ...source.manifest, id: `local.${createId()}`, name, version: "1.0.0" },
});
}
export function documentSource(document: PackageDocument): Record<string, unknown> {
try {
const metadata: unknown = JSON.parse(document.metadata);
if (isRecord(metadata)) return { ...metadata, files: document.files };
} catch {
/* An incomplete manifest can still be saved as a draft. */
}
return { _draftMetadata: document.metadata, files: document.files };
}
const redact = (text: string) =>
redactCustomWidgetCredentialLiterals(text).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gu, "$1");
export function recoveryDocument(document: PackageDocument): PackageDocument {
return {
name: redact(document.name),
metadata: redact(document.metadata),
files: Object.fromEntries(Object.entries(document.files).map(([path, content]) => [path, redact(content)])),
};
}
export function downloadPackage(name: string, value: unknown) {
downloadJson(value, `${name.replace(/[^a-z0-9._-]+/giu, "-") || "widget"}.json`);
}
const maximumHistoryBytes = 2_000_000;
const maximumRecoveryBytes = 1_000_000;
export function usePackageDocument(
initial: PackageDocument,
userId: string,
installationId?: string,
) {
const [document, setDocument] = useState(initial);
const [saved, setSaved] = useState(initial);
const [recovery, setRecovery] = useState<PackageDocument | null>(null);
const [historyState, setHistoryState] = useState({ undo: false, redo: false });
const history = useRef({ entries: [JSON.stringify(initial)], index: 0, lastChange: 0, field: "" });
const current = useRef(document);
const key = `homarr:custom-widget-recovery:${userId}`;
const definitionId = `package:${installationId ?? "new"}`;
const dirty = JSON.stringify(document) !== JSON.stringify(saved);
current.current = document;
const syncHistory = () =>
setHistoryState({
undo: history.current.index > 0,
redo: history.current.index < history.current.entries.length - 1,
});
const edit = (next: PackageDocument, field = "") => {
const state = history.current;
const serialized = JSON.stringify(next);
if (serialized === state.entries[state.index]) return;
const now = Date.now();
const coalesce =
field &&
state.field === field &&
now - state.lastChange < 600 &&
state.index > 0 &&
state.index === state.entries.length - 1;
state.entries = state.entries.slice(0, state.index + 1);
if (coalesce) state.entries[state.index] = serialized;
else {
state.entries.push(serialized);
state.index += 1;
}
let size = state.entries.reduce((sum, entry) => sum + entry.length, 0);
while (state.entries.length > 1 && (state.entries.length > 100 || size > maximumHistoryBytes)) {
size -= state.entries.shift()?.length ?? 0;
state.index -= 1;
}
state.lastChange = now;
state.field = field;
current.current = next;
setDocument(next);
syncHistory();
};
const move = (offset: number) => {
const state = history.current;
const index = state.index + offset;
if (index < 0 || index >= state.entries.length) return;
state.index = index;
state.field = "";
const entry = state.entries[index];
if (!entry) return;
const next = JSON.parse(entry) as PackageDocument;
current.current = next;
setDocument(next);
syncHistory();
};
useEffect(() => {
try {
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (!isRecord(stored) || stored.definitionId !== definitionId || !isRecord(stored.content)) return;
const content = stored.content;
if (typeof content.name !== "string" || typeof content.metadata !== "string" || !isRecord(content.files)) return;
const next = documentFromSource(content.name, { files: content.files, _draftMetadata: content.metadata });
if (JSON.stringify(next) !== JSON.stringify(initial)) setRecovery(next);
} catch {
/* Browser recovery is optional. */
}
}, [definitionId, initial, key]);
useEffect(() => {
if (recovery) return;
const timer = setTimeout(() => {
try {
if (!dirty) {
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (isRecord(stored) && stored.definitionId === definitionId) localStorage.removeItem(key);
return;
}
const payload = JSON.stringify({ definitionId, content: recoveryDocument(document) });
if (payload.length <= maximumRecoveryBytes) localStorage.setItem(key, payload);
} catch {
/* Storage may be unavailable or full. */
}
}, 500);
return () => clearTimeout(timer);
}, [definitionId, dirty, document, key, recovery]);
const discardRecovery = () => {
setRecovery(null);
try {
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (isRecord(stored) && stored.definitionId === definitionId) localStorage.removeItem(key);
} catch {
/* Optional storage. */
}
};
const markSaved = (value: PackageDocument) => {
setSaved(value);
history.current.field = "";
if (JSON.stringify(current.current) === JSON.stringify(value)) discardRecovery();
};
return {
document,
dirty,
edit,
undo: () => move(-1),
redo: () => move(1),
historyState,
reset: () => edit(saved),
markSaved,
recovery,
discardRecovery,
restoreRecovery: () => {
if (recovery) edit(recovery);
discardRecovery();
},
};
}