Simplify Custom JSX v2 authoring
This commit is contained in:
177 files changed
+4775
-43426
No files matched your search
@@ -1,44 +1,131 @@
|
||||
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
|
||||
import { customJsxAuthoringCatalog } from "./component-catalog";
|
||||
import { customJsxExamples } from "./examples";
|
||||
|
||||
export const CUSTOM_WIDGET_MANTINE_VERSION = customJsxAuthoringCatalog.mantineVersion;
|
||||
export const CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL = "--- END HOMARR CUSTOM WIDGET OFFLINE BUNDLE ---";
|
||||
const CUSTOM_WIDGET_AI_PROMPT_LIMIT = 8_000;
|
||||
const CUSTOM_WIDGET_AI_PROMPT_LIMIT = 12_000;
|
||||
|
||||
export const CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION =
|
||||
"Create the requested widget now and return exactly one complete `json` fenced block followed by one complete `jsx` fenced block. Homarr will validate the result after it is pasted into the workbench.";
|
||||
"Return exactly one complete `json` fenced block followed by one complete `jsx` fenced block. Do not include prose outside those blocks.";
|
||||
|
||||
const AUTHORING_PROMPT = `You create Homarr Custom JSX v2 widgets. Return exactly two fenced blocks: a json block containing one complete widget object with template set to "__HOMARR_TEMPLATE__", then a jsx block containing the readable template.
|
||||
const RECOMMENDED_COMPONENTS = [
|
||||
"Stack",
|
||||
"Group",
|
||||
"SimpleGrid",
|
||||
"Grid",
|
||||
"Box",
|
||||
"Center",
|
||||
"Paper",
|
||||
"Card",
|
||||
"Card.Section",
|
||||
"ScrollArea",
|
||||
"Text",
|
||||
"Title",
|
||||
"Badge",
|
||||
"Alert",
|
||||
"Progress",
|
||||
"RingProgress",
|
||||
"ThemeIcon",
|
||||
"Indicator",
|
||||
"Avatar",
|
||||
"Image",
|
||||
"Divider",
|
||||
"Skeleton",
|
||||
"Loader",
|
||||
"Table",
|
||||
"Tabs",
|
||||
"Tabs.List",
|
||||
"Tabs.Tab",
|
||||
"Tabs.Panel",
|
||||
"Accordion",
|
||||
"TextInput",
|
||||
"NumberInput",
|
||||
"Select",
|
||||
"MultiSelect",
|
||||
"Switch",
|
||||
"Checkbox",
|
||||
"Radio",
|
||||
"Radio.Group",
|
||||
"Radio.Card",
|
||||
"Radio.Indicator",
|
||||
"Slider",
|
||||
"SegmentedControl",
|
||||
"Button",
|
||||
"ActionIcon",
|
||||
"Tooltip",
|
||||
"Popover",
|
||||
"Calendar",
|
||||
"AreaChart",
|
||||
"BarChart",
|
||||
"LineChart",
|
||||
"DonutChart",
|
||||
] as const;
|
||||
|
||||
Use $schema "homarr-custom-widget-v2". A widget contains metadata, inline API sources, named requests, an options schema, defaults, and one JSX template. Never include credentials. Use one source named "default" unless the widget genuinely combines APIs.
|
||||
const leanShape = `{
|
||||
"$schema": "homarr-custom-widget-v2",
|
||||
"name": "Widget name",
|
||||
"description": "Optional summary",
|
||||
"sources": {
|
||||
"default": { "name": "API", "baseUrl": "https://api.example.com", "networkScope": "public", "auth": "none" }
|
||||
},
|
||||
"requests": {
|
||||
"items": { "path": "/items/{option:category}", "query": { "limit": { "$option": "limit" } } },
|
||||
"update": { "kind": "action", "method": "POST", "path": "/items/{param:id}", "invalidates": ["items"] }
|
||||
},
|
||||
"options": {
|
||||
"category": { "label": "Category", "control": "text", "default": "all" },
|
||||
"limit": { "label": "Result limit", "control": "number", "default": 20, "min": 1, "max": 100 }
|
||||
},
|
||||
"template": "__HOMARR_TEMPLATE__"
|
||||
}`;
|
||||
|
||||
This Homarr release uses Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}. Use only the Homarr runtime components and Mantine capabilities described in this prompt. The embedded-skill variant includes the complete release-matched skill, widget schema, component catalog, and canonical examples for self-contained offline authoring.
|
||||
function compactExample(index: number) {
|
||||
const example = customJsxExamples[index];
|
||||
if (!example) return "";
|
||||
const { template, ...manifest } = example.widget;
|
||||
return `Example — ${example.title}:\n\n\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``;
|
||||
}
|
||||
|
||||
Queries and actions may use GET, POST, PUT, PATCH, or DELETE. Set kind to query for reads and action for user-triggered changes. Actions never use trigger "load". Declare every path, query, or body parameter. Use {name} in paths and {"$param":"name"} in query/body templates. Every declared parameter needs an explicit value source: SubFetch, ActionButton, and ToggleSwitch supply manual request values through their params prop; every load-query parameter must have an optionsBinding entry containing {"$option":"optionName"} or a primitive literal. Never infer a binding from matching names. Use load-triggered query results through data.<requestId>.
|
||||
const AUTHORING_PROMPT = `You are writing one safe Homarr Custom JSX v2 dashboard widget for Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}.
|
||||
|
||||
Source authentication is exactly one of {"type":"none"}, {"type":"bearer"}, {"type":"basic"}, {"type":"apiKeyHeader","headerName":"X-API-Key"}, or {"type":"apiKeyQuery","parameterName":"api_key"}. Credentials are configured separately by the user.
|
||||
Manifest contract:
|
||||
${leanShape}
|
||||
|
||||
Templates can read data, status, options, and inputs. Each status.<requestId> is an object shaped { loading: boolean, ok?: boolean, status?: number, statusText?: string, error?: string }; never compare it with the strings "loading", "success", or "error". Use status.list?.loading while loading, status.list?.ok === false for failure, and status.list?.ok === true for success. Bind supported Mantine controls with bind="search" and read the temporary value as inputs.search. Bound inputs live only in memory and reset when the widget reloads; saved configuration belongs in options. Restricted callback blocks may declare immutable local const values followed by one final return. Use RecursiveList for arbitrary-depth trees instead of authored recursion. Use Mantine Core, Dates, and Charts components. Do not use imports, hooks, refs, raw event callback props, component/renderRoot, arbitrary portals, raw HTML, fetch, eval, npm packages, or credentials. Design for compact and wide dashboard sizes with useful loading, empty, and error states.
|
||||
Sources are keyed by name and must include "default". Auth is "none", "bearer", "basic", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Never put credentials in the manifest.
|
||||
|
||||
Options use a restricted object JSON Schema. x-homarr controls include text, textarea, number, switch, select, multi-select, slider, date, time, color, icon, url, duration, timeZone, and json. Dynamic selects use x-homarr.optionsSource with requestId, optional itemsPath for wrapped arrays, valuePath, and labelPath.
|
||||
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. DELETE requires full permission and receives confirmation automatically. Use {option:name} or {"$option":"name"} for saved options. Use {param:name} or {"$param":"name"} only for invocation-time params supplied by SubFetch, ActionButton, or ToggleSwitch. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Paths and query values must be primitive; JSON bodies may bind structured options.
|
||||
|
||||
Widget shape:
|
||||
{ "$schema":"homarr-custom-widget-v2", "name":"...", "description":"...", "iconUrl":"https://...", "sources":[{ "id":"default", "name":"API", "baseUrl":"https://host", "networkScope":"public|private|loopback", "auth":{ "type":"none|bearer|basic|apiKeyHeader|apiKeyQuery" } }], "requests":[{ "id":"data", "sourceId":"default", "kind":"query", "method":"GET", "pathTemplate":"/api/{id}", "parameters":{ "id":"string", "limit":"number" }, "optionsBinding":{ "id":{ "$option":"resourceId" }, "limit":20 }, "queryTemplate":{ "limit":{ "$param":"limit" } }, "auth":"inherit", "minimumBoardPermission":"view", "trigger":"load" }], "optionsSchema":{ "type":"object", "properties":{ "resourceId":{ "type":"string" } }, "required":["resourceId"], "additionalProperties":false }, "defaultOptions":{ "resourceId":"example" }, "template":"__HOMARR_TEMPLATE__" }
|
||||
Options are keyed by name. Every option has label, control, and default. Controls: text, textarea, number, switch, select, multiSelect, slider, date, time, color, icon, url, duration, timeZone, json. Select choices use \`"choices": [{"label":"...","value":"..."}]\`. Dynamic choices must use \`"choicesFrom": {"request":"requestId","itemsPath":"optional.path","valuePath":"id","labelPath":"name"}\`, never an object under \`choices\`. Options are configured outside the widget and read through \`options.name\`; a bound control writes only to \`inputs.name\` and never changes an option.
|
||||
|
||||
Keep the result concise, accessible, responsive, and valid. Preserve unrelated fields when fixing an existing widget.`;
|
||||
JSX reads data.requestId, status.requestId, options.name, and temporary inputs.name. A status has loading, ok, status, statusText, and error. Use bind="search" on supported controls and inputs.search in params. SubFetch invokes a manual query. With trigger="manual", it renders its own load button; never author onClick or a fetch callback. Its child callback is (result, meta), where meta has ok, status, statusText, loading=false, and no error because SubFetch renders loading/error states itself. Use expression callbacks for map, filter, sort, and SubFetch. Do not use imports, hooks, refs, raw HTML, event callbacks, fetch, eval, bigint, npm packages, authored const blocks, IIFEs, or recursion. Regex is only for bounded string matching/replacement. Do not embed secrets.
|
||||
|
||||
Hard syntax rule: never write \`=> {\` anywhere. Every callback must be one concise expression, for example \`items.map(item => <Card key={item.id}>...</Card>)\`. Inline derived values directly, even when that repeats a short expression. Never use an IIFE to create local variables or branch; use JSX ternaries instead. Callback parameter names must not shadow the reserved roots \`data\`, \`status\`, \`options\`, or \`inputs\`.
|
||||
|
||||
Use only API routes grounded in the user request, documentation, or verified API notes. When a requested mutation is undocumented, omit it and explain the limitation through the widget design rather than inventing an endpoint.
|
||||
|
||||
Recommended components: ${RECOMMENDED_COMPONENTS.join(", ")}. This list is not exhaustive. Standard Mantine compound names are encouraged. Runtime helpers: RefreshButton, SubFetch, ActionButton, ToggleSwitch, and <Icon name="tabler-icon-name" />.
|
||||
|
||||
Make the result genuinely attractive: establish clear visual hierarchy, use deliberate spacing, restrained semantic color, responsive layouts, and theme-safe colors. Prefer one strong primary surface over excessive nested cards. Include useful loading, empty, error, and success states. Make narrow and wide tiles both work.
|
||||
|
||||
Visual quality bar:
|
||||
- Give the widget a purposeful header with title, useful context, and its primary status or action.
|
||||
- When the data supports it, lead with 2–4 scannable summary metrics before detailed rows.
|
||||
- Use responsive SimpleGrid/Grid column objects and let long content wrap on narrow tiles.
|
||||
- Use theme tokens and semantic Mantine colors; avoid hard-coded light backgrounds and decorative gradients.
|
||||
|
||||
${compactExample(0)}
|
||||
|
||||
${compactExample(1)}
|
||||
|
||||
Output the manifest with template set exactly to "__HOMARR_TEMPLATE__", then put the complete template in the JSX block.`;
|
||||
|
||||
export const CUSTOM_WIDGET_AUTHORING_PROMPT = AUTHORING_PROMPT;
|
||||
|
||||
export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX v2 widget at a time. Repeat this workflow independently when the user asks for several widgets.
|
||||
export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX v2 widget at a time.
|
||||
|
||||
1. Read homarr://custom-widgets/schema, homarr://custom-widgets/components, and homarr://custom-widgets/skill.
|
||||
2. Read the external API documentation and construct one credential-free homarr-custom-widget-v2 document.
|
||||
3. Call customWidget_validate before saving, then customWidget_previewCreate.
|
||||
4. Test queries with customWidget_previewQuery and actions with customWidget_previewAction. Actions are simulated until the user explicitly enables live preview actions.
|
||||
5. Open the preview URL, inspect customWidget_previewJournal, and iterate with customWidget_templatePatch or another preview session.
|
||||
6. Use customWidget_secretSet only for a credential the user supplied and only with dedicated permission. Otherwise call customWidget_secretRequestUser and poll its completion status; never receive or repeat the plaintext.
|
||||
7. Call customWidget_create only after validation, request tests, action simulation, and visual inspection pass.
|
||||
Read the live schema and only the component resources needed for the design. Construct a credential-free widget, validate it, create a preview, test queries and simulated actions, visually inspect it, then create it. Request credentials through Homarr when needed and never repeat plaintext. The live resources are authoritative for this Homarr release.
|
||||
|
||||
Use inline sources, named queries/actions, restricted JSON Schema options, temporary declarative bind controls exposed through inputs, and safe Mantine JSX. Every load-query parameter needs an explicit optionsBinding option reference or literal; manual queries and actions receive all parameters from the invoking component's params prop. Never infer sources from matching names. Each status.<requestId> is an object with loading, ok, status, statusText, and error fields; never compare it with "loading", "success", or "error". Use kind, not method, to distinguish reads from user-triggered changes. Never include credentials, imports, hooks, refs, callbacks, browser requests, arbitrary JavaScript, npm packages, polymorphic roots, or arbitrary portals. Make the widget responsive, accessible, loading-aware, empty-aware, and error-aware. The live schema and component resources are authoritative for the installed Homarr release.`;
|
||||
Use the lean keyed sources, requests, and options contract. Bind saved values directly with $option and invocation values with $param. Load queries cannot use $param. Keep the design responsive, accessible, theme-safe, loading-aware, empty-aware, and error-aware.`;
|
||||
|
||||
export function buildCustomWidgetMcpPrompt(request?: string | null, documentationUrl?: string | null) {
|
||||
const sections = [CUSTOM_WIDGET_MCP_AUTHORING_PROMPT];
|
||||
@@ -54,14 +141,11 @@ export function buildCustomWidgetAiPrompt(
|
||||
request?: string | null,
|
||||
documentationUrl?: string | null,
|
||||
) {
|
||||
const requestedWidget = truncatePromptText(
|
||||
redactText(request?.trim() || "Describe the widget you want to create."),
|
||||
1_500,
|
||||
);
|
||||
const sections = [`Please create this Homarr Custom JSX v2 widget:\n\n${requestedWidget}`];
|
||||
const sections = [
|
||||
`Create this Homarr Custom JSX v2 widget:\n\n${truncatePromptText(redactText(request?.trim() || "Describe the widget you want to create."), 1_500)}`,
|
||||
];
|
||||
if (documentationUrl) sections.push(`API documentation: ${truncatePromptText(redactUrl(documentationUrl), 500)}`);
|
||||
sections.push(AUTHORING_PROMPT);
|
||||
sections.push(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION);
|
||||
|
||||
const optionalSections = [
|
||||
...(rawResponse ? [{ label: "Sample API response", content: redactResponse(rawResponse) }] : []),
|
||||
@@ -69,26 +153,14 @@ export function buildCustomWidgetAiPrompt(
|
||||
? [{ label: "Current widget", content: JSON.stringify(redactValue(currentConfig), null, 2) }]
|
||||
: []),
|
||||
];
|
||||
for (const [index, section] of optionalSections.entries()) {
|
||||
const remainingSections = optionalSections.length - index;
|
||||
const remainingCharacters = CUSTOM_WIDGET_AI_PROMPT_LIMIT - sections.join("\n\n").length - 2;
|
||||
const sectionBudget = Math.floor(remainingCharacters / remainingSections);
|
||||
const formatted = formatBudgetedCodeSection(section.label, section.content, sectionBudget);
|
||||
if (formatted) sections.splice(-1, 0, formatted);
|
||||
}
|
||||
|
||||
return sections.join("\n\n");
|
||||
}
|
||||
|
||||
export function finalizeCustomWidgetOfflineContent(content: string) {
|
||||
const footerPrefix = `${content.trimEnd()}\n\n${CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL}\nCharacters: `;
|
||||
let digitCount = String(footerPrefix.length).length;
|
||||
while (true) {
|
||||
const characterCount = footerPrefix.length + digitCount;
|
||||
const countText = String(characterCount);
|
||||
if (countText.length === digitCount) return `${footerPrefix}${countText}`;
|
||||
digitCount = countText.length;
|
||||
for (const section of optionalSections) {
|
||||
const remaining =
|
||||
CUSTOM_WIDGET_AI_PROMPT_LIMIT - sections.join("\n\n").length - CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION.length - 8;
|
||||
const formatted = formatBudgetedCodeSection(section.label, section.content, remaining);
|
||||
if (formatted) sections.push(formatted);
|
||||
}
|
||||
const footer = `\n\n${CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION}`;
|
||||
return `${truncatePromptText(sections.join("\n\n"), CUSTOM_WIDGET_AI_PROMPT_LIMIT - footer.length)}${footer}`;
|
||||
}
|
||||
|
||||
const sensitiveKey =
|
||||
@@ -97,17 +169,16 @@ const sensitiveKey =
|
||||
function redactValue(value: unknown, key = ""): unknown {
|
||||
if (sensitiveKey.test(key)) return "[REDACTED]";
|
||||
if (Array.isArray(value)) return value.map((entry) => redactValue(entry));
|
||||
if (value !== null && typeof value === "object") {
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([entryKey, entry]) => [entryKey, redactValue(entry, entryKey)]),
|
||||
);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
if (["sources", "requests", "optionsSchema", "defaultOptions"].includes(key)) {
|
||||
if (["sources", "requests", "options"].includes(key)) {
|
||||
try {
|
||||
return redactValue(JSON.parse(value) as unknown);
|
||||
} catch {
|
||||
// Keep invalid editor JSON useful while applying the text redactor below.
|
||||
/* Keep invalid editor JSON useful. */
|
||||
}
|
||||
}
|
||||
return key === "baseUrl" || key === "iconUrl" ? redactUrl(value) : redactText(value);
|
||||
@@ -119,7 +190,7 @@ function redactResponse(value: string) {
|
||||
try {
|
||||
return JSON.stringify(redactValue(JSON.parse(value) as unknown), null, 2);
|
||||
} catch {
|
||||
return "[REDACTED_URL]";
|
||||
return truncatePromptText(redactText(value), 1_500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,8 +221,7 @@ function formatBudgetedCodeSection(label: string, content: string, budget: numbe
|
||||
const prefix = `${label}:\n\n\`\`\`json\n`;
|
||||
const suffix = "\n```";
|
||||
if (budget <= prefix.length + suffix.length + 80) return null;
|
||||
const contentBudget = budget - prefix.length - suffix.length;
|
||||
return `${prefix}${truncatePromptText(content, contentBudget)}${suffix}`;
|
||||
return `${prefix}${truncatePromptText(content, budget - prefix.length - suffix.length)}${suffix}`;
|
||||
}
|
||||
|
||||
function truncatePromptText(value: string, limit: number): string {
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { customJsxAuthoringCatalog, getCustomJsxComponentProps } from "./component-catalog";
|
||||
import { customJsxExamples } from "./examples";
|
||||
import {
|
||||
CUSTOM_WIDGET_OFFLINE_BUNDLE,
|
||||
CUSTOM_WIDGET_SKILL_FILES,
|
||||
CUSTOM_WIDGET_SKILL_MD,
|
||||
CUSTOM_WIDGET_SKILL_VERSION,
|
||||
} from "./embedded-ai-prompt";
|
||||
import { customJsxTablerIconNames } from "./tabler-icons";
|
||||
|
||||
export const CUSTOM_WIDGET_SKILLS_SH_URL = "https://www.skills.sh/homarr-labs/homarr/homarr-custom-widget";
|
||||
@@ -13,23 +7,47 @@ export const CUSTOM_WIDGET_SKILL_SOURCE_URL =
|
||||
"https://github.com/homarr-labs/homarr/tree/HEAD/.agents/skills/homarr-custom-widget";
|
||||
export const CUSTOM_WIDGET_SKILL_INSTALL_COMMAND =
|
||||
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget";
|
||||
export const CUSTOM_WIDGET_SKILL_VERSION = "2.0.0";
|
||||
|
||||
export const CUSTOM_WIDGET_SKILL_MD = `---
|
||||
name: homarr-custom-widget
|
||||
description: Author safe Homarr Custom JSX v2 widgets from API documentation.
|
||||
---
|
||||
|
||||
# Homarr Custom Widget
|
||||
|
||||
Author one widget at a time. When connected to Homarr, retrieve \`homarr://custom-widgets/schema\` and only the component resources needed for the design. The live resources are authoritative for the installed release.
|
||||
|
||||
1. Read the API documentation.
|
||||
2. Create one credential-free widget with keyed \`sources\`, keyed \`requests\`, optional keyed \`options\`, and safe JSX \`template\`.
|
||||
3. Validate, preview, test queries and simulated actions, visually inspect, and iterate.
|
||||
4. Request credentials through Homarr and never repeat plaintext.
|
||||
5. Save only after narrow/wide, light/dark, loading, empty, error, and success states work.
|
||||
|
||||
Use \`{option:name}\` or \`$option\` for saved options. Use \`{param:name}\` or \`$param\` for values supplied by \`SubFetch\`, \`ActionButton\`, or \`ToggleSwitch\`. Load queries cannot use invocation parameters. Templates read \`data\`, \`status\`, \`options\`, and temporary \`inputs\`.
|
||||
|
||||
\`SubFetch\` with \`trigger="manual"\` renders its own load button. Its callback is \`(result, meta)\`; never author \`onClick\` or a fetch callback.
|
||||
|
||||
Use standard Mantine compound names and deliberate visual hierarchy, spacing, restrained semantic color, and responsive layouts. Avoid excessive nested cards.
|
||||
|
||||
Do not use imports, hooks, refs, raw HTML, raw event callbacks, browser requests, arbitrary functions, eval, bigint, npm packages, authored statement blocks, IIFEs, or recursion. Do not pretend MCP tools exist in an offline chat session.
|
||||
|
||||
When this skill is installed from the repository, optional offline details are in \`references/schema.md\`, \`references/runtime.md\`, and \`references/security.md\`. MCP-only clients should use the live Homarr resources instead.
|
||||
`;
|
||||
|
||||
export function getCustomWidgetSkill() {
|
||||
return {
|
||||
name: "homarr-custom-widget",
|
||||
version: CUSTOM_WIDGET_SKILL_VERSION,
|
||||
skillMd: CUSTOM_WIDGET_SKILL_MD,
|
||||
files: CUSTOM_WIDGET_SKILL_FILES,
|
||||
componentCatalog: customJsxAuthoringCatalog,
|
||||
examples: customJsxExamples,
|
||||
skillsShUrl: CUSTOM_WIDGET_SKILLS_SH_URL,
|
||||
sourceUrl: CUSTOM_WIDGET_SKILL_SOURCE_URL,
|
||||
installCommand: CUSTOM_WIDGET_SKILL_INSTALL_COMMAND,
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomWidgetOfflineBundle() {
|
||||
return CUSTOM_WIDGET_OFFLINE_BUNDLE;
|
||||
export function getCustomWidgetSkillContent() {
|
||||
return CUSTOM_WIDGET_SKILL_MD;
|
||||
}
|
||||
|
||||
export function getCustomWidgetComponentCatalog() {
|
||||
@@ -37,7 +55,8 @@ export function getCustomWidgetComponentCatalog() {
|
||||
}
|
||||
|
||||
export function getCustomWidgetComponent(name: string) {
|
||||
const component = customJsxAuthoringCatalog.components.find((candidate) => candidate.name === name);
|
||||
const canonicalName = name === "Icon" ? "TablerIcon" : name;
|
||||
const component = customJsxAuthoringCatalog.components.find((candidate) => candidate.name === canonicalName);
|
||||
if (!component) return null;
|
||||
return {
|
||||
schemaVersion: customJsxAuthoringCatalog.schemaVersion,
|
||||
@@ -48,7 +67,7 @@ export function getCustomWidgetComponent(name: string) {
|
||||
category: component.category,
|
||||
safety: component.safety,
|
||||
description: component.description,
|
||||
props: getCustomJsxComponentProps(name),
|
||||
props: getCustomJsxComponentProps(canonicalName),
|
||||
blockedProps: component.blockedProps,
|
||||
bind: component.bind,
|
||||
subcomponents: component.subcomponents,
|
||||
@@ -56,7 +75,6 @@ export function getCustomWidgetComponent(name: string) {
|
||||
documentationUrl: component.documentationUrl,
|
||||
knownValues: component.name === "TablerIcon" ? { name: customJsxTablerIconNames } : undefined,
|
||||
deniedReason: component.deniedReason,
|
||||
blockedCapabilities: customJsxAuthoringCatalog.blockedCapabilities,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
|
||||
import type { HomarrCustomWidgetV2Input } from "./custom-jsx-schema";
|
||||
|
||||
export interface BundledCustomWidget {
|
||||
id: "seed-dog-facts" | "seed-currency-exchange" | "seed-jellyfin" | "seed-pokedex";
|
||||
widget: HomarrCustomWidgetV2;
|
||||
id: "seed-dog-facts" | "seed-currency-exchange" | "seed-jellyfin" | "seed-pokedex" | "seed-tautulli-activity";
|
||||
widget: HomarrCustomWidgetV2Input;
|
||||
}
|
||||
|
||||
export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
|
||||
@@ -12,39 +12,12 @@ export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Random Dog Fact",
|
||||
description: "Displays a random fun fact about dogs.",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "Dog API",
|
||||
baseUrl: "https://dogapi.dog",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "fact",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v2/facts",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 30,
|
||||
},
|
||||
],
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
sources: { default: { name: "Dog API", baseUrl: "https://dogapi.dog", networkScope: "public", auth: "none" } },
|
||||
requests: { fact: { path: "/api/v2/facts", cacheSeconds: 30 } },
|
||||
options: {},
|
||||
template: `<Stack gap="sm" p="sm" h="100%" justify="center">
|
||||
<Group justify="space-between">
|
||||
<Text fw={700}>Dog fact</Text>
|
||||
<RefreshButton />
|
||||
</Group>
|
||||
{status.fact?.loading ? <Skeleton height={72} radius="md" /> :
|
||||
status.fact?.error ? <Alert color="red">{status.fact.error}</Alert> :
|
||||
<Text size="sm">{data.fact?.data?.[0]?.attributes?.body ?? "No dog fact was returned."}</Text>}
|
||||
<Group justify="space-between"><Text fw={700}>Dog fact</Text><RefreshButton /></Group>
|
||||
{status.fact?.loading ? <Skeleton height={72} radius="md" /> : status.fact?.error ? <Alert color="red">{status.fact.error}</Alert> : <Text size="sm">{data.fact?.data?.[0]?.attributes?.body ?? "No dog fact was returned."}</Text>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
@@ -54,56 +27,29 @@ export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Currency Exchange",
|
||||
description: "Converts an amount using European Central Bank exchange rates.",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "Frankfurter",
|
||||
baseUrl: "https://api.frankfurter.dev",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "rates",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/v1/latest",
|
||||
parameters: { from: "string", to: "string", amount: "number" },
|
||||
optionsBinding: {
|
||||
from: { $option: "from" },
|
||||
to: { $option: "to" },
|
||||
amount: { $option: "amount" },
|
||||
},
|
||||
queryTemplate: {
|
||||
from: { $param: "from" },
|
||||
to: { $param: "to" },
|
||||
amount: { $param: "amount" },
|
||||
},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 300,
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
from: { type: "string", title: "From currency", minLength: 3, maxLength: 3 },
|
||||
to: { type: "string", title: "Target currencies", description: "Comma-separated currency codes" },
|
||||
amount: { type: "number", title: "Amount", minimum: 0 },
|
||||
},
|
||||
required: ["from", "to", "amount"],
|
||||
additionalProperties: false,
|
||||
sources: {
|
||||
default: { name: "Frankfurter", baseUrl: "https://api.frankfurter.dev", networkScope: "public", auth: "none" },
|
||||
},
|
||||
requests: {
|
||||
rates: {
|
||||
path: "/v1/latest",
|
||||
query: { from: { $option: "from" }, to: { $option: "to" }, amount: { $option: "amount" } },
|
||||
cacheSeconds: 300,
|
||||
},
|
||||
},
|
||||
options: {
|
||||
from: { label: "From currency", control: "text", default: "JPY" },
|
||||
to: {
|
||||
label: "Target currencies",
|
||||
description: "Comma-separated currency codes",
|
||||
control: "text",
|
||||
default: "EUR,USD",
|
||||
},
|
||||
amount: { label: "Amount", control: "number", default: 50, min: 0 },
|
||||
},
|
||||
defaultOptions: { from: "JPY", to: "EUR,USD", amount: 50 },
|
||||
template: `<Stack gap="sm" p="sm">
|
||||
<Group justify="space-between"><Text fw={700}>{options.amount} {options.from}</Text><Badge>{data.rates?.date ?? "Latest"}</Badge></Group>
|
||||
{status.rates?.loading ? <Skeleton height={80} radius="md" /> : status.rates?.error ? <Alert color="red">{status.rates.error}</Alert> :
|
||||
<SimpleGrid cols={{ base: 1, xs: 2 }}>
|
||||
{Object.entries(data.rates?.rates ?? {}).map(entry => <Paper key={entry[0]} withBorder p="sm"><Text size="xs" c="dimmed">{entry[0]}</Text><Text fw={700} size="xl">{entry[1]}</Text></Paper>)}
|
||||
</SimpleGrid>}
|
||||
{status.rates?.loading ? <Skeleton height={80} radius="md" /> : status.rates?.error ? <Alert color="red">{status.rates.error}</Alert> : <SimpleGrid cols={{ base: 1, xs: 2 }}>{Object.entries(data.rates?.rates ?? {}).map(entry => <Paper key={entry[0]} withBorder p="sm"><Text size="xs" c="dimmed">{entry[0]}</Text><Text fw={700} size="xl">{entry[1]}</Text></Paper>)}</SimpleGrid>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
@@ -114,37 +60,19 @@ export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
|
||||
name: "Jellyfin Library",
|
||||
description: "Counts movies, series, episodes, and songs in a Jellyfin library.",
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/jellyfin.svg",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
sources: {
|
||||
default: {
|
||||
name: "Jellyfin",
|
||||
baseUrl: "http://jellyfin.local",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Emby-Token" },
|
||||
auth: { type: "apiKeyHeader", name: "X-Emby-Token" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "counts",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/Items/Counts",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 60,
|
||||
},
|
||||
],
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
},
|
||||
requests: { counts: { path: "/Items/Counts", cacheSeconds: 60 } },
|
||||
options: {},
|
||||
template: `<Stack gap="sm" p="sm">
|
||||
<Group justify="space-between"><Text fw={700}>Jellyfin library</Text><RefreshButton /></Group>
|
||||
{status.counts?.loading ? <Skeleton height={96} radius="md" /> : status.counts?.error ? <Alert color="red">{status.counts.error}</Alert> :
|
||||
<SimpleGrid cols={{ base: 2, sm: 4 }}>
|
||||
{[{ label: "Movies", value: data.counts?.MovieCount }, { label: "Series", value: data.counts?.SeriesCount }, { label: "Episodes", value: data.counts?.EpisodeCount }, { label: "Songs", value: data.counts?.SongCount }].map(item => <Paper key={item.label} withBorder p="sm"><Text size="xs" c="dimmed">{item.label}</Text><Text fw={700} size="xl">{item.value ?? 0}</Text></Paper>)}
|
||||
</SimpleGrid>}
|
||||
{status.counts?.loading ? <Skeleton height={96} radius="md" /> : status.counts?.error ? <Alert color="red">{status.counts.error}</Alert> : <SimpleGrid cols={{ base: 2, sm: 4 }}>{[{ label: "Movies", value: data.counts?.MovieCount }, { label: "Series", value: data.counts?.SeriesCount }, { label: "Episodes", value: data.counts?.EpisodeCount }, { label: "Songs", value: data.counts?.SongCount }].map(item => <Paper key={item.label} withBorder p="sm"><Text size="xs" c="dimmed">{item.label}</Text><Text fw={700} size="xl">{item.value ?? 0}</Text></Paper>)}</SimpleGrid>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
@@ -155,66 +83,57 @@ export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
|
||||
name: "Pokédex",
|
||||
description: "Browse Pokémon and open a responsive detail view.",
|
||||
iconUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "PokeAPI",
|
||||
baseUrl: "https://pokeapi.co",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
sources: { default: { name: "PokeAPI", baseUrl: "https://pokeapi.co", networkScope: "public", auth: "none" } },
|
||||
requests: {
|
||||
pokemon: {
|
||||
path: "/api/v2/pokemon",
|
||||
query: { limit: { $option: "limit" }, offset: { $option: "offset" } },
|
||||
cacheSeconds: 300,
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "pokemon",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v2/pokemon",
|
||||
parameters: { limit: "number" },
|
||||
optionsBinding: { limit: { $option: "limit" } },
|
||||
queryTemplate: { limit: { $param: "limit" }, offset: 0 },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 300,
|
||||
},
|
||||
{
|
||||
id: "detail",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v2/pokemon/{name}",
|
||||
parameters: { name: "string" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
cacheTtlSeconds: 300,
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
limit: {
|
||||
type: "number",
|
||||
title: "Pokémon to load",
|
||||
minimum: 1,
|
||||
maximum: 100,
|
||||
"x-homarr": { control: "number" },
|
||||
},
|
||||
},
|
||||
required: ["limit"],
|
||||
additionalProperties: false,
|
||||
detail: { path: "/api/v2/pokemon/{param:name}", trigger: "manual", cacheSeconds: 300 },
|
||||
},
|
||||
defaultOptions: { limit: 20 },
|
||||
template: `<Stack gap="sm" p="sm">
|
||||
<Group justify="space-between"><Title order={3}>Pokédex</Title><Badge color="red">{data.pokemon?.count ?? 0} Pokémon</Badge></Group>
|
||||
{status.pokemon?.loading ? <Skeleton height={180} radius="md" /> : status.pokemon?.error ? <Alert color="red">{status.pokemon.error}</Alert> :
|
||||
<Stack gap="xs">{(data.pokemon?.results ?? []).map((pokemon) => {
|
||||
const segments = pokemon.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
return <Paper key={dexId} withBorder p="xs"><Group justify="space-between"><Group gap="xs"><Badge variant="light">#{dexId}</Badge><Text fw={600} tt="capitalize">{pokemon.name}</Text></Group><SubFetch requestId="detail" params={{ name: pokemon.name }} trigger="manual"><Stack gap="xs"><SubData path="sprites.front_default" as="Image" alt={pokemon.name} w={80} h={80} /><SubData path="name" as="Title" order={4} /><SubData path="types" as="Code" /></Stack></SubFetch></Group></Paper>;
|
||||
})}</Stack>}
|
||||
options: {
|
||||
limit: { label: "Pokémon to load", control: "number", default: 24, min: 1, max: 100 },
|
||||
offset: { label: "Start at Pokédex number", control: "number", default: 0, min: 0, advanced: true },
|
||||
accent: { label: "Accent color", control: "color", default: "red" },
|
||||
},
|
||||
template: `<Stack gap="md" p="md" h="100%">
|
||||
<Group justify="space-between" align="flex-start">
|
||||
<Stack gap={2}><Group gap="xs"><ThemeIcon color={options.accent} variant="light" radius="xl"><Icon name="pokeball" /></ThemeIcon><Title order={3}>Pokédex</Title></Group><Text size="xs" c="dimmed">Explore species, types, abilities, and base stats</Text></Stack>
|
||||
<Group gap="xs"><Badge color={options.accent} variant="light">{data.pokemon?.count?.toLocaleString() ?? "—"} species</Badge><RefreshButton /></Group>
|
||||
</Group>
|
||||
<TextInput bind="search" label="Filter loaded Pokémon" placeholder="Search by name…" />
|
||||
{status.pokemon?.loading ? <SimpleGrid cols={{ base: 1, xs: 2 }}>{[1, 2, 3, 4].map(item => <Skeleton key={item} height={116} radius="md" />)}</SimpleGrid> : status.pokemon?.error ? <Alert color="red" title="The Pokédex could not be loaded">{status.pokemon.error}</Alert> : (data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).length === 0 ? <Alert color="gray" title="No Pokémon found">Try another name or increase the result limit in widget options.</Alert> : <ScrollArea h={300} type="auto"><SimpleGrid cols={{ base: 1, xs: 2 }} spacing="sm">{(data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).map((pokemon, index) => <Card key={pokemon.name} withBorder radius="md" padding="sm"><Stack gap="sm"><Group justify="space-between"><Group gap="xs"><Badge color={options.accent} variant="outline">#{options.offset + index + 1}</Badge><Text fw={700} tt="capitalize">{pokemon.name}</Text></Group><Text size="xs" c="dimmed">Details</Text></Group><SubFetch requestId="detail" params={{ name: pokemon.name }} trigger="manual" loadingLabel="Loading Pokémon…">{(detail) => <Stack gap="sm"><Group align="flex-start" wrap="nowrap"><Image src={detail.sprites?.other?.["official-artwork"]?.front_default ?? detail.sprites?.front_default} alt={detail.name} w={92} h={92} fit="contain" fallbackSrc="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png" /><Stack gap="xs"><Group gap={6}>{(detail.types ?? []).map(type => <Badge key={type.type?.name} variant="light" tt="capitalize">{type.type?.name}</Badge>)}</Group><Text size="xs" c="dimmed">Height {detail.height / 10} m · Weight {detail.weight / 10} kg</Text><Text size="xs"><Text span fw={600}>Abilities: </Text>{(detail.abilities ?? []).map(ability => ability.ability?.name?.replace("-", " ")).join(", ")}</Text></Stack></Group><Divider /><Stack gap={6}>{(detail.stats ?? []).map(stat => <Stack key={stat.stat?.name} gap={3}><Group justify="space-between"><Text size="xs" tt="capitalize">{stat.stat?.name?.replace("-", " ")}</Text><Text size="xs" fw={700}>{stat.base_stat}</Text></Group><Progress value={Math.min(100, stat.base_stat / 2)} color={options.accent} size="sm" /></Stack>)}</Stack></Stack>}</SubFetch></Stack></Card>)}</SimpleGrid></ScrollArea>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "seed-tautulli-activity",
|
||||
widget: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Tautulli Activity",
|
||||
description: "Shows active Plex streams from Tautulli.",
|
||||
sources: {
|
||||
default: {
|
||||
name: "Tautulli API",
|
||||
baseUrl: "http://tautulli.local",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyQuery", name: "apikey" },
|
||||
},
|
||||
},
|
||||
requests: { activity: { path: "/api/v2", query: { cmd: "get_activity" }, cacheSeconds: 15 } },
|
||||
options: {},
|
||||
template: `<Stack gap="md" p="md">
|
||||
<Group justify="space-between"><Stack gap={2}><Text fw={700}>Tautulli Activity</Text><Text size="xs" c="dimmed">Live streaming sessions</Text></Stack><RefreshButton /></Group>
|
||||
{status.activity?.loading ? <Stack gap="sm"><Skeleton height={80} radius="md" /><Skeleton height={80} radius="md" /></Stack> : status.activity?.error ? <Alert color="red" title="Could not load activity">{status.activity.error}</Alert> : (data.activity?.response?.data?.sessions ?? []).length === 0 ? <Alert color="gray" title="No active streams">All quiet.</Alert> : <>
|
||||
<SimpleGrid cols={{ base: 2, xs: 4 }}>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Active streams</Text><Text size="xl" fw={700}>{(data.activity?.response?.data?.sessions ?? []).length}</Text></Paper>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Total bandwidth</Text><Text size="xl" fw={700}>{((data.activity?.response?.data?.sessions ?? []).reduce((sum, session) => sum + (session.bandwidth || 0), 0) / 1000000).toFixed(1)}<Text span size="xs" c="dimmed"> Mbps</Text></Text></Paper>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Direct play</Text><Text size="xl" fw={700}>{(data.activity?.response?.data?.sessions ?? []).filter(session => session.transcode_decision === "direct play" || session.transcode_decision === "copy").length}</Text></Paper>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Transcodes</Text><Text size="xl" fw={700}>{(data.activity?.response?.data?.sessions ?? []).filter(session => session.transcode_decision === "transcode").length}</Text></Paper>
|
||||
</SimpleGrid>
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }}>{(data.activity?.response?.data?.sessions ?? []).map(session => <Paper key={session.session_key} withBorder p="sm" radius="md"><Stack gap="xs"><Group justify="space-between"><Group gap="xs"><Text size="sm" fw={600}>{session.user}</Text><Badge variant="light" color={session.state === "playing" ? "green" : session.state === "paused" ? "yellow" : "orange"}>{session.state}</Badge></Group><Badge variant="light" color="gray">{session.player}</Badge></Group><Text size="sm" lineClamp={1}>{session.full_title}</Text><Progress value={session.progress_percent} size="sm" color="blue" /><Group justify="space-between"><Group gap="xs"><Badge variant="light" color={session.transcode_decision === "transcode" ? "red" : session.transcode_decision === "copy" ? "orange" : "teal"}>{session.transcode_decision}</Badge><Badge variant="light" color="gray">{session.bandwidth ? (session.bandwidth / 1000000).toFixed(1) + " Mbps" : "—"}</Badge></Group><Badge variant="outline" color={session.location === "lan" ? "blue" : "yellow"}>{session.location}</Badge></Group></Stack></Paper>)}</SimpleGrid>
|
||||
</>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previLine truncated
|
||||
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previLine truncated
|
||||
@@ -9,17 +9,6 @@ export function buildCustomJsxComponentUsageExample(
|
||||
component: CustomJsxComponentApi,
|
||||
catalog: Pick<CustomJsxAuthoringCatalog, "types">,
|
||||
) {
|
||||
if (component.name === "RecursiveList") {
|
||||
return `<RecursiveList data={data.tree} childrenPath="children" keyPath="id" showLines>
|
||||
{(node, meta) => (
|
||||
<Group gap="xs">
|
||||
<Text>{node.label}</Text>
|
||||
{meta.hasChildren && <Badge>{meta.childCount}</Badge>}
|
||||
</Group>
|
||||
)}
|
||||
</RecursiveList>`;
|
||||
}
|
||||
|
||||
const props = component.props
|
||||
.filter((prop) => prop.required)
|
||||
.slice(0, 4)
|
||||
|
||||
@@ -33,6 +33,13 @@ export const customJsxSupportedPropsByName = new Map(
|
||||
customJsxComponentRegistry.map((entry) => [entry.name, new Set(entry.supportedProps)]),
|
||||
);
|
||||
|
||||
export function resolveCustomJsxComponentName(name: string): string {
|
||||
if (name === "Icon") return "TablerIcon";
|
||||
if (customJsxComponentByName.has(name)) return name;
|
||||
const flat = name.replaceAll(".", "");
|
||||
return customJsxComponentByName.has(flat) ? flat : name;
|
||||
}
|
||||
|
||||
const catalogComponentsByName = new Map(
|
||||
customJsxAuthoringCatalog.components.map((component) => [component.name, component]),
|
||||
);
|
||||
@@ -57,6 +64,7 @@ export function getCustomJsxBindingType(
|
||||
componentName: string,
|
||||
props: Readonly<Record<string, unknown>> = {},
|
||||
): CustomJsxBindingType | null {
|
||||
componentName = resolveCustomJsxComponentName(componentName);
|
||||
const type = catalogComponentsByName.get(componentName)?.bind?.type;
|
||||
if (!type) return null;
|
||||
if (multipleDateBindingComponents.has(componentName) && ["multiple", "range"].includes(String(props.type))) {
|
||||
|
||||
@@ -2,15 +2,18 @@ import { z } from "zod/v4";
|
||||
|
||||
import { validateCustomJsxTemplate } from "../jsx/analyzer";
|
||||
import { validateCredentialFreeExport, validatePrototypeKeys } from "./definition-security";
|
||||
import { validateCustomWidgetOptions } from "./options";
|
||||
import { customWidgetOptionsSchemaSchema } from "./options-schema";
|
||||
import { customJsxRequestSchema, customWidgetIdentifierSchema, customWidgetSourceSchema } from "./request-schema";
|
||||
import { customWidgetOptionsSchema } from "./options-schema";
|
||||
import {
|
||||
collectCustomWidgetRequestReferences,
|
||||
customWidgetIdentifierSchema,
|
||||
customWidgetRequestsSchema,
|
||||
customWidgetSourcesSchema,
|
||||
} from "./request-schema";
|
||||
import type { CustomJsxRequest } from "./request-schema";
|
||||
import { customWidgetAuthTypes, customWidgetSecretKinds } from "./schema-types";
|
||||
import { customWidgetSecretKinds } from "./schema-types";
|
||||
|
||||
export * from "./options-schema";
|
||||
export * from "./request-schema";
|
||||
export type CustomWidgetOptionsSchema = z.infer<typeof customWidgetOptionsSchemaSchema>;
|
||||
export const CUSTOM_WIDGET_SCHEMA = "homarr-custom-widget-v2";
|
||||
|
||||
export const customWidgetBindingIdentifierSchema = z
|
||||
@@ -18,6 +21,7 @@ export const customWidgetBindingIdentifierSchema = z
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[A-Za-z][A-Za-z0-9_-]*$/u, "Binding names must start with a letter and contain letters, numbers, - or _");
|
||||
|
||||
export const customJsxTemplateSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
@@ -33,7 +37,7 @@ export const customJsxTemplateSchema = z
|
||||
}
|
||||
});
|
||||
|
||||
export const customWidgetSecretInputSchema = z.object({
|
||||
export const customWidgetSecretInputSchema = z.strictObject({
|
||||
sourceId: customWidgetIdentifierSchema,
|
||||
kind: z.enum(customWidgetSecretKinds),
|
||||
value: z.string().min(1).max(8_192),
|
||||
@@ -46,15 +50,14 @@ export const customWidgetSecretsInputSchema = z
|
||||
const identities = new Set<string>();
|
||||
secrets.forEach((secret, index) => {
|
||||
const identity = `${secret.sourceId}:${secret.kind}`;
|
||||
if (identities.has(identity)) {
|
||||
if (identities.has(identity))
|
||||
ctx.addIssue({ code: "custom", path: [index], message: "A widget secret can only be supplied once" });
|
||||
}
|
||||
identities.add(identity);
|
||||
});
|
||||
});
|
||||
|
||||
export const customWidgetDefinitionSchema = z
|
||||
.object({
|
||||
.strictObject({
|
||||
$schema: z.literal(CUSTOM_WIDGET_SCHEMA),
|
||||
name: z.string().trim().min(1).max(128),
|
||||
description: z.string().max(512).optional(),
|
||||
@@ -67,25 +70,14 @@ export const customWidgetDefinitionSchema = z
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
|
||||
}, "Widget icons must use HTTP or HTTPS without embedded credentials")
|
||||
.optional(),
|
||||
sources: z.array(customWidgetSourceSchema).min(1).max(8),
|
||||
requests: z.array(customJsxRequestSchema).max(64),
|
||||
optionsSchema: customWidgetOptionsSchemaSchema,
|
||||
defaultOptions: z.record(z.string(), z.unknown()),
|
||||
sources: customWidgetSourcesSchema,
|
||||
requests: customWidgetRequestsSchema,
|
||||
options: customWidgetOptionsSchema,
|
||||
template: customJsxTemplateSchema,
|
||||
})
|
||||
.strict()
|
||||
.superRefine((definition, ctx) => {
|
||||
for (const issue of validateCustomWidgetOptions(definition.optionsSchema, definition.defaultOptions)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["defaultOptions", ...issue.path.split(".").slice(1)],
|
||||
message: issue.message,
|
||||
});
|
||||
}
|
||||
const sourceIds = validateSourceIds(definition.sources, ctx);
|
||||
const requests = validateRequests(definition, sourceIds, ctx);
|
||||
validateDynamicOptions(definition.optionsSchema, requests, ctx);
|
||||
validateTemplateRequests(definition.template, requests, ctx);
|
||||
validateRequests(definition, ctx);
|
||||
validateTemplateRequests(definition.template, definition.requests, ctx);
|
||||
validateTemplateBindings(definition.template, ctx);
|
||||
validateCredentialFreeExport(definition, ctx);
|
||||
validatePrototypeKeys(definition, ctx);
|
||||
@@ -93,142 +85,76 @@ export const customWidgetDefinitionSchema = z
|
||||
|
||||
type Definition = z.infer<typeof customWidgetDefinitionSchema>;
|
||||
|
||||
function validateSourceIds(sources: Definition["sources"], ctx: z.RefinementCtx) {
|
||||
const ids = new Set<string>();
|
||||
sources.forEach((source, index) => {
|
||||
if (ids.has(source.id))
|
||||
ctx.addIssue({ code: "custom", path: ["sources", index, "id"], message: `Duplicate source ID: ${source.id}` });
|
||||
ids.add(source.id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
function validateDynamicOptions(
|
||||
schema: unknown,
|
||||
requests: Map<string, CustomJsxRequest>,
|
||||
ctx: z.RefinementCtx,
|
||||
path: Array<string | number> = ["optionsSchema"],
|
||||
) {
|
||||
if (schema === null || typeof schema !== "object" || Array.isArray(schema)) return;
|
||||
const node = schema as Record<string, unknown>;
|
||||
const presentation = node["x-homarr"];
|
||||
if (presentation !== null && typeof presentation === "object" && !Array.isArray(presentation)) {
|
||||
const source = (presentation as Record<string, unknown>).optionsSource;
|
||||
if (source !== null && typeof source === "object" && !Array.isArray(source)) {
|
||||
const requestId = (source as Record<string, unknown>).requestId;
|
||||
const request = typeof requestId === "string" ? requests.get(requestId) : undefined;
|
||||
if (!request || request.kind !== "query") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "x-homarr", "optionsSource", "requestId"],
|
||||
message: `Dynamic options require a query request named '${String(requestId)}'`,
|
||||
});
|
||||
} else {
|
||||
for (const parameterName of Object.keys(request.parameters)) {
|
||||
if (!Object.hasOwn(request.optionsBinding ?? {}, parameterName)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "x-homarr", "optionsSource", "requestId"],
|
||||
message: `Dynamic option request '${request.id}' parameter '${parameterName}' requires an explicit optionsBinding entry`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.properties !== null && typeof node.properties === "object" && !Array.isArray(node.properties)) {
|
||||
for (const [key, child] of Object.entries(node.properties))
|
||||
validateDynamicOptions(child, requests, ctx, [...path, "properties", key]);
|
||||
}
|
||||
if (node.items !== undefined) validateDynamicOptions(node.items, requests, ctx, [...path, "items"]);
|
||||
for (const branch of ["if", "then", "else"] as const) {
|
||||
if (node[branch] !== undefined) validateDynamicOptions(node[branch], requests, ctx, [...path, branch]);
|
||||
}
|
||||
}
|
||||
|
||||
function validateRequests(definition: Definition, sourceIds: Set<string>, ctx: z.RefinementCtx) {
|
||||
const requests = new Map<string, CustomJsxRequest>();
|
||||
definition.requests.forEach((request, index) => {
|
||||
if (requests.has(request.id))
|
||||
ctx.addIssue({ code: "custom", path: ["requests", index, "id"], message: `Duplicate request ID: ${request.id}` });
|
||||
if (!sourceIds.has(request.sourceId)) {
|
||||
function validateRequests(definition: Definition, ctx: z.RefinementCtx) {
|
||||
for (const [requestId, request] of Object.entries(definition.requests)) {
|
||||
if (!definition.sources[request.source]) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "sourceId"],
|
||||
message: `Unknown source ID: ${request.sourceId}`,
|
||||
path: ["requests", requestId, "source"],
|
||||
message: `Unknown source '${request.source}'`,
|
||||
});
|
||||
}
|
||||
const source = definition.sources.find((candidate) => candidate.id === request.sourceId);
|
||||
if (source?.auth.type === "apiKeyHeader" && request.auth === "inherit") {
|
||||
const authHeader = source.auth.headerName.toLowerCase();
|
||||
if (Object.keys(request.staticHeaders ?? {}).some((header) => header.toLowerCase() === authHeader)) {
|
||||
const references = collectCustomWidgetRequestReferences(request);
|
||||
for (const optionName of references.options) {
|
||||
if (!definition.options[optionName]) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "staticHeaders"],
|
||||
message: "Static headers cannot override the source authentication header",
|
||||
});
|
||||
}
|
||||
}
|
||||
if (source?.auth.type === "apiKeyQuery" && request.auth === "inherit") {
|
||||
const authParameter = source.auth.parameterName.toLowerCase();
|
||||
if (Object.keys(request.queryTemplate ?? {}).some((parameter) => parameter.toLowerCase() === authParameter)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "queryTemplate"],
|
||||
message: "Query templates cannot override the source authentication parameter",
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [parameterName, binding] of Object.entries(request.optionsBinding ?? {})) {
|
||||
if (typeof binding !== "object") continue;
|
||||
const optionName = binding.$option;
|
||||
const optionSchema = definition.optionsSchema.properties?.[optionName];
|
||||
if (optionSchema === null || typeof optionSchema !== "object" || Array.isArray(optionSchema)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "optionsBinding", parameterName, "$option"],
|
||||
path: ["requests", requestId],
|
||||
message: `Unknown widget option '${optionName}'`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const parameterType = request.parameters[parameterName];
|
||||
const declaredOptionType = (optionSchema as Record<string, unknown>).type;
|
||||
const optionType = declaredOptionType === "integer" ? "number" : declaredOptionType;
|
||||
if (parameterType !== undefined && optionType !== parameterType) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "optionsBinding", parameterName, "$option"],
|
||||
message: `Option '${optionName}' must be ${parameterType} to supply parameter '${parameterName}'`,
|
||||
});
|
||||
}
|
||||
}
|
||||
requests.set(request.id, request);
|
||||
});
|
||||
definition.requests.forEach((request, index) => {
|
||||
request.invalidates?.forEach((requestId, invalidationIndex) => {
|
||||
const target = requests.get(requestId);
|
||||
if (!target || target.kind !== "query") {
|
||||
if (request.trigger === "load" && references.params.size > 0) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", requestId],
|
||||
message: `Load requests cannot use invocation parameters: ${[...references.params].join(", ")}`,
|
||||
});
|
||||
}
|
||||
request.invalidates?.forEach((target, index) => {
|
||||
if (definition.requests[target]?.kind !== "query") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index, "invalidates", invalidationIndex],
|
||||
message: `Invalidation target '${requestId}' must be a query request`,
|
||||
path: ["requests", requestId, "invalidates", index],
|
||||
message: `Invalidation target '${target}' must be a query`,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
for (const [optionName, option] of Object.entries(definition.options)) {
|
||||
const requestId = option.choicesFrom?.request;
|
||||
if (requestId && definition.requests[requestId]?.kind !== "query") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["options", optionName, "choicesFrom", "request"],
|
||||
message: `Dynamic choices require a query named '${requestId}'`,
|
||||
});
|
||||
}
|
||||
if (requestId) {
|
||||
const request = definition.requests[requestId];
|
||||
const references = request ? collectCustomWidgetRequestReferences(request) : null;
|
||||
if (request && (request.trigger !== "load" || (references?.params.size ?? 0) > 0)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["options", optionName, "choicesFrom", "request"],
|
||||
message: "Dynamic choices require a load query without invocation parameters",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateTemplateRequests(template: string, requests: Map<string, CustomJsxRequest>, ctx: z.RefinementCtx) {
|
||||
for (const match of template.matchAll(/<(SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/g)) {
|
||||
function validateTemplateRequests(template: string, requests: Record<string, CustomJsxRequest>, ctx: z.RefinementCtx) {
|
||||
for (const match of template.matchAll(/<(SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/gu)) {
|
||||
const component = match[1] as "SubFetch" | "ActionButton" | "ToggleSwitch";
|
||||
const idMatch = (match[2] ?? "").match(/\brequestId\s*=\s*(?:"([^"]+)"|'([^']+)')/);
|
||||
const attributes = match[2] ?? "";
|
||||
const idMatch = attributes.match(/\brequestId\s*=\s*(?:"([^"]+)"|'([^']+)')/u);
|
||||
const requestId = idMatch?.[1] ?? idMatch?.[2];
|
||||
if (!requestId) {
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: `${component} must use a literal requestId` });
|
||||
continue;
|
||||
}
|
||||
const request = requests.get(requestId);
|
||||
const request = requests[requestId];
|
||||
const expectedKind = component === "SubFetch" ? "query" : "action";
|
||||
if (!request)
|
||||
ctx.addIssue({
|
||||
@@ -236,25 +162,10 @@ function validateTemplateRequests(template: string, requests: Map<string, Custom
|
||||
path: ["template"],
|
||||
message: `${component} references unknown request '${requestId}'`,
|
||||
});
|
||||
else if (request.kind !== expectedKind) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["template"],
|
||||
message: `${component} requires a ${expectedKind} request, but '${requestId}' is ${request.kind}`,
|
||||
});
|
||||
} else if (component === "SubFetch" && request.trigger !== "manual") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["template"],
|
||||
message: `SubFetch requires a manual query, but '${requestId}' is load-triggered`,
|
||||
});
|
||||
} else if (Object.keys(request.parameters).length > 0 && !/\bparams\s*=/u.test(match[2] ?? "")) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["template"],
|
||||
message: `${component} must supply params for request '${requestId}'`,
|
||||
});
|
||||
}
|
||||
else if (request.kind !== expectedKind)
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: `${component} requires a ${expectedKind} request` });
|
||||
else if (component === "SubFetch" && request.trigger !== "manual")
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: `SubFetch requires '${requestId}' to be manual` });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,19 +179,15 @@ function validateTemplateBindings(template: string, ctx: z.RefinementCtx) {
|
||||
}
|
||||
|
||||
export type HomarrCustomWidgetV2 = z.infer<typeof customWidgetDefinitionSchema>;
|
||||
export type HomarrCustomWidgetV2Input = z.input<typeof customWidgetDefinitionSchema>;
|
||||
export const customWidgetCreateSchema = customWidgetDefinitionSchema.safeExtend({
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
});
|
||||
export const customWidgetUpdateSchema = z
|
||||
.object(customWidgetDefinitionSchema.shape)
|
||||
.strictObject(customWidgetDefinitionSchema.shape)
|
||||
.partial()
|
||||
.extend({
|
||||
id: z.string().min(1),
|
||||
secrets: customWidgetSecretsInputSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
.extend({ id: z.string().min(1), secrets: customWidgetSecretsInputSchema.optional() });
|
||||
export const customWidgetImportSchema = customWidgetDefinitionSchema;
|
||||
export type CustomWidgetCreateInput = z.infer<typeof customWidgetCreateSchema>;
|
||||
export type CustomWidgetUpdateInput = z.infer<typeof customWidgetUpdateSchema>;
|
||||
export type CustomWidgetImport = z.infer<typeof customWidgetImportSchema>;
|
||||
export const customWidgetAuthTypeSchema = z.enum(customWidgetAuthTypes);
|
||||
@@ -9,4 +9,5 @@ export type {
|
||||
CustomWidgetImport,
|
||||
CustomWidgetUpdateInput,
|
||||
HomarrCustomWidgetV2,
|
||||
HomarrCustomWidgetV2Input,
|
||||
} from "./custom-jsx-schema";
|
||||
@@ -1,101 +1,48 @@
|
||||
import type { RefinementCtx } from "zod/v4";
|
||||
import type { z } from "zod/v4";
|
||||
|
||||
import type { CustomJsxRequest } from "./request-schema";
|
||||
|
||||
const credentialKeyPattern =
|
||||
const credentialKey =
|
||||
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
|
||||
const credentialTextPattern =
|
||||
/(?:\bauthorization\s*[:=]\s*["']?bearer\s+[A-Za-z0-9._~+/%-]{8,}|\b(?:api[ _-]?key|access[ _-]?token|refresh[ _-]?token|client[ _-]?secret|token|password|passwd|secret)\s*[:=]\s*["'][^"']{4,}["'])/iu;
|
||||
const bearerHeaderValuePattern = /^\s*bearer\s+\S{8,}\s*$/iu;
|
||||
const blockedObjectKeys = new Set(["__proto__", "prototype", "constructor"]);
|
||||
|
||||
interface SecurityDefinition {
|
||||
defaultOptions: Record<string, unknown>;
|
||||
requests: CustomJsxRequest[];
|
||||
template: string;
|
||||
iconUrl?: string;
|
||||
optionsSchema: unknown;
|
||||
}
|
||||
|
||||
function isCredentialKeyName(value: string) {
|
||||
return credentialKeyPattern.test(value);
|
||||
}
|
||||
|
||||
export function validateCredentialFreeExport(definition: SecurityDefinition, ctx: RefinementCtx) {
|
||||
if (containsCredentialLikeValue(definition.defaultOptions)) {
|
||||
ctx.addIssue({ code: "custom", path: ["defaultOptions"], message: "Default options cannot contain credentials" });
|
||||
}
|
||||
definition.requests.forEach((request, index) => {
|
||||
if (
|
||||
containsCredentialLikeValue(request.optionsBinding) ||
|
||||
containsCredentialLikeValue(request.queryTemplate) ||
|
||||
containsCredentialLikeValue(request.bodyTemplate) ||
|
||||
Object.entries(request.staticHeaders ?? {}).some(
|
||||
([name, value]) => containsCredentialLikeValue(value, name) || bearerHeaderValuePattern.test(value),
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", index],
|
||||
message: "Static request templates cannot contain credentials",
|
||||
});
|
||||
}
|
||||
});
|
||||
if (credentialTextPattern.test(definition.template)) {
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: "Templates cannot contain literal credentials" });
|
||||
}
|
||||
if (definition.iconUrl && URL.canParse(definition.iconUrl)) {
|
||||
const icon = new URL(definition.iconUrl);
|
||||
if ([...icon.searchParams].some(([key, value]) => isCredentialKeyName(key) && value.trim().length > 0)) {
|
||||
ctx.addIssue({ code: "custom", path: ["iconUrl"], message: "Widget icon URLs cannot contain credentials" });
|
||||
export function validateCredentialFreeExport(definition: Record<string, unknown>, ctx: z.RefinementCtx) {
|
||||
inspect(definition.options, ["options"], ctx);
|
||||
inspect(definition.requests, ["requests"], ctx);
|
||||
if (typeof definition.iconUrl === "string" && URL.canParse(definition.iconUrl)) {
|
||||
const url = new URL(definition.iconUrl);
|
||||
if ([...url.searchParams.keys()].some((key) => credentialKey.test(key))) {
|
||||
ctx.addIssue({ code: "custom", path: ["iconUrl"], message: "Credentials must not be embedded in the icon URL" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function containsCredentialLikeValue(value: unknown, key = ""): boolean {
|
||||
if (isCredentialKeyName(key) && typeof value === "string" && value.trim().length > 0) return true;
|
||||
if (Array.isArray(value)) return value.some((entry) => containsCredentialLikeValue(entry));
|
||||
if (value === null || typeof value !== "object") return false;
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") return false;
|
||||
return entries.some(([childKey, child]) => containsCredentialLikeValue(child, childKey));
|
||||
}
|
||||
|
||||
export function validatePrototypeKeys(definition: SecurityDefinition, ctx: RefinementCtx) {
|
||||
const values: Array<[Array<string | number>, unknown]> = [
|
||||
[["optionsSchema"], definition.optionsSchema],
|
||||
[["defaultOptions"], definition.defaultOptions],
|
||||
];
|
||||
definition.requests.forEach((request, index) => {
|
||||
values.push([["requests", index, "optionsBinding"], request.optionsBinding]);
|
||||
values.push([["requests", index, "queryTemplate"], request.queryTemplate]);
|
||||
values.push([["requests", index, "bodyTemplate"], request.bodyTemplate]);
|
||||
});
|
||||
for (const [path, value] of values) {
|
||||
const blockedPath = findBlockedObjectKey(value);
|
||||
if (blockedPath) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, ...blockedPath],
|
||||
message: "Prototype-pollution keys are not allowed",
|
||||
});
|
||||
}
|
||||
if (
|
||||
typeof definition.template === "string" &&
|
||||
/(?:authorization\s*:\s*bearer|api[-_ ]?key\s*[:=]|password\s*[:=]|secret\s*[:=]|token\s*[:=])\s*["']?[A-Za-z0-9._~+/%=-]{8,}/iu.test(
|
||||
definition.template,
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: "Credentials must not be embedded in JSX" });
|
||||
}
|
||||
}
|
||||
|
||||
function findBlockedObjectKey(value: unknown, path: string[] = []): string[] | null {
|
||||
if (Array.isArray(value)) {
|
||||
for (const [index, entry] of value.entries()) {
|
||||
const found = findBlockedObjectKey(entry, [...path, String(index)]);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (value === null || typeof value !== "object") return null;
|
||||
function inspect(value: unknown, path: Array<string | number>, ctx: z.RefinementCtx): void {
|
||||
if (Array.isArray(value)) return value.forEach((entry, index) => inspect(entry, [...path, index], ctx));
|
||||
if (!value || typeof value !== "object") return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (blockedObjectKeys.has(key.toLowerCase())) return [...path, key];
|
||||
const found = findBlockedObjectKey(child, [...path, key]);
|
||||
if (found) return found;
|
||||
if (credentialKey.test(key) && typeof child === "string" && child.trim()) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: "Credentials must use source authentication" });
|
||||
}
|
||||
inspect(child, [...path, key], ctx);
|
||||
}
|
||||
}
|
||||
|
||||
export function validatePrototypeKeys(value: unknown, ctx: z.RefinementCtx) {
|
||||
walk(value, [], ctx);
|
||||
}
|
||||
|
||||
function walk(value: unknown, path: Array<string | number>, ctx: z.RefinementCtx): void {
|
||||
if (Array.isArray(value)) return value.forEach((entry, index) => walk(entry, [...path, index], ctx));
|
||||
if (!value || typeof value !== "object") return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (["__proto__", "prototype", "constructor"].includes(key))
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: "Unsafe object key" });
|
||||
walk(child, [...path, key], ctx);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import generatedSkillContent from "./skill-content.generated.json";
|
||||
|
||||
import {
|
||||
buildCustomWidgetAiPrompt,
|
||||
CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION,
|
||||
CUSTOM_WIDGET_MANTINE_VERSION,
|
||||
finalizeCustomWidgetOfflineContent,
|
||||
} from "./ai-prompt";
|
||||
import {
|
||||
CUSTOM_JSX_AUTHORING_CATALOG_SCHEMA_VERSION,
|
||||
CUSTOM_WIDGET_AUTHORING_VERSION,
|
||||
} from "./component-catalog-types";
|
||||
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
|
||||
|
||||
export { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "./ai-prompt";
|
||||
|
||||
export const CUSTOM_WIDGET_SKILL_VERSION = "2.0.0";
|
||||
|
||||
interface GeneratedSkillContent {
|
||||
schemaVersion: 1;
|
||||
files: Array<{ path: string; content: string }>;
|
||||
}
|
||||
|
||||
const skillContent = generatedSkillContent as GeneratedSkillContent;
|
||||
|
||||
export const CUSTOM_WIDGET_SKILL_FILES = skillContent.files as readonly Readonly<{
|
||||
path: string;
|
||||
content: string;
|
||||
}>[];
|
||||
|
||||
const skillFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "SKILL.md");
|
||||
if (!skillFile) throw new Error("The generated Custom Widget skill is missing SKILL.md");
|
||||
|
||||
export const CUSTOM_WIDGET_SKILL_MD = skillFile.content;
|
||||
const componentCatalogFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "references/component-catalog.json");
|
||||
const examplesFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "references/examples.json");
|
||||
if (!componentCatalogFile || !examplesFile)
|
||||
throw new Error("The generated Custom Widget skill is missing its catalog or examples");
|
||||
|
||||
export const CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG = componentCatalogFile.content.trim();
|
||||
export const CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES = examplesFile.content.trim();
|
||||
|
||||
const machineReferencePaths = new Set([componentCatalogFile.path, examplesFile.path]);
|
||||
|
||||
export const CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT = [
|
||||
"# Homarr Custom Widget offline authoring bundle",
|
||||
[
|
||||
`Skill version: ${CUSTOM_WIDGET_SKILL_VERSION}`,
|
||||
`Custom Widget authoring version: ${CUSTOM_WIDGET_AUTHORING_VERSION}`,
|
||||
`Mantine version: ${CUSTOM_WIDGET_MANTINE_VERSION}`,
|
||||
`Component catalog schema: ${CUSTOM_JSX_AUTHORING_CATALOG_SCHEMA_VERSION}`,
|
||||
].join("\n"),
|
||||
...CUSTOM_WIDGET_SKILL_FILES.filter(({ path }) => !machineReferencePaths.has(path)).map(
|
||||
({ path, content }) => `--- BEGIN SKILL FILE: ${path} ---\n${content.trimEnd()}\n--- END SKILL FILE: ${path} ---`,
|
||||
),
|
||||
`--- BEGIN CANONICAL COMPONENT CATALOG ---\n${CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG}\n--- END CANONICAL COMPONENT CATALOG ---`,
|
||||
`--- BEGIN CANONICAL RUNTIME EXAMPLES ---\n${CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES}\n--- END CANONICAL RUNTIME EXAMPLES ---`,
|
||||
].join("\n\n");
|
||||
|
||||
export const CUSTOM_WIDGET_OFFLINE_BUNDLE = finalizeCustomWidgetOfflineContent(CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT);
|
||||
|
||||
export function buildCustomWidgetAiPromptWithEmbeddedSkill(
|
||||
jsonSchema?: unknown,
|
||||
rawResponse?: string | null,
|
||||
currentConfig?: Partial<HomarrCustomWidgetV2> | Record<string, unknown> | null,
|
||||
request?: string | null,
|
||||
documentationUrl?: string | null,
|
||||
) {
|
||||
const prompt = [
|
||||
buildCustomWidgetAiPrompt(jsonSchema, rawResponse, currentConfig, request, documentationUrl),
|
||||
"This clipboard workflow has no Homarr MCP tools, repository access, or local files. The complete release-matched skill, schema, component catalog, and examples are embedded below. Author the best-effort widget now from this content; do not ask for tools or files. Homarr will validate it after paste.",
|
||||
CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT,
|
||||
CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION,
|
||||
].join("\n\n");
|
||||
return finalizeCustomWidgetOfflineContent(prompt);
|
||||
}
|
||||
@@ -1,121 +1,76 @@
|
||||
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
|
||||
import type { HomarrCustomWidgetV2Input } from "./custom-jsx-schema";
|
||||
|
||||
export interface CustomJsxExample {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
widget: HomarrCustomWidgetV2;
|
||||
widget: HomarrCustomWidgetV2Input;
|
||||
}
|
||||
|
||||
export const CUSTOM_JSX_STARTER = `<Stack gap="xs" p="sm">
|
||||
<Group justify="space-between">
|
||||
<Text fw={600}>Service status</Text>
|
||||
<Badge color={data.status === "online" ? "green" : "red"}>{data.status ?? "unknown"}</Badge>
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed">Configure a load query or paste sample data to start.</Text>
|
||||
export const CUSTOM_JSX_STARTER = `<Stack gap="sm" p="sm">
|
||||
<Group justify="space-between"><Text fw={700}>Service status</Text><RefreshButton /></Group>
|
||||
{status.status?.loading ? <Skeleton height={72} radius="md" /> : status.status?.error ? <Alert color="red">{status.status.error}</Alert> : <Badge color={data.status?.online ? "green" : "red"}>{data.status?.online ? "Online" : "Offline"}</Badge>}
|
||||
</Stack>`;
|
||||
|
||||
export const CUSTOM_WIDGET_STARTER: HomarrCustomWidgetV2 = {
|
||||
export const CUSTOM_WIDGET_STARTER: HomarrCustomWidgetV2Input = {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "New custom widget",
|
||||
description: "",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "API",
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
},
|
||||
],
|
||||
requests: [],
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
sources: { default: { name: "API", baseUrl: "https://example.com", networkScope: "public", auth: "none" } },
|
||||
requests: { status: { path: "/api/status" } },
|
||||
options: {},
|
||||
template: CUSTOM_JSX_STARTER,
|
||||
};
|
||||
|
||||
export const customJsxExamples: readonly CustomJsxExample[] = [
|
||||
{
|
||||
id: "service-status",
|
||||
title: "Service status",
|
||||
description: "A compact status widget backed by one load query.",
|
||||
id: "service-dashboard",
|
||||
title: "Service dashboard",
|
||||
description: "A polished responsive dashboard with clear loading and error states.",
|
||||
widget: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Service status",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "Service API",
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "status",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/status",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
},
|
||||
],
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
template: `<Stack gap="xs" p="sm">
|
||||
<Group justify="space-between">
|
||||
<Text fw={600}>{data.status.name ?? "Service"}</Text>
|
||||
<Badge color={data.status.online ? "green" : "red"}>{data.status.online ? "Online" : "Offline"}</Badge>
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed">{data.status.message ?? "No additional details"}</Text>
|
||||
</Stack>`,
|
||||
name: "Service dashboard",
|
||||
sources: {
|
||||
default: { name: "Service API", baseUrl: "https://example.com", networkScope: "public", auth: "none" },
|
||||
},
|
||||
requests: { overview: { path: "/api/overview", cacheSeconds: 30 } },
|
||||
options: {},
|
||||
template: `<Stack gap="md" p="md">
|
||||
<Group justify="space-between"><Stack gap={2}><Text fw={700}>System overview</Text><Text size="xs" c="dimmed">Live service health</Text></Stack><RefreshButton /></Group>
|
||||
{status.overview?.loading ? <Skeleton height={120} radius="lg" /> : status.overview?.error ? <Alert color="red" title="Could not load status">{status.overview.error}</Alert> : <SimpleGrid cols={{ base: 1, xs: 3 }}>{(data.overview?.services ?? []).map(service => <Paper key={service.name} withBorder p="sm" radius="md"><Group justify="space-between"><Text size="sm" fw={600}>{service.name}</Text><Badge color={service.online ? "green" : "red"} variant="light">{service.online ? "Online" : "Offline"}</Badge></Group><Text mt="xs" size="xl" fw={700}>{service.latency ?? "—"}<Text span size="xs" c="dimmed"> ms</Text></Text></Paper>)}</SimpleGrid>}
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "pokemon-evolution-tree",
|
||||
title: "Pokémon evolution tree",
|
||||
description: "A trusted arbitrary-depth tree with one immutable derived-value block per node.",
|
||||
id: "search-and-action",
|
||||
title: "Search and action",
|
||||
description: "A temporary search input, manual query, and explicit mutation.",
|
||||
widget: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Pokémon evolution tree",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "PokeAPI",
|
||||
baseUrl: "https://pokeapi.co",
|
||||
networkScope: "public",
|
||||
auth: { type: "none" },
|
||||
name: "Series search",
|
||||
sources: {
|
||||
default: {
|
||||
name: "Media API",
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", name: "X-Api-Key" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "evolution",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v2/evolution-chain/1",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
},
|
||||
requests: {
|
||||
search: { path: "/api/series/search", trigger: "manual", query: { term: { $param: "query" } } },
|
||||
monitor: {
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/api/series/{param:id}/monitor",
|
||||
confirmation: "Monitor this series?",
|
||||
},
|
||||
],
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
template: `<Stack gap="sm" p="sm">
|
||||
<Title order={3}>Evolution chain</Title>
|
||||
{status.evolution?.loading ? <Skeleton height={160} radius="md" /> : status.evolution?.error ? <Alert color="red">{status.evolution.error}</Alert> : data.evolution?.chain ?
|
||||
<RecursiveList data={data.evolution.chain} childrenPath="evolves_to" keyPath="species.name" defaultExpandedDepth={8} showLines>
|
||||
{(node, meta) => {
|
||||
const segments = node.species.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
return <Group gap="xs"><Badge variant="light">#{dexId}</Badge><Text tt="capitalize" fw={600}>{node.species.name}</Text>{meta.hasChildren && <Text size="xs" c="dimmed">{meta.childCount} next</Text>}</Group>;
|
||||
}}
|
||||
</RecursiveList> : <Text c="dimmed">No evolution chain returned.</Text>}
|
||||
},
|
||||
options: {},
|
||||
template: `<Stack gap="sm" p="md">
|
||||
<TextInput bind="search" label="Search TV shows" placeholder="Start typing…" />
|
||||
<SubFetch requestId="search" params={{ query: inputs.search }}>
|
||||
{(results) => <Stack gap="xs">{(results ?? []).map(series => <Paper key={series.id} withBorder p="sm" radius="md"><Group justify="space-between" wrap="nowrap"><Stack gap={2}><Text fw={600}>{series.title}</Text><Text size="xs" c="dimmed">{series.year ?? "Unknown year"}</Text></Stack><ActionButton requestId="monitor" params={{ id: series.id }}>Monitor</ActionButton></Group></Paper>)}</Stack>}
|
||||
</SubFetch>
|
||||
</Stack>`,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -73,32 +73,6 @@ function isTemplatePlaceholder(value: unknown) {
|
||||
return typeof value === "string" && value.replace(/[\\*_`\s]/gu, "").toUpperCase() === "HOMARRTEMPLATE";
|
||||
}
|
||||
|
||||
function normalizeAiRequestParameters(value: Record<string, unknown>, warnings: CustomWidgetImportIssue[]) {
|
||||
if (!Array.isArray(value.requests)) return;
|
||||
value.requests = value.requests.map((candidate, requestIndex) => {
|
||||
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return candidate;
|
||||
const request = { ...(candidate as Record<string, unknown>) };
|
||||
if (!request.parameters || typeof request.parameters !== "object" || Array.isArray(request.parameters))
|
||||
return request;
|
||||
const parameters = { ...(request.parameters as Record<string, unknown>) };
|
||||
for (const [name, parameter] of Object.entries(parameters)) {
|
||||
if (!parameter || typeof parameter !== "object" || Array.isArray(parameter)) continue;
|
||||
const keys = Object.keys(parameter);
|
||||
const type = (parameter as Record<string, unknown>).type;
|
||||
if (keys.length === 1 && ["string", "number", "boolean"].includes(String(type))) {
|
||||
parameters[name] = type;
|
||||
warnings.push({
|
||||
code: "NORMALIZED_PARAMETER_TYPE",
|
||||
path: ["requests", requestIndex, "parameters", name],
|
||||
message: `Converted { type: "${String(type)}" } to "${String(type)}".`,
|
||||
});
|
||||
}
|
||||
}
|
||||
request.parameters = parameters;
|
||||
return request;
|
||||
});
|
||||
}
|
||||
|
||||
type ParsedWidgetValue =
|
||||
| { success: true; value: Record<string, unknown> }
|
||||
| { success: false; issue: CustomWidgetImportIssue };
|
||||
@@ -179,7 +153,6 @@ export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResu
|
||||
const removedIssues = removedStateIssues(widget);
|
||||
if (removedIssues.length > 0) formatIssues.push(...removedIssues);
|
||||
const warnings: CustomWidgetImportIssue[] = [];
|
||||
normalizeAiRequestParameters(widget, warnings);
|
||||
if (jsxBlocks[0]) {
|
||||
if (isTemplatePlaceholder(widget.template) || !widget.template) widget.template = jsxBlocks[0].content.trim();
|
||||
else if (widget.template !== jsxBlocks[0].content.trim())
|
||||
@@ -214,11 +187,17 @@ export function getImportReview(value: unknown): ImportReview | null {
|
||||
const widget = parsed.data;
|
||||
return {
|
||||
name: widget.name,
|
||||
origins: widget.sources.map((source) => new URL(source.baseUrl).origin),
|
||||
authTypes: [...new Set(widget.sources.map((source) => source.auth.type))],
|
||||
networkScopes: [...new Set(widget.sources.map((source) => source.networkScope))],
|
||||
methods: [...new Set(widget.requests.map((request) => request.method))],
|
||||
permissions: [...new Set(widget.requests.map((request) => request.minimumBoardPermission))],
|
||||
hasActions: widget.requests.some((request) => request.kind === "action"),
|
||||
origins: Object.values(widget.sources).map((source) => new URL(source.baseUrl).origin),
|
||||
authTypes: [
|
||||
...new Set(
|
||||
Object.values(widget.sources).map((source) =>
|
||||
typeof source.auth === "string" ? source.auth : source.auth.type,
|
||||
),
|
||||
),
|
||||
],
|
||||
networkScopes: [...new Set(Object.values(widget.sources).map((source) => source.networkScope))],
|
||||
methods: [...new Set(Object.values(widget.requests).map((request) => request.method))],
|
||||
permissions: [...new Set(Object.values(widget.requests).map((request) => request.permission))],
|
||||
hasActions: Object.values(widget.requests).some((request) => request.kind === "action"),
|
||||
};
|
||||
}
|
||||
@@ -1,39 +1,14 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { matchesDeclaredOptionType } from "./option-value-types";
|
||||
import { customWidgetIdentifierSchema } from "./request-schema";
|
||||
|
||||
const optionSchemaKeys = new Set([
|
||||
"type",
|
||||
"title",
|
||||
"description",
|
||||
"default",
|
||||
"enum",
|
||||
"const",
|
||||
"minimum",
|
||||
"maximum",
|
||||
"multipleOf",
|
||||
"minLength",
|
||||
"maxLength",
|
||||
"minItems",
|
||||
"maxItems",
|
||||
"format",
|
||||
"items",
|
||||
"properties",
|
||||
"required",
|
||||
"additionalProperties",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"x-homarr",
|
||||
]);
|
||||
const optionTypes = new Set(["object", "array", "string", "number", "integer", "boolean", "null"]);
|
||||
const optionControls = new Set([
|
||||
export const customWidgetOptionControls = [
|
||||
"text",
|
||||
"textarea",
|
||||
"number",
|
||||
"switch",
|
||||
"select",
|
||||
"multi-select",
|
||||
"multiSelect",
|
||||
"slider",
|
||||
"date",
|
||||
"time",
|
||||
@@ -43,258 +18,91 @@ const optionControls = new Set([
|
||||
"duration",
|
||||
"timeZone",
|
||||
"json",
|
||||
]);
|
||||
const optionFormats = new Set(["date", "date-time", "time", "color", "uri", "icon", "duration", "time-zone"]);
|
||||
const finiteNumberKeywords = ["minimum", "maximum", "multipleOf"] as const;
|
||||
const nonNegativeIntegerKeywords = ["minLength", "maxLength", "minItems", "maxItems"] as const;
|
||||
const credentialOptionName =
|
||||
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
|
||||
const controlsByType: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||
string: new Set(["text", "textarea", "select", "date", "time", "color", "icon", "url", "timeZone", "json"]),
|
||||
number: new Set(["number", "select", "slider", "duration", "json"]),
|
||||
integer: new Set(["number", "select", "slider", "duration", "json"]),
|
||||
boolean: new Set(["switch", "select", "json"]),
|
||||
array: new Set(["multi-select", "json"]),
|
||||
object: new Set(["json"]),
|
||||
null: new Set(["json"]),
|
||||
};
|
||||
] as const;
|
||||
|
||||
function validateOptionsSource(value: unknown, ctx: z.RefinementCtx, path: Array<string | number>) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
ctx.addIssue({ code: "custom", path, message: "optionsSource must be an object" });
|
||||
return;
|
||||
}
|
||||
const keys = Object.keys(value);
|
||||
if (
|
||||
keys.some((key) => !["requestId", "itemsPath", "valuePath", "labelPath"].includes(key)) ||
|
||||
!["requestId", "valuePath", "labelPath"].every((key) => {
|
||||
const candidate = (value as Record<string, unknown>)[key];
|
||||
return typeof candidate === "string" && candidate.length > 0;
|
||||
})
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path, message: "optionsSource requires requestId, valuePath, and labelPath" });
|
||||
}
|
||||
const itemsPath = (value as Record<string, unknown>).itemsPath;
|
||||
if (itemsPath !== undefined && (typeof itemsPath !== "string" || itemsPath.length === 0)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "itemsPath"], message: "itemsPath must be a non-empty path" });
|
||||
}
|
||||
}
|
||||
const choiceSchema = z.strictObject({
|
||||
label: z.string().trim().min(1).max(128),
|
||||
value: z.union([z.string(), z.number().finite()]),
|
||||
});
|
||||
|
||||
function validatePresentation(
|
||||
value: unknown,
|
||||
schema: Record<string, unknown>,
|
||||
ctx: z.RefinementCtx,
|
||||
path: Array<string | number>,
|
||||
) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
ctx.addIssue({ code: "custom", path, message: "x-homarr must be an object" });
|
||||
return;
|
||||
}
|
||||
const metadata = value as Record<string, unknown>;
|
||||
const allowed = new Set(["control", "placeholder", "advanced", "order", "optionsSource"]);
|
||||
for (const key of Object.keys(metadata)) {
|
||||
if (!allowed.has(key))
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: `Unsupported x-homarr field '${key}'` });
|
||||
}
|
||||
if (
|
||||
metadata.control !== undefined &&
|
||||
(typeof metadata.control !== "string" || !optionControls.has(metadata.control))
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "control"], message: "Unknown Homarr option control" });
|
||||
} else if (
|
||||
typeof metadata.control === "string" &&
|
||||
typeof schema.type === "string" &&
|
||||
!controlsByType[schema.type]?.has(metadata.control)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "control"],
|
||||
message: `Control '${metadata.control}' does not support ${schema.type} values`,
|
||||
});
|
||||
}
|
||||
if (metadata.placeholder !== undefined && typeof metadata.placeholder !== "string") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "placeholder"], message: "placeholder must be a string" });
|
||||
}
|
||||
if (metadata.advanced !== undefined && typeof metadata.advanced !== "boolean") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "advanced"], message: "advanced must be a boolean" });
|
||||
}
|
||||
if (metadata.order !== undefined && (typeof metadata.order !== "number" || !Number.isFinite(metadata.order))) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "order"], message: "order must be a finite number" });
|
||||
}
|
||||
if (metadata.optionsSource !== undefined) {
|
||||
validateOptionsSource(metadata.optionsSource, ctx, [...path, "optionsSource"]);
|
||||
if (metadata.control !== "select" && metadata.control !== "multi-select") {
|
||||
const choicesFromSchema = z.strictObject({
|
||||
request: customWidgetIdentifierSchema,
|
||||
itemsPath: z.preprocess(
|
||||
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
|
||||
z.string().trim().min(1).optional(),
|
||||
),
|
||||
valuePath: z.string().trim().min(1),
|
||||
labelPath: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const customWidgetOptionSchema = z
|
||||
.strictObject({
|
||||
label: z.string().trim().min(1).max(128),
|
||||
description: z.string().max(512).optional(),
|
||||
control: z.enum(customWidgetOptionControls),
|
||||
default: z.json(),
|
||||
choices: z.array(choiceSchema).min(1).max(100).optional(),
|
||||
choicesFrom: choicesFromSchema.optional(),
|
||||
min: z.number().finite().optional(),
|
||||
max: z.number().finite().optional(),
|
||||
step: z.number().finite().positive().optional(),
|
||||
advanced: z.boolean().optional(),
|
||||
group: z.string().trim().min(1).max(128).optional(),
|
||||
})
|
||||
.superRefine((option, ctx) => {
|
||||
const issue = getCustomWidgetOptionValueIssue(option, option.default);
|
||||
if (issue) ctx.addIssue({ code: "custom", path: ["default"], message: issue });
|
||||
if (option.min !== undefined && option.max !== undefined && option.min > option.max) {
|
||||
ctx.addIssue({ code: "custom", path: ["min"], message: "Minimum cannot be greater than maximum" });
|
||||
}
|
||||
if ((option.choices || option.choicesFrom) && !["select", "multiSelect"].includes(option.control)) {
|
||||
ctx.addIssue({ code: "custom", path: ["choices"], message: "Choices require a select or multiSelect control" });
|
||||
}
|
||||
if (option.choices && option.choicesFrom) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "optionsSource"],
|
||||
message: "Dynamic options require a select or multi-select control",
|
||||
path: ["choicesFrom"],
|
||||
message: "Use static choices or dynamic choices, not both",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateScalarKeywords(schema: Record<string, unknown>, ctx: z.RefinementCtx, path: Array<string | number>) {
|
||||
for (const key of finiteNumberKeywords) {
|
||||
if (schema[key] !== undefined && (typeof schema[key] !== "number" || !Number.isFinite(schema[key]))) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a finite number` });
|
||||
if (
|
||||
option.choices &&
|
||||
new Set(option.choices.map((choice) => String(choice.value))).size !== option.choices.length
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: ["choices"], message: "Choice values must be unique" });
|
||||
}
|
||||
}
|
||||
if (typeof schema.multipleOf === "number" && schema.multipleOf <= 0)
|
||||
ctx.addIssue({ code: "custom", path: [...path, "multipleOf"], message: "multipleOf must be greater than zero" });
|
||||
for (const key of nonNegativeIntegerKeywords) {
|
||||
if (schema[key] !== undefined && (!Number.isInteger(schema[key]) || Number(schema[key]) < 0)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a non-negative integer` });
|
||||
}
|
||||
}
|
||||
for (const [minimum, maximum] of [
|
||||
["minimum", "maximum"],
|
||||
["minLength", "maxLength"],
|
||||
["minItems", "maxItems"],
|
||||
] as const) {
|
||||
if (typeof schema[minimum] === "number" && typeof schema[maximum] === "number" && schema[minimum] > schema[maximum])
|
||||
ctx.addIssue({ code: "custom", path, message: `${minimum} cannot be greater than ${maximum}` });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function validateChoices(schema: Record<string, unknown>, ctx: z.RefinementCtx, path: Array<string | number>) {
|
||||
if (
|
||||
schema.enum !== undefined &&
|
||||
(!Array.isArray(schema.enum) || schema.enum.length === 0 || schema.enum.length > 100)
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "enum must contain between 1 and 100 values" });
|
||||
} else if (
|
||||
Array.isArray(schema.enum) &&
|
||||
schema.enum.some((entry) => !matchesDeclaredOptionType(schema.type, entry))
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "Every enum value must match the option type" });
|
||||
}
|
||||
if (schema.const !== undefined && !matchesDeclaredOptionType(schema.type, schema.const))
|
||||
ctx.addIssue({ code: "custom", path: [...path, "const"], message: "const must match the option type" });
|
||||
}
|
||||
export const customWidgetOptionsSchema = z
|
||||
.record(customWidgetIdentifierSchema, customWidgetOptionSchema)
|
||||
.refine((options) => Object.keys(options).length <= 64, "A widget can define at most 64 options")
|
||||
.default({});
|
||||
|
||||
function validateOptionSchemaNode(
|
||||
export type CustomWidgetOption = z.infer<typeof customWidgetOptionSchema>;
|
||||
export type CustomWidgetOptions = z.infer<typeof customWidgetOptionsSchema>;
|
||||
|
||||
export function getCustomWidgetOptionValueIssue(
|
||||
option: Pick<CustomWidgetOption, "control" | "min" | "max" | "choices">,
|
||||
value: unknown,
|
||||
ctx: z.RefinementCtx,
|
||||
path: Array<string | number>,
|
||||
isRoot = false,
|
||||
requiresType = true,
|
||||
propertyTypesRequired = true,
|
||||
): void {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
ctx.addIssue({ code: "custom", path, message: "Option schemas must be objects" });
|
||||
return;
|
||||
}
|
||||
const schema = value as Record<string, unknown>;
|
||||
for (const key of Object.keys(schema)) {
|
||||
if (!optionSchemaKeys.has(key)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: `Unsupported option schema keyword '${key}'` });
|
||||
}
|
||||
}
|
||||
if (
|
||||
(requiresType && typeof schema.type !== "string") ||
|
||||
(schema.type !== undefined && !optionTypes.has(String(schema.type)))
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "type"], message: "Every option schema needs one supported type" });
|
||||
}
|
||||
for (const key of ["title", "description"] as const) {
|
||||
if (schema[key] !== undefined && typeof schema[key] !== "string") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a string` });
|
||||
}
|
||||
}
|
||||
validateScalarKeywords(schema, ctx, path);
|
||||
if (schema.format !== undefined && (typeof schema.format !== "string" || !optionFormats.has(schema.format))) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Unsupported option format" });
|
||||
}
|
||||
if (schema.format !== undefined && schema.type !== "string") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Option formats require a string type" });
|
||||
}
|
||||
validateChoices(schema, ctx, path);
|
||||
if (isRoot && schema.type !== "object") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "type"], message: "The root options schema must be an object" });
|
||||
}
|
||||
if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "additionalProperties"],
|
||||
message: "additionalProperties can only be false",
|
||||
});
|
||||
}
|
||||
if (schema.type === "object" && schema.additionalProperties !== false) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "additionalProperties"],
|
||||
message: "Object options must set additionalProperties to false",
|
||||
});
|
||||
}
|
||||
if (schema.properties !== undefined) {
|
||||
if (schema.type !== undefined && schema.type !== "object") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "properties"], message: "properties require an object type" });
|
||||
}
|
||||
if (schema.properties === null || typeof schema.properties !== "object" || Array.isArray(schema.properties)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "properties"], message: "properties must be an object" });
|
||||
} else {
|
||||
for (const [key, child] of Object.entries(schema.properties)) {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u.test(key)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "properties", key],
|
||||
message: "Option names must start with a letter and contain letters, numbers, - or _",
|
||||
});
|
||||
}
|
||||
if (credentialOptionName.test(key)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [...path, "properties", key],
|
||||
message: "Credentials must use source authentication, not widget options",
|
||||
});
|
||||
}
|
||||
validateOptionSchemaNode(child, ctx, [...path, "properties", key], false, propertyTypesRequired);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (schema.required !== undefined && !Array.isArray(schema.required)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "required"], message: "required must be an array" });
|
||||
} else if (
|
||||
Array.isArray(schema.required) &&
|
||||
schema.properties !== null &&
|
||||
typeof schema.properties === "object" &&
|
||||
!Array.isArray(schema.properties)
|
||||
) {
|
||||
for (const key of schema.required) {
|
||||
if (typeof key !== "string" || !Object.hasOwn(schema.properties, key)) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "required"], message: "required contains an unknown option" });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (schema.type === "array" && schema.items === undefined) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "items"], message: "Array options require an items schema" });
|
||||
}
|
||||
if (schema.items !== undefined) {
|
||||
if (schema.type !== undefined && schema.type !== "array") {
|
||||
ctx.addIssue({ code: "custom", path: [...path, "items"], message: "items require an array type" });
|
||||
}
|
||||
validateOptionSchemaNode(schema.items, ctx, [...path, "items"]);
|
||||
}
|
||||
for (const branch of ["if", "then", "else"] as const) {
|
||||
if (schema[branch] !== undefined) {
|
||||
validateOptionSchemaNode(schema[branch], ctx, [...path, branch], false, false, branch !== "if");
|
||||
}
|
||||
}
|
||||
if (schema["x-homarr"] !== undefined) validatePresentation(schema["x-homarr"], schema, ctx, [...path, "x-homarr"]);
|
||||
}
|
||||
): string | null {
|
||||
if (["number", "slider", "duration"].includes(option.control)) {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return "Expected a number";
|
||||
if (option.min !== undefined && value < option.min) return `Must be at least ${option.min}`;
|
||||
if (option.max !== undefined && value > option.max) return `Must be at most ${option.max}`;
|
||||
} else if (option.control === "switch") {
|
||||
if (typeof value !== "boolean") return "Expected a boolean";
|
||||
} else if (option.control === "multiSelect") {
|
||||
if (!Array.isArray(value) || value.some((entry) => !["string", "number"].includes(typeof entry)))
|
||||
return "Expected a list of choices";
|
||||
} else if (option.control !== "json" && typeof value !== "string") return "Expected text";
|
||||
|
||||
export const customWidgetOptionsSchemaSchema = z
|
||||
.object({
|
||||
type: z.literal("object"),
|
||||
properties: z.record(z.string(), z.unknown()).default({}),
|
||||
required: z.array(z.string()).optional(),
|
||||
additionalProperties: z.literal(false).default(false),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
if: z.unknown().optional(),
|
||||
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
|
||||
then: z.unknown().optional(),
|
||||
else: z.unknown().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((schema, ctx) => validateOptionSchemaNode(schema, ctx, [], true));
|
||||
if (option.control === "url" && typeof value === "string" && value && !URL.canParse(value))
|
||||
return "Must be a valid URL";
|
||||
if (option.choices && (option.control === "select" || option.control === "multiSelect")) {
|
||||
const allowed = option.choices.map((choice) => choice.value);
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
if (values.some((entry) => !allowed.some((choice) => Object.is(choice, entry))))
|
||||
return "Value is not one of the allowed choices";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,106 +1,26 @@
|
||||
import { matchesDeclaredOptionType } from "./option-value-types";
|
||||
import { getCustomWidgetOptionValueIssue } from "./options-schema";
|
||||
import type { CustomWidgetOptions } from "./options-schema";
|
||||
|
||||
export interface CustomWidgetOptionIssue {
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
export function getCustomWidgetDefaultOptions(options: CustomWidgetOptions): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.entries(options).map(([name, option]) => [name, option.default]));
|
||||
}
|
||||
|
||||
export function validateCustomWidgetOptions(
|
||||
schema: JsonSchema,
|
||||
options: CustomWidgetOptions,
|
||||
value: Record<string, unknown>,
|
||||
): CustomWidgetOptionIssue[] {
|
||||
const issues: CustomWidgetOptionIssue[] = [];
|
||||
validateValue(schema, value, "configuration", issues);
|
||||
for (const [name, option] of Object.entries(options)) {
|
||||
const issue = getCustomWidgetOptionValueIssue(option, value[name]);
|
||||
if (issue) issues.push({ path: `configuration.${name}`, message: issue });
|
||||
}
|
||||
for (const name of Object.keys(value)) {
|
||||
if (!Object.hasOwn(options, name)) issues.push({ path: `configuration.${name}`, message: "Unknown option" });
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
function validateValue(schema: JsonSchema, value: unknown, path: string, issues: CustomWidgetOptionIssue[]): void {
|
||||
if (schema.const !== undefined && !Object.is(value, schema.const)) {
|
||||
issues.push({ path, message: "Value does not match the required constant" });
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(schema.enum) && !schema.enum.some((candidate) => Object.is(candidate, value))) {
|
||||
issues.push({ path, message: "Value is not one of the allowed choices" });
|
||||
return;
|
||||
}
|
||||
|
||||
const type = schema.type;
|
||||
if (typeof type === "string" && !matchesDeclaredOptionType(type, value)) {
|
||||
issues.push({ path, message: `Expected ${type}` });
|
||||
return;
|
||||
}
|
||||
|
||||
validateScalarValue(schema, value, path, issues);
|
||||
if (Array.isArray(value)) validateArrayValue(schema, value, path, issues);
|
||||
if (isRecord(value)) validateObjectValue(schema, value, path, issues);
|
||||
else if (isRecord(schema.if)) {
|
||||
const branch = matchesSchema(schema.if, value) ? schema.then : schema.else;
|
||||
if (isRecord(branch)) validateValue(branch, value, path, issues);
|
||||
}
|
||||
}
|
||||
|
||||
function validateScalarValue(schema: JsonSchema, value: unknown, path: string, issues: CustomWidgetOptionIssue[]) {
|
||||
if (typeof value === "string") {
|
||||
if (typeof schema.minLength === "number" && value.length < schema.minLength)
|
||||
issues.push({ path, message: `Must contain at least ${schema.minLength} characters` });
|
||||
if (typeof schema.maxLength === "number" && value.length > schema.maxLength)
|
||||
issues.push({ path, message: `Must contain at most ${schema.maxLength} characters` });
|
||||
if (schema.format === "uri" && !URL.canParse(value)) issues.push({ path, message: "Must be a valid URL" });
|
||||
}
|
||||
|
||||
if (typeof value === "number") {
|
||||
if (typeof schema.minimum === "number" && value < schema.minimum)
|
||||
issues.push({ path, message: `Must be at least ${schema.minimum}` });
|
||||
if (typeof schema.maximum === "number" && value > schema.maximum)
|
||||
issues.push({ path, message: `Must be at most ${schema.maximum}` });
|
||||
if (typeof schema.multipleOf === "number" && schema.multipleOf > 0 && value % schema.multipleOf !== 0)
|
||||
issues.push({ path, message: `Must be a multiple of ${schema.multipleOf}` });
|
||||
}
|
||||
}
|
||||
|
||||
function validateArrayValue(schema: JsonSchema, value: unknown[], path: string, issues: CustomWidgetOptionIssue[]) {
|
||||
if (typeof schema.minItems === "number" && value.length < schema.minItems)
|
||||
issues.push({ path, message: `Choose at least ${schema.minItems} values` });
|
||||
if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
|
||||
issues.push({ path, message: `Choose at most ${schema.maxItems} values` });
|
||||
if (isRecord(schema.items))
|
||||
value.forEach((entry, index) => validateValue(schema.items as JsonSchema, entry, `${path}.${index}`, issues));
|
||||
}
|
||||
|
||||
function validateObjectValue(
|
||||
schema: JsonSchema,
|
||||
value: Record<string, unknown>,
|
||||
path: string,
|
||||
issues: CustomWidgetOptionIssue[],
|
||||
) {
|
||||
const branch = isRecord(schema.if) ? (matchesSchema(schema.if, value) ? schema.then : schema.else) : undefined;
|
||||
const branchSchema = isRecord(branch) ? branch : {};
|
||||
const properties = {
|
||||
...(isRecord(schema.properties) ? schema.properties : {}),
|
||||
...(isRecord(branchSchema.properties) ? branchSchema.properties : {}),
|
||||
};
|
||||
const required = [
|
||||
...(Array.isArray(schema.required) ? schema.required : []),
|
||||
...(Array.isArray(branchSchema.required) ? branchSchema.required : []),
|
||||
].filter((entry): entry is string => typeof entry === "string");
|
||||
for (const key of required) {
|
||||
if (value[key] === undefined) issues.push({ path: `${path}.${key}`, message: "This field is required" });
|
||||
}
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const childSchema = properties[key];
|
||||
if (isRecord(childSchema)) validateValue(childSchema, child, `${path}.${key}`, issues);
|
||||
else if (schema.additionalProperties === false) issues.push({ path: `${path}.${key}`, message: "Unknown option" });
|
||||
}
|
||||
}
|
||||
|
||||
function matchesSchema(schema: JsonSchema, value: unknown): boolean {
|
||||
const issues: CustomWidgetOptionIssue[] = [];
|
||||
validateValue(schema, value, "value", issues);
|
||||
return issues.length === 0;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -4,124 +4,23 @@ import { customWidgetMethods } from "./schema-types";
|
||||
|
||||
export const customJsxNetworkScopes = ["public", "private", "loopback"] as const;
|
||||
export type CustomJsxNetworkScope = (typeof customJsxNetworkScopes)[number];
|
||||
export const customJsxRequestParameterTypes = ["string", "number", "boolean"] as const;
|
||||
export type CustomJsxRequestParameterType = (typeof customJsxRequestParameterTypes)[number];
|
||||
|
||||
export const customWidgetIdentifierSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[a-z][a-z0-9_-]*$/, "IDs must start with a letter and contain lowercase letters, numbers, - or _");
|
||||
export const isCustomWidgetParameterIdentifier = (value: string) => /^[A-Za-z][A-Za-z0-9_-]*$/u.test(value);
|
||||
export const customWidgetParameterIdentifierSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.refine(
|
||||
isCustomWidgetParameterIdentifier,
|
||||
"Parameter names must start with a letter and contain letters, numbers, - or _",
|
||||
);
|
||||
.regex(/^[A-Za-z][A-Za-z0-9_-]*$/u, "IDs must start with a letter and contain letters, numbers, - or _");
|
||||
|
||||
const requestParametersSchema = z
|
||||
.record(customWidgetParameterIdentifierSchema, z.enum(customJsxRequestParameterTypes))
|
||||
.refine((parameters) => Object.keys(parameters).length <= 32, "A request can declare at most 32 parameters");
|
||||
const optionReferenceSchema = z.object({ $option: customWidgetParameterIdentifierSchema }).strict();
|
||||
const requestOptionBindingValueSchema = z.union([z.string(), z.number().finite(), z.boolean(), optionReferenceSchema]);
|
||||
const requestOptionsBindingSchema = z
|
||||
.record(customWidgetParameterIdentifierSchema, requestOptionBindingValueSchema)
|
||||
.refine((bindings) => Object.keys(bindings).length <= 32, "A request can bind at most 32 parameters");
|
||||
const reservedRequestHeaders = new Set([
|
||||
"authorization",
|
||||
"connection",
|
||||
"content-length",
|
||||
"cookie",
|
||||
"expect",
|
||||
"forwarded",
|
||||
"host",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"via",
|
||||
]);
|
||||
const headerNameSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, "Header names must be valid HTTP tokens")
|
||||
.refine((name) => {
|
||||
const normalized = name.toLowerCase();
|
||||
return (
|
||||
!reservedRequestHeaders.has(normalized) &&
|
||||
!normalized.startsWith("proxy-") &&
|
||||
!normalized.startsWith("sec-") &&
|
||||
!normalized.startsWith("x-forwarded-")
|
||||
);
|
||||
}, "Authentication cannot use a reserved, proxy, forwarding, or hop-by-hop header");
|
||||
const staticHeadersSchema = z
|
||||
.record(headerNameSchema, z.string().max(8192))
|
||||
.refine((headers) => Object.keys(headers).length <= 32, "A request can declare at most 32 static headers")
|
||||
.refine(
|
||||
(headers) =>
|
||||
Object.keys(headers).every((name) => {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
return (
|
||||
!reservedRequestHeaders.has(normalized) &&
|
||||
!normalized.startsWith("proxy-") &&
|
||||
!normalized.startsWith("sec-") &&
|
||||
!normalized.startsWith("x-forwarded-")
|
||||
);
|
||||
}),
|
||||
"Static headers cannot override authentication, cookies, routing, forwarding, proxy, or hop-by-hop headers",
|
||||
)
|
||||
.refine(
|
||||
(headers) =>
|
||||
Object.entries(headers).every(
|
||||
([name, value]) =>
|
||||
!/(^|[-_])(api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu.test(
|
||||
name,
|
||||
) || value.trim().length === 0,
|
||||
),
|
||||
"Credential-like static headers must use source authentication",
|
||||
);
|
||||
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, "Header names must be valid HTTP tokens");
|
||||
|
||||
const collectParameterNames = (value: unknown, result = new Set<string>()): Set<string> => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry) => collectParameterNames(entry, result));
|
||||
return result;
|
||||
}
|
||||
if (value === null || typeof value !== "object") return result;
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") {
|
||||
result.add(entries[0][1]);
|
||||
return result;
|
||||
}
|
||||
entries.forEach(([, entry]) => collectParameterNames(entry, result));
|
||||
return result;
|
||||
};
|
||||
|
||||
const hasNoControlCharacters = (value: string) =>
|
||||
[...value].every((character) => {
|
||||
const codePoint = character.codePointAt(0) ?? 0;
|
||||
return codePoint >= 0x20 && codePoint !== 0x7f;
|
||||
});
|
||||
|
||||
const authSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("none") }),
|
||||
z.object({ type: z.literal("bearer") }),
|
||||
z.object({ type: z.literal("basic") }),
|
||||
z.object({ type: z.literal("apiKeyHeader"), headerName: headerNameSchema }),
|
||||
z.object({
|
||||
type: z.literal("apiKeyQuery"),
|
||||
parameterName: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.refine(hasNoControlCharacters, "Query authentication parameter names cannot contain control characters"),
|
||||
}),
|
||||
const authSchema = z.union([
|
||||
z.enum(["none", "bearer", "basic"]),
|
||||
z.strictObject({ type: z.literal("apiKeyHeader"), name: headerNameSchema }),
|
||||
z.strictObject({ type: z.literal("apiKeyQuery"), name: z.string().trim().min(1).max(256) }),
|
||||
]);
|
||||
|
||||
export type CustomWidgetSourceUrlIssue = "invalid" | "protocol" | "credentials" | "queryOrFragment";
|
||||
@@ -142,9 +41,8 @@ const sourceUrlIssueMessages: Record<CustomWidgetSourceUrlIssue, string> = {
|
||||
queryOrFragment: "API source URLs cannot contain a query string or fragment",
|
||||
};
|
||||
|
||||
export const customWidgetSourceSchema = z.object({
|
||||
id: customWidgetIdentifierSchema,
|
||||
name: z.string().trim().min(1).max(128),
|
||||
export const customWidgetSourceSchema = z.strictObject({
|
||||
name: z.string().trim().min(1).max(128).optional(),
|
||||
baseUrl: z
|
||||
.string()
|
||||
.url()
|
||||
@@ -154,124 +52,182 @@ export const customWidgetSourceSchema = z.object({
|
||||
if (issue && issue !== "invalid") ctx.addIssue({ code: "custom", message: sourceUrlIssueMessages[issue] });
|
||||
}),
|
||||
networkScope: z.enum(customJsxNetworkScopes),
|
||||
auth: authSchema,
|
||||
auth: authSchema.default("none"),
|
||||
});
|
||||
export type CustomWidgetSource = z.infer<typeof customWidgetSourceSchema>;
|
||||
|
||||
export const customWidgetSourcesSchema = z
|
||||
.record(customWidgetIdentifierSchema, customWidgetSourceSchema)
|
||||
.refine((sources) => Object.keys(sources).length <= 8, "A widget can use at most 8 API sources")
|
||||
.refine((sources) => Object.hasOwn(sources, "default"), "A widget must define a default API source");
|
||||
|
||||
export const optionReferenceSchema = z.strictObject({ $option: customWidgetIdentifierSchema });
|
||||
export const parameterReferenceSchema = z.strictObject({ $param: customWidgetIdentifierSchema });
|
||||
export type CustomWidgetValueReference =
|
||||
| z.infer<typeof optionReferenceSchema>
|
||||
| z.infer<typeof parameterReferenceSchema>;
|
||||
|
||||
export const boundValueSchema: z.ZodType<unknown> = z.lazy(() =>
|
||||
z.union([
|
||||
z.null(),
|
||||
z.string(),
|
||||
z.number().finite(),
|
||||
z.boolean(),
|
||||
optionReferenceSchema,
|
||||
parameterReferenceSchema,
|
||||
z.array(boundValueSchema),
|
||||
z.record(z.string(), boundValueSchema),
|
||||
]),
|
||||
);
|
||||
|
||||
const reservedRequestHeaders = new Set([
|
||||
"authorization",
|
||||
"connection",
|
||||
"content-length",
|
||||
"cookie",
|
||||
"expect",
|
||||
"forwarded",
|
||||
"host",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"via",
|
||||
]);
|
||||
|
||||
const headersSchema = z
|
||||
.record(headerNameSchema, z.string().max(8192))
|
||||
.refine((headers) => Object.keys(headers).length <= 32, "A request can declare at most 32 headers")
|
||||
.refine(
|
||||
(headers) =>
|
||||
Object.keys(headers).every((name) => {
|
||||
const normalized = name.toLowerCase();
|
||||
return (
|
||||
!reservedRequestHeaders.has(normalized) &&
|
||||
!normalized.startsWith("proxy-") &&
|
||||
!normalized.startsWith("sec-") &&
|
||||
!normalized.startsWith("x-forwarded-")
|
||||
);
|
||||
}),
|
||||
"Headers cannot override authentication, cookies, routing, forwarding, proxy, or hop-by-hop headers",
|
||||
)
|
||||
.refine(
|
||||
(headers) =>
|
||||
Object.keys(headers).every((name) => !/(?:api[-_]?key|authorization|password|secret|token)/iu.test(name)),
|
||||
"Credential headers must be configured through source authentication",
|
||||
);
|
||||
|
||||
const confirmationSchema = z.union([
|
||||
z.string().trim().min(1).max(512),
|
||||
z.strictObject({
|
||||
title: z.string().trim().min(1).max(128),
|
||||
message: z.string().trim().min(1).max(512),
|
||||
confirmLabel: z.string().trim().min(1).max(64).optional(),
|
||||
destructive: z.boolean().optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const customJsxRequestSchema = z
|
||||
.object({
|
||||
id: customWidgetIdentifierSchema,
|
||||
sourceId: customWidgetIdentifierSchema,
|
||||
kind: z.enum(["query", "action"]),
|
||||
method: z.enum(customWidgetMethods),
|
||||
pathTemplate: z
|
||||
.strictObject({
|
||||
source: customWidgetIdentifierSchema.default("default"),
|
||||
kind: z.enum(["query", "action"]).default("query"),
|
||||
method: z.enum(customWidgetMethods).default("GET"),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(2048)
|
||||
.startsWith("/")
|
||||
.refine((path) => !path.startsWith("//"), "Path templates must be same-origin paths")
|
||||
.refine((path) => !path.includes("\\"), "Path templates cannot contain backslashes")
|
||||
.refine((path) => !path.includes("#"), "Path templates cannot contain URL fragments"),
|
||||
parameters: requestParametersSchema,
|
||||
optionsBinding: requestOptionsBindingSchema.optional(),
|
||||
queryTemplate: z.record(z.string().min(1).max(256), z.json()).optional(),
|
||||
bodyTemplate: z.json().optional(),
|
||||
staticHeaders: staticHeadersSchema.optional(),
|
||||
auth: z.enum(["inherit", "none"]),
|
||||
minimumBoardPermission: z.enum(["view", "modify", "full"]),
|
||||
trigger: z.enum(["load", "manual"]).default("manual"),
|
||||
cacheTtlSeconds: z.number().int().min(0).max(3600).optional(),
|
||||
confirmation: z
|
||||
.object({
|
||||
title: z.string().min(1).max(128),
|
||||
message: z.string().min(1).max(512),
|
||||
confirmLabel: z.string().min(1).max(64).optional(),
|
||||
destructive: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
.refine((path) => !path.startsWith("//"), "Request paths must be same-origin")
|
||||
.refine((path) => !path.includes("\\"), "Request paths cannot contain backslashes")
|
||||
.refine((path) => !path.includes("#"), "Request paths cannot contain URL fragments")
|
||||
.refine(
|
||||
(path) => !/[{}]/u.test(path.replaceAll(/\{(?:option|param):[A-Za-z][A-Za-z0-9_-]*\}/gu, "")),
|
||||
"Request paths contain an invalid placeholder; use {option:name} or {param:name}",
|
||||
),
|
||||
trigger: z.enum(["load", "manual"]).optional(),
|
||||
query: z.record(z.string().min(1).max(256), boundValueSchema).optional(),
|
||||
body: boundValueSchema.optional(),
|
||||
headers: headersSchema.optional(),
|
||||
auth: z.enum(["inherit", "none"]).default("inherit"),
|
||||
permission: z.enum(["view", "modify", "full"]).optional(),
|
||||
cacheSeconds: z.number().int().min(0).max(3600).optional(),
|
||||
confirmation: confirmationSchema.optional(),
|
||||
invalidates: z.array(customWidgetIdentifierSchema).max(32).optional(),
|
||||
})
|
||||
.superRefine((request, ctx) => {
|
||||
if (request.kind === "action" && request.trigger === "load") {
|
||||
ctx.addIssue({ code: "custom", path: ["trigger"], message: "Actions cannot run automatically" });
|
||||
}
|
||||
if (request.kind === "action" && request.cacheTtlSeconds !== undefined && request.cacheTtlSeconds !== 0) {
|
||||
ctx.addIssue({ code: "custom", path: ["cacheTtlSeconds"], message: "Actions cannot be cached" });
|
||||
}
|
||||
if (request.kind === "query" && request.confirmation !== undefined) {
|
||||
ctx.addIssue({ code: "custom", path: ["confirmation"], message: "Only actions can require confirmation" });
|
||||
}
|
||||
if (request.kind === "query" && request.invalidates !== undefined) {
|
||||
ctx.addIssue({ code: "custom", path: ["invalidates"], message: "Only actions can invalidate queries" });
|
||||
}
|
||||
if (request.method === "DELETE" && request.minimumBoardPermission !== "full") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["minimumBoardPermission"],
|
||||
message: "DELETE requests require full permission",
|
||||
});
|
||||
}
|
||||
const declared = new Set(Object.keys(request.parameters));
|
||||
const optionBindings = request.optionsBinding ?? {};
|
||||
for (const [name, binding] of Object.entries(optionBindings)) {
|
||||
const parameterType = request.parameters[name];
|
||||
if (!parameterType) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["optionsBinding", name],
|
||||
message: `Option binding '${name}' does not match a declared parameter`,
|
||||
});
|
||||
} else if ((typeof binding !== "object" || binding === null) && typeof binding !== parameterType) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["optionsBinding", name],
|
||||
message: `Literal binding for '${name}' must be ${parameterType}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (request.kind === "query" && request.trigger === "load") {
|
||||
for (const name of declared) {
|
||||
if (!Object.hasOwn(optionBindings, name)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["optionsBinding", name],
|
||||
message: `Load request parameter '${name}' requires an explicit option reference or literal value`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const used = [...request.pathTemplate.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1] ?? "");
|
||||
collectParameterNames(request.queryTemplate).forEach((name) => used.push(name));
|
||||
collectParameterNames(request.bodyTemplate).forEach((name) => used.push(name));
|
||||
for (const name of used) {
|
||||
if (!isCustomWidgetParameterIdentifier(name)) {
|
||||
ctx.addIssue({ code: "custom", path: ["pathTemplate"], message: `Placeholder '${name}' is invalid` });
|
||||
} else if (!declared.has(name)) {
|
||||
ctx.addIssue({ code: "custom", path: ["parameters"], message: `Placeholder '${name}' is not declared` });
|
||||
}
|
||||
}
|
||||
.transform((request) => {
|
||||
const confirmation =
|
||||
request.method === "DELETE" && request.confirmation === undefined
|
||||
? ({ title: "Confirm action", message: "Are you sure?", destructive: true } as const)
|
||||
: request.confirmation;
|
||||
return {
|
||||
...request,
|
||||
trigger: request.kind === "action" ? ("manual" as const) : (request.trigger ?? ("load" as const)),
|
||||
permission:
|
||||
request.method === "DELETE"
|
||||
? ("full" as const)
|
||||
: (request.permission ?? (request.kind === "action" ? ("modify" as const) : ("view" as const))),
|
||||
...(confirmation === undefined ? {} : { confirmation }),
|
||||
};
|
||||
});
|
||||
export type CustomJsxRequest = z.infer<typeof customJsxRequestSchema>;
|
||||
export type CustomJsxRequestOptionsBinding = NonNullable<CustomJsxRequest["optionsBinding"]>;
|
||||
|
||||
export function resolveCustomWidgetOptionsBinding(
|
||||
request: Pick<CustomJsxRequest, "id" | "parameters" | "optionsBinding">,
|
||||
options: Record<string, unknown>,
|
||||
): Record<string, string | number | boolean> {
|
||||
const bindings = request.optionsBinding ?? {};
|
||||
const params: Record<string, string | number | boolean> = {};
|
||||
for (const [name, expectedType] of Object.entries(request.parameters)) {
|
||||
const binding = bindings[name];
|
||||
if (binding === undefined) {
|
||||
throw new Error(`Request '${request.id}' parameter '${name}' has no explicit option binding`);
|
||||
}
|
||||
const optionName = typeof binding === "object" ? binding.$option : undefined;
|
||||
const value = optionName === undefined ? binding : options[optionName];
|
||||
if (typeof value !== expectedType) {
|
||||
const source = optionName === undefined ? "literal binding" : `option '${optionName}'`;
|
||||
throw new Error(`Request '${request.id}' parameter '${name}' requires ${source} to be ${expectedType}`);
|
||||
}
|
||||
params[name] = value as string | number | boolean;
|
||||
}
|
||||
return params;
|
||||
export type CustomJsxRequest = z.infer<typeof customJsxRequestSchema>;
|
||||
export type CustomJsxRequestInput = z.input<typeof customJsxRequestSchema>;
|
||||
|
||||
export interface CustomWidgetConfirmation {
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
destructive?: boolean;
|
||||
}
|
||||
|
||||
export function getCustomWidgetConfirmation(
|
||||
request: Pick<CustomJsxRequest, "confirmation" | "method">,
|
||||
): CustomWidgetConfirmation | undefined {
|
||||
if (typeof request.confirmation === "string") {
|
||||
return { title: "Confirm action", message: request.confirmation };
|
||||
}
|
||||
return request.confirmation;
|
||||
}
|
||||
|
||||
export const customWidgetRequestsSchema = z
|
||||
.record(customWidgetIdentifierSchema, customJsxRequestSchema)
|
||||
.refine((requests) => Object.keys(requests).length <= 64, "A widget can define at most 64 requests");
|
||||
|
||||
const pathReferencePattern = /\{(option|param):([A-Za-z][A-Za-z0-9_-]*)\}/gu;
|
||||
|
||||
export interface CustomWidgetRequestReferences {
|
||||
options: Set<string>;
|
||||
params: Set<string>;
|
||||
}
|
||||
|
||||
export function collectCustomWidgetRequestReferences(request: Pick<CustomJsxRequest, "path" | "query" | "body">) {
|
||||
const references: CustomWidgetRequestReferences = { options: new Set(), params: new Set() };
|
||||
for (const match of request.path.matchAll(pathReferencePattern)) {
|
||||
const name = match[2];
|
||||
if (name) references[match[1] === "option" ? "options" : "params"].add(name);
|
||||
}
|
||||
collectBoundValueReferences(request.query, references);
|
||||
collectBoundValueReferences(request.body, references);
|
||||
return references;
|
||||
}
|
||||
|
||||
function collectBoundValueReferences(value: unknown, references: CustomWidgetRequestReferences): void {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry) => collectBoundValueReferences(entry, references));
|
||||
return;
|
||||
}
|
||||
if (value === null || typeof value !== "object") return;
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$option" && typeof entries[0][1] === "string") {
|
||||
references.options.add(entries[0][1]);
|
||||
return;
|
||||
}
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") {
|
||||
references.params.add(entries[0][1]);
|
||||
return;
|
||||
}
|
||||
entries.forEach(([, entry]) => collectBoundValueReferences(entry, references));
|
||||
}
|
||||
@@ -1,143 +1,60 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { customWidgetOptionsSchemaSchema } from "./options-schema";
|
||||
import { customJsxRequestSchema } from "./request-schema";
|
||||
import { customWidgetOptionsSchema } from "./options-schema";
|
||||
import { customWidgetRequestsSchema } from "./request-schema";
|
||||
|
||||
let requestsSchema: Record<string, unknown> | undefined;
|
||||
let optionsSchema: Record<string, unknown> | undefined;
|
||||
let defaultOptionsSchema: Record<string, unknown> | undefined;
|
||||
|
||||
export function getCustomWidgetRequestsJsonSchema() {
|
||||
requestsSchema ??= {
|
||||
...z.toJSONSchema(customJsxRequestSchema.array()),
|
||||
...z.toJSONSchema(customWidgetRequestsSchema, { io: "input" }),
|
||||
title: "Named Custom Widget queries and actions",
|
||||
};
|
||||
return requestsSchema;
|
||||
}
|
||||
|
||||
export function getCustomWidgetOptionsJsonSchema() {
|
||||
optionsSchema ??= {
|
||||
...z.toJSONSchema(customWidgetOptionsSchemaSchema),
|
||||
title: "Custom Widget options schema",
|
||||
};
|
||||
optionsSchema ??= { ...z.toJSONSchema(customWidgetOptionsSchema, { io: "input" }), title: "Custom Widget options" };
|
||||
return optionsSchema;
|
||||
}
|
||||
|
||||
export function getCustomWidgetDefaultOptionsJsonSchema() {
|
||||
defaultOptionsSchema ??= {
|
||||
...z.toJSONSchema(z.record(z.string(), z.unknown())),
|
||||
title: "Custom Widget default option values",
|
||||
description: "Values must validate against the widget options schema.",
|
||||
};
|
||||
return defaultOptionsSchema;
|
||||
}
|
||||
|
||||
export const CUSTOM_WIDGET_REQUEST_EXAMPLES = {
|
||||
minimal: [
|
||||
{
|
||||
id: "data",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/status",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
minimal: { data: { path: "/api/status" } },
|
||||
full: {
|
||||
environments: { path: "/api/environments", cacheSeconds: 60 },
|
||||
summary: {
|
||||
path: "/api/environments/{option:environmentId}/summary",
|
||||
query: { includeStopped: { $option: "includeStopped" } },
|
||||
cacheSeconds: 60,
|
||||
},
|
||||
],
|
||||
full: [
|
||||
{
|
||||
id: "environments",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/environments",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 60,
|
||||
},
|
||||
{
|
||||
id: "summary",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/environments/{environmentId}/summary",
|
||||
parameters: { environmentId: "number", includeStopped: "boolean" },
|
||||
optionsBinding: {
|
||||
environmentId: { $option: "environmentId" },
|
||||
includeStopped: false,
|
||||
},
|
||||
queryTemplate: { includeStopped: { $param: "includeStopped" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "load",
|
||||
cacheTtlSeconds: 60,
|
||||
},
|
||||
{
|
||||
id: "search",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
pathTemplate: "/api/search",
|
||||
parameters: { query: "string", limit: "number" },
|
||||
queryTemplate: { limit: { $param: "limit" } },
|
||||
bodyTemplate: { term: { $param: "query" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
search: {
|
||||
trigger: "manual",
|
||||
cacheTtlSeconds: 30,
|
||||
method: "POST",
|
||||
path: "/api/search",
|
||||
query: { limit: { $param: "limit" } },
|
||||
body: { term: { $param: "query" } },
|
||||
},
|
||||
{
|
||||
id: "restart",
|
||||
sourceId: "default",
|
||||
restart: {
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/api/containers/{id}/restart",
|
||||
parameters: { id: "string" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
confirmation: {
|
||||
title: "Restart container",
|
||||
message: "Restart this container now?",
|
||||
confirmLabel: "Restart",
|
||||
},
|
||||
invalidates: ["search"],
|
||||
path: "/api/containers/{param:id}/restart",
|
||||
confirmation: "Restart this container?",
|
||||
invalidates: ["summary"],
|
||||
},
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const CUSTOM_WIDGET_OPTIONS_EXAMPLES = {
|
||||
minimal: {
|
||||
schema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaults: {},
|
||||
},
|
||||
minimal: {},
|
||||
full: {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string", title: "Title", "x-homarr": { control: "text" } },
|
||||
limit: { type: "number", title: "Result limit", minimum: 1, maximum: 100 },
|
||||
environmentId: {
|
||||
type: "number",
|
||||
title: "Environment",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: {
|
||||
requestId: "environments",
|
||||
itemsPath: "items",
|
||||
valuePath: "Id",
|
||||
labelPath: "Name",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ["limit"],
|
||||
additionalProperties: false,
|
||||
title: { label: "Title", control: "text", default: "Overview" },
|
||||
limit: { label: "Result limit", control: "number", default: 20, min: 1, max: 100 },
|
||||
environmentId: {
|
||||
label: "Environment",
|
||||
control: "select",
|
||||
default: 1,
|
||||
choicesFrom: { request: "environments", itemsPath: "items", valuePath: "Id", labelPath: "Name" },
|
||||
},
|
||||
defaults: { title: "Overview", limit: 20 },
|
||||
},
|
||||
} as const;
|
||||
@@ -10,7 +10,7 @@ let customWidgetJsonSchema: Record<string, unknown> | undefined;
|
||||
|
||||
export function getCustomWidgetJsonSchema() {
|
||||
customWidgetJsonSchema ??= {
|
||||
...z.toJSONSchema(customWidgetImportSchema),
|
||||
...z.toJSONSchema(customWidgetImportSchema, { io: "input" }),
|
||||
title: "Homarr Custom JSX v2 widget",
|
||||
description: "The only supported Homarr custom-widget format. Secrets are configured separately.",
|
||||
};
|
||||
|
||||
@@ -1,37 +1,33 @@
|
||||
import type { CustomWidgetSource } from "./request-schema";
|
||||
import type { CustomWidgetSecretKind } from "./schema-types";
|
||||
|
||||
type AuthType = "none" | "bearer" | "basic" | "apiKeyHeader" | "apiKeyQuery";
|
||||
|
||||
export interface CustomWidgetSecretRequirement {
|
||||
sourceId: string;
|
||||
sourceName: string;
|
||||
authType: CustomWidgetSource["auth"]["type"];
|
||||
authType: AuthType;
|
||||
kind: CustomWidgetSecretKind;
|
||||
destination?: string;
|
||||
}
|
||||
|
||||
export function getCustomWidgetRequiredSecretKinds(authType: CustomWidgetSource["auth"]["type"]) {
|
||||
export function getCustomWidgetRequiredSecretKinds(authType: AuthType) {
|
||||
if (authType === "basic") return ["username", "password"] as const;
|
||||
if (authType === "bearer" || authType === "apiKeyHeader" || authType === "apiKeyQuery") {
|
||||
return ["apiKey"] as const;
|
||||
}
|
||||
if (["bearer", "apiKeyHeader", "apiKeyQuery"].includes(authType)) return ["apiKey"] as const;
|
||||
return [] as const;
|
||||
}
|
||||
|
||||
export function getCustomWidgetSecretRequirements(
|
||||
sources: readonly CustomWidgetSource[],
|
||||
sources: Record<string, CustomWidgetSource>,
|
||||
): CustomWidgetSecretRequirement[] {
|
||||
return sources.flatMap((source) =>
|
||||
getCustomWidgetRequiredSecretKinds(source.auth.type).map((kind) => ({
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
authType: source.auth.type,
|
||||
return Object.entries(sources).flatMap(([sourceId, source]) => {
|
||||
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
return getCustomWidgetRequiredSecretKinds(authType).map((kind) => ({
|
||||
sourceId,
|
||||
sourceName: source.name ?? sourceId,
|
||||
authType,
|
||||
kind,
|
||||
destination:
|
||||
source.auth.type === "apiKeyHeader"
|
||||
? source.auth.headerName
|
||||
: source.auth.type === "apiKeyQuery"
|
||||
? source.auth.parameterName
|
||||
: undefined,
|
||||
})),
|
||||
);
|
||||
destination: typeof source.auth === "object" ? source.auth.name : undefined,
|
||||
}));
|
||||
});
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"files": [
|
||||
{
|
||||
"path": "SKILL.md",
|
||||
"content": "---\nname: homarr-custom-widget\ndescription: Author safe Homarr Custom JSX v2 widgets from API documentation. Use when creating or fixing Homarr custom widgets, including multi-source dashboards, queries, actions, options, temporary inputs, and Mantine JSX.\nlicense: Apache-2.0\nmetadata:\n version: \"2.0.0\"\n---\n\n# Homarr Custom Widget\n\nCreate one widget at a time. Repeat the workflow when the user asks for several widgets; do not invent packs or shared connections.\n\n## Choose the authoring reference\n\nWhen connected to Homarr, retrieve the live widget schema and component catalog before authoring. Live metadata is authoritative because Homarr and Mantine versions can differ between installations.\n\nFor offline authoring, read these installed, release-matched references in order:\n\n1. [Schema guide](references/schema.md)\n2. [Canonical widget JSON Schema](references/widget-schema.json)\n3. [JSX runtime](references/runtime.md)\n4. [Security boundary](references/security.md)\n5. [Component catalog guide](references/components.md)\n6. [Canonical component catalog](references/component-catalog.json)\n7. [Canonical examples](references/examples.json)\n8. [Official Mantine LLM index](references/mantine-core.md)\n9. [Official Mantine Dates guide](references/mantine-dates.md)\n10. [Mantine Charts links](references/mantine-charts.md)\n11. [Homarr components](references/homarr-components.md)\n\nTogether, this file and its references are the complete offline authoring bundle for the matching Homarr release. The JSON catalog contains the exact enabled component names, prop metadata, bindings, blocked capabilities, and versions. If live metadata is available, prefer it because it reflects the installed Homarr and Mantine versions.\n\n## Authoring workflow\n\n1. Read the API documentation supplied by the user. Ask for a missing base URL only when it cannot be inferred safely.\n2. Build one credential-free `homarr-custom-widget-v2` manifest and one safe JSX template.\n3. Use immutable local `const` blocks for repeated derived values and `RecursiveList` for arbitrary-depth trees. Do not emulate either feature with unrestricted JavaScript or authored recursion.\n4. Return the complete manifest and JSX in the exact fenced-block format requested by the authoring prompt.\n5. When the user supplies Homarr diagnostics, correct every reported issue while preserving unrelated fields.\n\n## Output rules\n\n- Use inline sources, named requests, definition-owned options, temporary bound inputs, and one safe JSX template.\n- Use `kind`, not the HTTP method, to distinguish reads from user-triggered actions.\n- Give every declared request parameter an explicit source. Load queries use `optionsBinding` with an option reference or primitive literal; manual queries and actions receive values only from the invoking component's `params` prop. Never infer bindings from matching names.\n- Treat `status.<requestId>` as `{ loading, ok, status, statusText, error }`. Never compare it with `\"loading\"`, `\"success\"`, or `\"error\"`; check `status.list?.loading`, `status.list?.ok === false`, or `status.list?.ok === true`.\n- Never put a credential in JSX, options, headers, URLs, examples, exports, logs, or chat output.\n- Use declarative `bind` controls and Homarr request components. Controlled collection callbacks, zero-argument derived-value IIFEs, and the `RecursiveList` child template may use the restricted safe-block grammar documented in the runtime reference. Never emit imports, hooks, refs, raw callback props, browser requests, or arbitrary JavaScript.\n- Include responsive loading, empty, error, and success states.\n- Keep actions explicit, permission-scoped, confirmed when destructive, and followed by targeted invalidation.\n"
|
||||
},
|
||||
{
|
||||
"path": "references/schema.md",
|
||||
"content": "# Custom Widget v2 schema\n\nEvery import and export is one object with `$schema: \"homarr-custom-widget-v2\"`, metadata, `sources`, `requests`, `optionsSchema`, `defaultOptions`, and `template`. Secrets are accepted separately by create/update/preview operations and never exported.\n\nThe safe-local-binding and `RecursiveList` expansion changes only template authoring. It does not add database fields, request fields, persistence, or another widget schema version.\n\n```ts\ninterface HomarrCustomWidgetV2 {\n $schema: \"homarr-custom-widget-v2\";\n name: string;\n description?: string;\n iconUrl?: string;\n sources: CustomWidgetSource[];\n requests: CustomWidgetRequest[];\n optionsSchema: CustomWidgetOptionsSchema;\n defaultOptions: Record<string, unknown>;\n template: string;\n}\n```\n\nA source has a stable lowercase `id`, display `name`, `baseUrl`, `networkScope` (`public`, `private`, or `loopback`), and one auth mode: `none`, `bearer`, `basic`, `apiKeyHeader`, or `apiKeyQuery`.\n\nA request has `id`, `sourceId`, `kind`, any supported HTTP `method`, same-origin `pathTemplate`, declared primitive `parameters`, optional `optionsBinding`, `queryTemplate`, and `bodyTemplate`, optional safe `staticHeaders`, `auth`, `minimumBoardPermission`, optional `trigger`, caching, confirmation, and invalidation. Parameter names may use camelCase. Reference a declared parameter with `{name}` in a path or `{ \"$param\": \"name\" }` in structured query/body data.\n\nEvery declared parameter needs an explicit source. For a load query, bind each parameter in `optionsBinding` with `{ \"$option\": \"optionName\" }` or a primitive literal of the declared type. The referenced option must exist in `optionsSchema`. For manual queries and actions, the invoking `SubFetch`, `ActionButton`, or `ToggleSwitch` supplies the complete parameter object through `params`. Never infer a source because a parameter, option, or temporary input has the same name.\n\nDynamic option requests have no JSX invoker and therefore also require `optionsBinding` for every parameter they declare.\n\nOptions use a restricted object JSON Schema. Set `additionalProperties: false`. Presentation metadata lives under `x-homarr`; dynamic selects use `optionsSource.requestId`, optional `itemsPath` for wrapped arrays, `valuePath`, and `labelPath`. Default options must validate against the schema.\n\nOption and bind names start with a letter and use letters, numbers, `-`, or `_`; camelCase is supported. Every JSX `bind` value is a literal temporary input name.\n\nDo not model credentials as options or static defaults. Credential-like option names and values are rejected; source authentication is configured separately.\n\nDo not add `stateSchema`, `defaultState`, scripts, imports, or component declarations to the manifest. Temporary interaction values come only from JSX `bind` controls and are exposed through `inputs`. Derived values declared with safe `const` blocks exist only while evaluating the template.\n\nThis reference is sufficient for offline authoring against the matching release. When connected, retrieve the live Custom Widget schema; it supersedes this static copy if the installed Homarr version differs.\n"
|
||||
},
|
||||
{
|
||||
"path": "references/widget-schema.json",
|
||||
"content": "{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"$schema\": {\n \"type\": \"string\",\n \"const\": \"homarr-custom-widget-v2\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 128\n },\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 512\n },\n \"iconUrl\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"sources\": {\n \"minItems\": 1,\n \"maxItems\": 8,\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 128\n },\n \"baseUrl\": {\n \"type\": \"string\",\n \"maxLength\": 2048,\n \"format\": \"uri\"\n },\n \"networkScope\": {\n \"type\": \"string\",\n \"enum\": [\n \"public\",\n \"private\",\n \"loopback\"\n ]\n },\n \"auth\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"none\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"bearer\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"basic\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"apiKeyHeader\"\n },\n \"headerName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"pattern\": \"^[!#$%&'*+\\\\-.^_`|~0-9A-Za-z]+$\"\n }\n },\n \"required\": [\n \"type\",\n \"headerName\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"apiKeyQuery\"\n },\n \"parameterName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256\n }\n },\n \"required\": [\n \"type\",\n \"parameterName\"\n ],\n \"additionalProperties\": false\n }\n ]\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"baseUrl\",\n \"networkScope\",\n \"auth\"\n ],\n \"additionalProperties\": false\n }\n },\n \"requests\": {\n \"maxItems\": 64,\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"sourceId\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"kind\": {\n \"type\": \"string\",\n \"enum\": [\n \"query\",\n \"action\"\n ]\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"GET\",\n \"POST\",\n \"PUT\",\n Line truncated
|
||||
},
|
||||
{
|
||||
"path": "references/runtime.md",
|
||||
"content": "# JSX runtime\n\nTemplates read four roots: `data.<requestId>`, `status.<requestId>`, `options`, and `inputs`.\n\nEach request status is an object:\n\n```ts\nstatus.<requestId> = {\n loading: boolean;\n ok?: boolean;\n status?: number;\n statusText?: string;\n error?: string;\n};\n```\n\nUse `status.list?.loading` for loading, `status.list?.ok === false` for failure, and `status.list?.ok === true` for success. Do not compare `status.list` with the strings `\"loading\"`, `\"success\"`, or `\"error\"`; those comparisons are always false and are rejected by validation.\n\nUse Mantine Core, Dates, Charts, safe Tabler icons, and Homarr runtime components. Safe installed Mantine exports are discovered automatically. Ordinary serializable props and Mantine style props pass through; `style` and `styles` are scoped and sanitized.\n\nRender icons as `<TablerIcon name=\"server\" size={18} />`. When connected, retrieve `homarr://custom-widgets/components/TablerIcon` for the supported icon names.\n\nUse `SubFetch` for a manual query, `ActionButton` or `ToggleSwitch` for an action, and `RefreshButton` to refresh data. A query with `trigger: \"load\"` populates its data automatically and follows the widget refresh interval.\n\nManual requests receive values only from the invoking component:\n\n```jsx\n<SubFetch requestId=\"search\" params={{ query: inputs.search }} />\n<ActionButton requestId=\"restart\" params={{ id: container.Id }}>Restart</ActionButton>\n```\n\nLoop variables and other JSX expressions can flow into a request only through that `params` prop. A load query has no invoking component, so every declared parameter must have an `optionsBinding` entry:\n\n```json\n{\n \"parameters\": { \"endpointId\": \"string\", \"showAll\": \"boolean\" },\n \"optionsBinding\": {\n \"endpointId\": { \"$option\": \"endpointId\" },\n \"showAll\": false\n }\n}\n```\n\nDo not rely on parameter and option names matching. For an invalid-placeholder or unresolved-parameter error on a load query, check missing `optionsBinding` entries before changing placeholder syntax.\n\nBind local controls declaratively:\n\n```jsx\n<TextInput bind=\"search\" label=\"Search\" />\n<DatePicker bind=\"selectedDate\" />\n<Select bind=\"selectedEntity\" data={options.entities} />\n```\n\nBound inputs exist only in memory while the widget is mounted and reset on reload. They are available as `inputs.<bindName>` and are never saved to local storage. Put durable user configuration in options. Do not author raw component callback props.\n\nBinding types follow the component mode. `Accordion multiple`, `Chip.Group multiple`, `TreeSelect mode=\"multiple\"|\"checkbox\"`, and date pickers with `type=\"multiple\"|\"range\"` expose `string[]`. `DateTimePicker` and `InlineDateTimePicker` support `type=\"range\"`, but not `multiple`. Components that do not advertise a temporary bind cannot use `bind`.\n\n## Immutable local bindings\n\nCollection callbacks may use a tightly constrained block body when a value would otherwise be recomputed throughout the returned JSX:\n\n```jsx\n{data.pokemon.map((pokemon) => {\n const segments = pokemon.url.split(\"/\").filter((part) => part);\n const dexId = segments.at(-1);\n const favorite = inputs.favorites.includes(pokemon.name);\n\n return (\n <Card key={dexId}>\n <Text>#{dexId}</Text>\n <Text>{pokemon.name}</Text>\n {favorite && <Badge>Favorite</Badge>}\n </Card>\n );\n})}\n```\n\nA page-level derived value may use a directly invoked, zero-argument inline arrow:\n\n```jsx\n{(() => {\n const visiblePokemon = data.pokemon.filter(\n (pokemon) => !inputs.favoritesOnly || inputs.favorites.includes(pokemon.name),\n );\n\n return <Stack>{visiblePokemon.map((pokemon) => <Text>{pokemon.name}</Text>)}</Stack>;\n})()}\n```\n\nA safe block contains one or more `const` declarations followed by exactly one final `return`. Each declaration uses one simple identifier and a required initializer made from existing safe expressions. Earlier local bindings are available to later initializers and to the return expression.\n\nThe following remain invalid:\n\n- `let`, `var`, assignment, update expressions, or destructuring.\n- Function or class declarations, and function values stored in `const`.\n- Loops, `if`, `switch`, `try`, `catch`, `throw`, labels, or `new`.\n- Async functions, generators, `await`, or `yield`.\n- Early or multiple returns.\n- Duplicate local names or shadowing `data`, `status`, `options`, or `inputs`.\n- Invoking a function obtained from API data or a property. Only a directly invoked zero-argument inline arrow is an IIFE.\n\nLocal evaluation shares the parent widget's depth, operation, collection, string, and rendered-node budgets. Blocks cannot reset or evade those limits.\n\nBlock diagnostics include `INVALID_LOCAL_DECLARATION`, `LOCAL_BINDING_REQUIRES_INITIALIZER`, `DUPLICATE_LOCAL_BINDING`, `RESERVED_LOCAL_BINDING`, `UNSUPPORTED_BLOCK_STATEMENT`, `BLOCK_REQULine truncated
|
||||
},
|
||||
{
|
||||
"path": "references/security.md",
|
||||
"content": "# Security boundary\n\nHomarr executes requests on the server and constrains them to a declared source. Network scopes, DNS checks, redirect validation, SSRF protection, request/response limits, timeouts, rates, permissions, and secret injection are enforced outside JSX.\n\nNever include secrets in a widget document. Configure them per widget source. Stored plaintext is never returned, duplicated, or exported.\n\nThe runtime blocks imports, hooks, refs, raw callback props, polymorphic roots, provider replacement, arbitrary portals, browser `fetch`, `XMLHttpRequest`, arbitrary JavaScript, evaluation, npm packages, prototype-pollution keys, unsafe URLs, global selectors, and CSS escaping the widget root.\n\nSafe block bodies are not general JavaScript. They permit only immutable `const` declarations with simple identifiers and one final return. Mutation, assignments, declarations of callable values, control-flow statements, async behavior, reserved-root shadowing, and multiple returns are rejected before rendering. A zero-argument IIFE is callable only when its callee is the inline arrow syntax itself. Values obtained from API data can never become executable callbacks.\n\nCollection callbacks, zero-argument derived-value IIFEs, and the `RecursiveList` child template execute inside the interpreter and share the parent widget's budgets. They are never passed to Mantine or React as authored callbacks.\n\n`RecursiveList` is a Homarr-owned traversal boundary, not general recursion. It validates dotted paths, rejects prototype-related segments, treats API objects as read-only, contains malformed branches, detects ancestor cycles, and enforces both depth and node caps. Defaults are 16 levels and 500 nodes; hard maximums are 32 levels and 2,000 nodes. Reaching a cap records a diagnostic and renders an omission row rather than throwing outside the widget.\n\nDo not work around a blocked capability. Express network behavior as a named request and interaction as a declarative Homarr component. Require explicit confirmation for destructive actions. Never let actions trigger on load.\n\nTreat request/response journals and diagnostics as sensitive. Homarr redacts credentials, but an agent should also avoid repeating private URLs, request bodies, or personal data unless necessary to fix the widget.\n\nThe installed static references describe the complete offline capability boundary for their matching release. When Homarr exposes live schema or component metadata, that metadata wins if it differs.\n"
|
||||
},
|
||||
{
|
||||
"path": "references/components.md",
|
||||
"content": "# Component catalog\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nThis is the complete Custom JSX component boundary for this Homarr release. The machine-readable `component-catalog.json` contains exact generated component, prop, binding, and safety metadata; these Markdown pages provide the human-readable inventory and upstream Mantine indexes. Ordinary serializable props pass through unless the capability boundary explicitly blocks them.\n\n## Package references\n\n- [Mantine Core](mantine-core.md) — 265 enabled, 133 denied\n- [Mantine Dates](mantine-dates.md) — 29 enabled, 3 denied\n- [Mantine Charts](mantine-charts.md) — 18 enabled, 1 denied\n- [Homarr components](homarr-components.md) — 13 enabled, 0 denied\n\n## Authoring boundary\n\n- Use the exact component names below. Compound names such as `Tabs.List`, `Card.Section`, and `Radio.Group` are distinct catalog entries.\n- Use the official Mantine LLM links for component props and examples. Homarr's live catalog is authoritative for availability, bindings, and blocked capabilities.\n- Use `bind=\"name\"` only when a component record declares bind metadata. Read the temporary in-memory value from `inputs.name`; it is never persisted.\n- Ordinary authored callbacks remain blocked. Restricted collection callbacks, directly invoked zero-argument derived-value IIFEs, and `RecursiveList`'s child template may use the immutable local `const` grammar in [JSX runtime](runtime.md#immutable-local-bindings).\n- Use [`RecursiveList`](homarr-components.md#component-recursivelist) for custom arbitrary-depth trees. Do not author recursion or pass a renderer callback to Mantine Tree.\n- Unknown ordinary Mantine props are advisory and are not silently discarded. Every capability listed in the blocked table is rejected.\n\n## Complete enabled inventory\n\n### Mantine Core\n\n[`Accordion`](https://mantine.dev/core/accordion/), [`Accordion.Chevron`](https://mantine.dev/core/accordion/), [`Accordion.Control`](https://mantine.dev/core/accordion/), [`Accordion.Item`](https://mantine.dev/core/accordion/), [`Accordion.Panel`](https://mantine.dev/core/accordion/), [`AccordionChevron`](https://mantine.dev/core/accordion-chevron/), [`AccordionControl`](https://mantine.dev/core/accordion-control/), [`AccordionItem`](https://mantine.dev/core/accordion-item/), [`AccordionPanel`](https://mantine.dev/core/accordion-panel/), [`ActionIcon`](https://mantine.dev/core/action-icon/), [`ActionIcon.Group`](https://mantine.dev/core/action-icon/), [`ActionIcon.GroupSection`](https://mantine.dev/core/action-icon/), [`ActionIconGroup`](https://mantine.dev/core/action-icon-group/), [`ActionIconGroupSection`](https://mantine.dev/core/action-icon-group-section/), [`Alert`](https://mantine.dev/core/alert/), [`AlphaSlider`](https://mantine.dev/core/alpha-slider/), [`Anchor`](https://mantine.dev/core/anchor/), [`AngleSlider`](https://mantine.dev/core/angle-slider/), [`AspectRatio`](https://mantine.dev/core/aspect-ratio/), [`Autocomplete`](https://mantine.dev/core/autocomplete/), [`Avatar`](https://mantine.dev/core/avatar/), [`Avatar.Group`](https://mantine.dev/core/avatar/), [`AvatarGroup`](https://mantine.dev/core/avatar-group/), [`BackgroundImage`](https://mantine.dev/core/background-image/), [`Badge`](https://mantine.dev/core/badge/), [`Blockquote`](https://mantine.dev/core/blockquote/), [`Box`](https://mantine.dev/core/box/), [`Breadcrumbs`](https://mantine.dev/core/breadcrumbs/), [`Burger`](https://mantine.dev/core/burger/), [`Button`](https://mantine.dev/core/button/), [`Button.Group`](https://mantine.dev/core/button/), [`Button.GroupSection`](https://mantine.dev/core/button/), [`ButtonGroup`](https://mantine.dev/core/button-group/), [`ButtonGroupSection`](https://mantine.dev/core/button-group-section/), [`Card`](https://mantine.dev/core/card/), [`Card.Section`](https://mantine.dev/core/card/), [`CardSection`](https://mantine.dev/core/card-section/), [`Center`](https://mantine.dev/core/center/), [`CheckIcon`](https://mantine.dev/core/check-icon/), [`Checkbox`](https://mantine.dev/core/checkbox/), [`Checkbox.Card`](https://mantine.dev/core/checkbox/), [`Checkbox.Group`](https://mantine.dev/core/checkbox/), [`Checkbox.Indicator`](https://mantine.dev/core/checkbox/), [`CheckboxCard`](https://mantine.dev/core/checkbox-card/), [`CheckboxGroup`](https://mantine.dev/core/checkbox-group/), [`CheckboxIndicator`](https://mantine.dev/core/checkbox-indicator/), [`Chip`](https://mantine.dev/core/chip/), [`Chip.Group`](https://mantine.dev/core/chip/), [`ChipGroup`](https://mantine.dev/core/chip-group/), [`CloseButton`](https://mantine.dev/core/close-button/), [`CloseIcon`](https://mantine.dev/core/close-icon/), [`Code`](https://mantine.dev/core/code/), [`Collapse`](https://mantine.dev/core/collapse/), [`ColorInput`](https://mantine.dev/core/color-input/), [`ColorPicker`](https://mantine.devLine truncated
|
||||
},
|
||||
{
|
||||
"path": "references/component-catalog.json",
|
||||
"content": "{\"schemaVersion\":1,\"mantineVersion\":\"9.4.1\",\"customWidgetVersion\":\"2.0.0\",\"types\":[\"\\\"\\\" | \\\"anonymous\\\" | \\\"use-credentials\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"auto\\\" | \\\"fixed\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"auto\\\" | \\\"all\\\" | \\\"fill\\\" | \\\"stroke\\\" | \\\"painted\\\" | \\\"visible\\\" | \\\"visibleFill\\\" | \\\"visiblePainted\\\" | \\\"visibleStroke\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"block\\\" | \\\"inline\\\" | \\\"both\\\" | \\\"horizontal\\\" | \\\"vertical\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"contain\\\" | \\\"cover\\\" | \\\"fill\\\" | \\\"scale-down\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"wrap\\\" | \\\"nowrap\\\" | \\\"wrap-reverse\\\"\",\"\\\"12h\\\" | \\\"24h\\\"\",\"\\\"activity\\\" | \\\"display-none\\\"\",\"\\\"all\\\" | \\\"parent\\\" | \\\"child\\\"\",\"\\\"all\\\" | \\\"segment\\\"\",\"\\\"always\\\" | \\\"hover\\\" | \\\"not-hover\\\" | \\\"never\\\"\",\"\\\"area\\\" | \\\"radial\\\" | \\\"scatter\\\"\",\"\\\"auto\\\" | \\\"scroll\\\" | \\\"always\\\" | \\\"hover\\\" | \\\"never\\\"\",\"\\\"auto-fit\\\" | \\\"auto-fill\\\"\",\"\\\"block\\\" | \\\"grid\\\"\",\"\\\"both\\\" | \\\"rightSection\\\" | \\\"clear\\\"\",\"\\\"bottom\\\" | \\\"top\\\"\",\"\\\"bottom\\\" | \\\"top\\\" | \\\"baseline\\\" | \\\"middle\\\"\",\"\\\"bottom\\\" | \\\"top\\\" | \\\"middle\\\"\",\"\\\"bottom-end\\\" | \\\"bottom-start\\\" | \\\"top-end\\\" | \\\"top-start\\\" | \\\"bottom-center\\\" | \\\"top-center\\\" | \\\"middle-center\\\" | \\\"middle-end\\\" | \\\"middle-start\\\"\",\"\\\"button\\\" | \\\"submit\\\" | \\\"reset\\\"\",\"\\\"center\\\" | \\\"bottom\\\"\",\"\\\"center\\\" | \\\"left\\\" | \\\"right\\\"\",\"\\\"center\\\" | \\\"left\\\" | \\\"right\\\" | \\\"justify\\\" | \\\"char\\\"\",\"\\\"center\\\" | \\\"side\\\" | \\\"merge\\\"\",\"\\\"checkbox\\\" | \\\"radio\\\"\",\"\\\"dashed\\\" | \\\"dotted\\\" | \\\"solid\\\"\",\"\\\"default\\\" | \\\"gradient\\\"\",\"\\\"default\\\" | \\\"responsive\\\"\",\"\\\"default\\\" | \\\"stacked\\\" | \\\"percent\\\" | \\\"split\\\"\",\"\\\"default\\\" | \\\"stacked\\\" | \\\"percent\\\" | \\\"waterfall\\\"\",\"\\\"div\\\" | \\\"label\\\"\",\"\\\"end\\\" | \\\"start\\\"\",\"\\\"filled\\\" | \\\"light\\\"\",\"\\\"fixed\\\" | \\\"absolute\\\"\",\"\\\"hex\\\" | \\\"hexa\\\" | \\\"rgba\\\" | \\\"rgb\\\" | \\\"hsl\\\" | \\\"hsla\\\"\",\"\\\"horizontal\\\" | \\\"vertical\\\"\",\"\\\"hover\\\" | \\\"click\\\" | \\\"click-hover\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"baseline\\\" | \\\"before-edge\\\" | \\\"text-before-edge\\\" | \\\"middle\\\" | \\\"central\\\" | \\\"after-edge\\\" | \\\"text-after-edge\\\" | \\\"ideographic\\\" | \\\"alphabetic\\\" | \\\"hanging\\\" | \\\"mathematical\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"sRGB\\\" | \\\"linearRGB\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"text-before-edge\\\" | \\\"middle\\\" | \\\"central\\\" | \\\"text-after-edge\\\" | \\\"ideographic\\\" | \\\"alphabetic\\\" | \\\"hanging\\\" | \\\"mathematical\\\" | \\\"use-script\\\" | \\\"no-change\\\" | \\\"reset-size\\\"\",\"\\\"inherit\\\" | \\\"end\\\" | \\\"start\\\" | \\\"middle\\\"\",\"\\\"inherit\\\" | \\\"nonzero\\\" | \\\"evenodd\\\"\",\"\\\"inherit\\\" | \\\"round\\\" | \\\"butt\\\" | \\\"square\\\"\",\"\\\"inherit\\\" | \\\"round\\\" | \\\"miter\\\" | \\\"bevel\\\"\",\"\\\"initial\\\" | \\\"medial\\\" | \\\"terminal\\\" | \\\"isolated\\\"\",\"\\\"inside\\\" | \\\"outside\\\"\",\"\\\"left\\\" | \\\"right\\\"\",\"\\\"left\\\" | \\\"right\\\" | \\\"bottom\\\" | \\\"top\\\" | \\\"left-end\\\" | \\\"left-start\\\" | \\\"right-end\\\" | \\\"right-start\\\" | \\\"bottom-end\\\" | \\\"bottom-start\\\" | \\\"top-end\\\" | \\\"top-start\\\"\",\"\\\"left\\\" | \\\"right\\\" | \\\"inside\\\"\",\"\\\"link\\\" | \\\"none\\\" | \\\"copy\\\" | \\\"execute\\\" | \\\"move\\\" | \\\"popup\\\"\",\"\\\"media\\\" | \\\"container\\\"\",\"\\\"month\\\" | \\\"year\\\" | \\\"decade\\\"\",\"\\\"native\\\" | \\\"scrollarea\\\"\",\"\\\"none\\\" | \\\"all\\\" | \\\"rows\\\" | \\\"groups\\\" | \\\"columns\\\"\",\"\\\"none\\\" | \\\"all\\\" | \\\"with-indicators\\\"\",\"\\\"none\\\" | \\\"ascending\\\" | \\\"descending\\\" | \\\"other\\\"\",\"\\\"none\\\" | \\\"inline\\\" | \\\"list\\\" | \\\"both\\\"\",\"\\\"none\\\" | \\\"strict\\\" | \\\"blur\\\"\",\"\\\"none\\\" | \\\"sum\\\"\",\"\\\"none\\\" | \\\"thousand\\\" | \\\"lakh\\\" | \\\"wan\\\"\",\"\\\"none\\\" | \\\"x\\\" | \\\"y\\\" | \\\"xy\\\"\",\"\\\"number\\\" | RegExp | \\\"alphanumeriLine truncated
|
||||
},
|
||||
{
|
||||
"path": "references/examples.json",
|
||||
"content": "[\n {\n \"id\": \"service-status\",\n \"title\": \"Service status\",\n \"description\": \"A compact status widget backed by one load query.\",\n \"widget\": {\n \"$schema\": \"homarr-custom-widget-v2\",\n \"name\": \"Service status\",\n \"sources\": [\n {\n \"id\": \"default\",\n \"name\": \"Service API\",\n \"baseUrl\": \"https://example.com\",\n \"networkScope\": \"public\",\n \"auth\": {\n \"type\": \"none\"\n }\n }\n ],\n \"requests\": [\n {\n \"id\": \"status\",\n \"sourceId\": \"default\",\n \"kind\": \"query\",\n \"method\": \"GET\",\n \"pathTemplate\": \"/api/status\",\n \"parameters\": {},\n \"auth\": \"inherit\",\n \"minimumBoardPermission\": \"view\",\n \"trigger\": \"load\"\n }\n ],\n \"optionsSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"defaultOptions\": {},\n \"template\": \"<Stack gap=\\\"xs\\\" p=\\\"sm\\\">\\n <Group justify=\\\"space-between\\\">\\n <Text fw={600}>{data.status.name ?? \\\"Service\\\"}</Text>\\n <Badge color={data.status.online ? \\\"green\\\" : \\\"red\\\"}>{data.status.online ? \\\"Online\\\" : \\\"Offline\\\"}</Badge>\\n </Group>\\n <Text size=\\\"sm\\\" c=\\\"dimmed\\\">{data.status.message ?? \\\"No additional details\\\"}</Text>\\n </Stack>\"\n }\n },\n {\n \"id\": \"pokemon-evolution-tree\",\n \"title\": \"Pokémon evolution tree\",\n \"description\": \"A trusted arbitrary-depth tree with one immutable derived-value block per node.\",\n \"widget\": {\n \"$schema\": \"homarr-custom-widget-v2\",\n \"name\": \"Pokémon evolution tree\",\n \"sources\": [\n {\n \"id\": \"default\",\n \"name\": \"PokeAPI\",\n \"baseUrl\": \"https://pokeapi.co\",\n \"networkScope\": \"public\",\n \"auth\": {\n \"type\": \"none\"\n }\n }\n ],\n \"requests\": [\n {\n \"id\": \"evolution\",\n \"sourceId\": \"default\",\n \"kind\": \"query\",\n \"method\": \"GET\",\n \"pathTemplate\": \"/api/v2/evolution-chain/1\",\n \"parameters\": {},\n \"auth\": \"inherit\",\n \"minimumBoardPermission\": \"view\",\n \"trigger\": \"load\"\n }\n ],\n \"optionsSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"defaultOptions\": {},\n \"template\": \"<Stack gap=\\\"sm\\\" p=\\\"sm\\\">\\n <Title order={3}>Evolution chain</Title>\\n {status.evolution?.loading ? <Skeleton height={160} radius=\\\"md\\\" /> : status.evolution?.error ? <Alert color=\\\"red\\\">{status.evolution.error}</Alert> : data.evolution?.chain ?\\n <RecursiveList data={data.evolution.chain} childrenPath=\\\"evolves_to\\\" keyPath=\\\"species.name\\\" defaultExpandedDepth={8} showLines>\\n {(node, meta) => {\\n const segments = node.species.url.split(\\\"/\\\").filter((part) => part);\\n const dexId = segments.at(-1);\\n return <Group gap=\\\"xs\\\"><Badge variant=\\\"light\\\">#{dexId}</Badge><Text tt=\\\"capitalize\\\" fw={600}>{node.species.name}</Text>{meta.hasChildren && <Text size=\\\"xs\\\" c=\\\"dimmed\\\">{meta.childCount} next</Text>}</Group>;\\n }}\\n </RecursiveList> : <Text c=\\\"dimmed\\\">No evolution chain returned.</Text>}\\n</Stack>\"\n }\n }\n]\n"
|
||||
},
|
||||
{
|
||||
"path": "references/mantine-core.md",
|
||||
"content": "# Mantine UI - LLM Documentation\n\nThis index lists Mantine documentation pages formatted for LLMs.\nEach link points to a standalone Markdown file under the /llms path.\n\nFor a single consolidated file with all content, use:\n- https://mantine.dev/llms-full.txt\n\n## FAQ\n\n- [Are Mantine components accessible?](https://mantine.dev/llms/q-are-mantine-components-accessible.md): Learn about Mantine components accessibility features\n- [Browser zooms in when input is focused. What should I do?](https://mantine.dev/llms/q-browser-zooms-on-focus.md): Use meta tag to disable browser scaling or increase input size\n- [Can I have color schemes other than light and dark?](https://mantine.dev/llms/q-light-dark-is-not-enough.md): Learn about the difference between color scheme and theme\n- [Can I have different primary color for light and dark color schemes?](https://mantine.dev/llms/q-primary-virtual-color.md): Learn how to use virtual color with primary color in theme object\n- [Can I remove MultiSelect placeholder when the component has selected values?](https://mantine.dev/llms/q-multiselect-value-placeholder.md): Learn why MultiSelect placeholder is not removed when values are selected and how to remove it with CSS\n- [Can I use an array of strings as a list in use-form?](https://mantine.dev/llms/q-list-of-strings-in-use-form.md): Learn about use-form lists limitations\n- [Can I use Mantine components as server components?](https://mantine.dev/llms/q-server-components.md): Learn about use client directive and server components usage\n- [Can I use Mantine with Astro?](https://mantine.dev/llms/q-can-i-use-mantine-with-astro.md): No, Astro does not support React context\n- [Can I use Mantine with Create React App (CRA)?](https://mantine.dev/llms/q-can-i-use-mantine-with-cra.md): Learn how to use Mantine without postcss-preset-mantine or how to eject CRA and customize webpack.config.js and use postcss-preset-mantine\n- [Can I use Mantine with Emotion/styled-components/tailwindcss?](https://mantine.dev/llms/q-third-party-styles.md): Learn about limitations of third-party styles\n- [Can I use Mantine with Vue/Svelte/Angular/etc.?](https://mantine.dev/llms/q-vue-svelte-angular.md): No, Mantine is a React library and does not support other frameworks/libraries\n- [Can I use nested inline styles with Mantine components?](https://mantine.dev/llms/q-nested-inline-styles.md): Nested styles are supported only in CSS files\n- [Can I use PostCSS function in inline styles?](https://mantine.dev/llms/q-postcss-fns-inline.md): Learn where PostCSS functions can be used in Mantine\n- [Can I use private CSS variables to style components?](https://mantine.dev/llms/q-private-css-variables.md): No, it is not safe and will not work with future versions of Mantine.\n- [Can I use SegmentedControl with empty value?](https://mantine.dev/llms/q-segmented-control-no-value.md): SegmentedControl cannot be used without a value\n- [How can I add dynamic CSS styles?](https://mantine.dev/llms/q-dynamic-css-styles.md): Use data attributes, CSS variables or inline styles\n- [How can I add fuzzy search to Select component?](https://mantine.dev/llms/q-select-fuzzy.md): Learn how to integrate third-party fuzzy search libraries with Mantine Select component\n- [How can I add hover styles to an element?](https://mantine.dev/llms/q-how-to-add-hover-styles.md): Learn how to add hover classes to an element with CSS modules, &:hover or @mixin hover\n- [How can I apply styles to all Mantine components?](https://mantine.dev/llms/q-apply-styles-to-all.md): Learn how to use attribute selector to apply styles to all Mantine components\n- [How can I change body background color?](https://mantine.dev/llms/q-body-background.md): Use CSS to change body background color\n- [How can I change component color prop value depending on the color scheme?](https://mantine.dev/llms/q-color-scheme-color.md): Learn how to use CSS variables resolver to change color value depending on the color scheme\n- [How can I change input focus styles?](https://mantine.dev/llms/q-input-focus-styles.md): Learn how to use Styles API with Mantine inputs\n- [How can I change Tabs border color?](https://mantine.dev/llms/q-tabs-border-color.md): Learn how to use Styles API with Tabs component\n- [How can I contribute to the library?](https://mantine.dev/llms/q-how-can-i-contribute.md): There are multiple ways to contribute even without writing code\n- [How can I disable all inputs/input groups inside a form?](https://mantine.dev/llms/q-disable-all-inputs-in-form.md): Learn how to disable all inputs/input groups inside a form with the unstyled Fieldset component\n- [How can I display different elements in light and dark color schemes?](https://mantine.dev/llms/q-light-dark-elements.md): Learn how to hide/show elements based on color scheme\n- [How can I focus the first input with error with use-form?](https://mantine.dev/llms/q-focus-first-input-with-error.md): Learn how to handlLine truncated
|
||||
},
|
||||
{
|
||||
"path": "references/mantine-dates.md",
|
||||
"content": "# GettingStartedDates\nPackage: @mantine/dates\nImport: import { GettingStartedDates } from '@mantine/dates';\n\n## Installation\n\n```bash\nyarn add @mantine/dates dayjs\n```\n\n```bash\nnpm install @mantine/dates dayjs\n```\n\nAfter installation import package styles at the root of your application:\n\n```tsx\nimport '@mantine/core/styles.css';\n// ‼️ import dates styles after core package styles\nimport '@mantine/dates/styles.css';\n```\n\n## Do not forget to import styles\n\nFollowed the installation instructions above but something is not working\n(calendars and date pickers have no styles and look broken)?\nYou've fallen into the trap of not importing dates styles!\nTo fix this issue, import dates styles at the root of your application:\n\n```tsx\nimport '@mantine/dates/styles.css';\n```\n\n## Usage\n\nAfter installing the `@mantine/dates` package and importing styles, you can use all components from it:\n\n\n\n## Date values as strings\n\n`@mantine/dates` components work with date strings: `YYYY-MM-DD` or `YYYY-MM-DD HH:mm:ss` depending on the component. Those strings do not include any timezone-specific information.\n\n## dayjs\n\n`@mantine/dates` components use [dayjs](https://day.js.org/) under the hood for date manipulations and formatting.\ndayjs is a required dependency – you cannot change it to another date library. If you want to use a different\ndate library in your application, you will need to install it separately.\n\n## DatesProvider\n\nThe `DatesProvider` component lets you set various settings that are shared across all\ncomponents exported from the `@mantine/dates` package. `DatesProvider` supports the following settings:\n\n* `locale` – dayjs locale. Note that you also need to import the corresponding locale module from dayjs. The default value is `en`.\n* `firstDayOfWeek` – a number from 0 to 6, where 0 is Sunday and 6 is Saturday. The default value is 1 – Monday.\n* `weekendDays` – an array of numbers from 0 to 6, where 0 is Sunday and 6 is Saturday. The default value is `[0, 6]` – Saturday and Sunday.\n* `consistentWeeks` – boolean. If `true`, every month will have 6 weeks. The default value is `false`.\n\n```tsx\nimport 'dayjs/locale/ru';\nimport { DatesProvider, MonthPickerInput, DatePickerInput } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru', firstDayOfWeek: 0, weekendDays: [0] }}>\n <MonthPickerInput label=\"Pick month\" placeholder=\"Pick month\" />\n <DatePickerInput mt=\"md\" label=\"Pick date\" placeholder=\"Pick date\" />\n </DatesProvider>\n );\n}\n```\n\n\n## Consistent weeks\n\nIf you want to avoid layout shifts, set `consistentWeeks: true` in the `DatesProvider` settings.\nThis will ensure that every month has 6 weeks, even if outside days are not in the same month.\n\n```tsx\nimport { DatePicker, DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ consistentWeeks: true }}>\n <DatePicker />\n </DatesProvider>\n );\n}\n```\n\n\n## Custom parse format\n\nSome components like [DateInput](https://mantine.dev/llms/dates-date-input.md) require the [custom parse format](https://day.js.org/docs/en/plugin/custom-parse-format)\ndayjs plugin. You need to extend dayjs with this plugin before using components that require it. Note that\nthis is usually done once in your application root file, so you don't need to do it every time you use the component.\n\n```tsx\nimport dayjs from 'dayjs';\nimport customParseFormat from 'dayjs/plugin/customParseFormat';\n\ndayjs.extend(customParseFormat);\n```\n\n## Localization and server components\n\nTo add localization, you must import `import 'dayjs/locale/x';` in your application (`x` is the locale name)\nand set `locale` either on `DatesProvider` or on each component individually.\n\nExample of setting the locale on DatesProvider:\n\n```tsx\nimport 'dayjs/locale/ru';\n\nimport { DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru' }}>\n {/* Your app */}\n </DatesProvider>\n );\n}\n```\n\nThe code above works in all environments, except Next.js app router.\nIf you are using Next.js app router, you must add `'use client';` to the\ntop of the file where you are importing `dayjs/locale/x` – locale data\nis required both on client and server.\n\n```tsx\n'use client';\n\nimport 'dayjs/locale/ru';\n\nimport { DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru' }}>\n {/* Your app */}\n </DatesProvider>\n );\n}\n```\n"
|
||||
},
|
||||
{
|
||||
"path": "references/mantine-charts.md",
|
||||
"content": "# Mantine Charts\n\nUse the official Mantine LLM index in [Mantine Core](mantine-core.md#charts) to discover chart documentation.\n\nThe upstream source is https://mantine.dev/llms.txt. Follow its `## Charts` links for current component documentation. Homarr's live component catalog remains authoritative for the installed component names and blocked capabilities.\n"
|
||||
},
|
||||
{
|
||||
"path": "references/homarr-components.md",
|
||||
"content": "# Homarr components\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@homarr/widgets`. The component-specific props below supplement ordinary safe serializable Mantine props and style props. Component-specific records override ordinary behavior with the same name.\n\n## Package guidance\n\nHomarr components own controlled request, action, pagination, disclosure, icon, and recursive traversal behavior. Manual request parameters come from the invoking component's `params` prop. `RecursiveList` is the only supported arbitrary-depth authored renderer and its child template may use the restricted safe-block grammar.\n\n## Enabled inventory\n\n<code>ActionButton</code>, <code>Collapsible</code>, <code>PaginatedList</code>, <code>RecursiveList</code>, <code>RefreshButton</code>, <code>StatBar</code>, <code>SubData</code>, <code>SubFetch</code>, <code>TabPanel</code>, <code>TablerIcon</code>, <code>TabsContainer</code>, <code>ToggleSwitch</code>, <code>TypeBadge</code>\n\n## Denied inventory\n\n_None._\n\n## Component records\n\n<a id=\"component-actionbutton\"></a>\n### `ActionButton`\n\n- Safety: `wrapped`\n- Category: `network`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Action labels must describe their effect; destructive actions require confirmation.\n\nRuns a named user-triggered action.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>color</code> | no | <code>string</code> | — | — |\n| <code>confirmMessage</code> | no | <code>string</code> | — | — |\n| <code>disabled</code> | no | <code>boolean | string</code> | — | — |\n| <code>errorMessage</code> | no | <code>string</code> | — | — |\n| <code>fullWidth</code> | no | <code>boolean | string</code> | — | — |\n| <code>icon</code> | no | <code>string</code> | — | — |\n| <code>label</code> | no | <code>string</code> | — | — |\n| <code>params</code> | no | <code>Record<string, string | number | boolean></code> | — | — |\n| <code>requestId</code> | no | <code>string</code> | — | Identifier of the named Custom Widget action. |\n| <code>size</code> | no | <code>string</code> | — | — |\n| <code>successMessage</code> | no | <code>string</code> | — | — |\n| <code>variant</code> | no | <code>string</code> | — | — |\n\n<a id=\"component-collapsible\"></a>\n### `Collapsible`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nShows and hides a bounded content section.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>defaultOpen</code> | no | <code>boolean</code> | — | — |\n| <code>title</code> | yes | <code>string</code> | — | — |\n\n<a id=\"component-paginatedlist\"></a>\n### `PaginatedList`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nRenders a bounded page of collection items.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>pageSize</code> | no | <code>number</code> | — | — |\n\n<a id=\"component-recursivelist\"></a>\n### `RecursiveList`\n\n- Safety: `wrapped`\n- Category: `content`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide meaningful text alternatives for non-text content.\n\nRenders an arbitrary-depth tree through a bounded, Homarr-owned traversal.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>childrenPath</code> | yes | <code>string</code> | — | — |\n| <code>data</code> | yes | <code>unknown</code> | — | — |\n| <code>defaultExpandedDepth</code> | no | <code>number</code> | — | — |\n| <code>gap</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>indent</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>keyPath</code> | yes | <code>string</code> | — | — |\n| <code>maxDepth</code> | no | <code>number</code> | — | — |\nLine truncated
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export const customJsxTablerIconNames = [
|
||||
"bluetooth",
|
||||
"bolt",
|
||||
"bookmark",
|
||||
"brand-docker",
|
||||
"bug",
|
||||
"calendar",
|
||||
"camera",
|
||||
@@ -72,6 +73,7 @@ export const customJsxTablerIconNames = [
|
||||
"player-skip-forward",
|
||||
"player-stop",
|
||||
"plus",
|
||||
"pokeball",
|
||||
"power",
|
||||
"progress",
|
||||
"pulse",
|
||||
|
||||
@@ -6,22 +6,13 @@ export interface CustomJsxTemplateDiagnostic {
|
||||
column: number;
|
||||
}
|
||||
|
||||
export function createCustomJsxParseDiagnostic(template: string, error: unknown): CustomJsxTemplateDiagnostic {
|
||||
export function createCustomJsxParseDiagnostic(_template: string, error: unknown): CustomJsxTemplateDiagnostic {
|
||||
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
|
||||
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
|
||||
const missingInitializer = [...template.matchAll(/(?:\bconst|,)\s+([A-Za-z_$][\w$]*)\s*;/gu)].find((match) => {
|
||||
const semicolon = (match.index ?? 0) + match[0].length - 1;
|
||||
return Math.abs(semicolon - parseIndex) <= 1;
|
||||
});
|
||||
const duplicateBinding = /Identifier '([^']+)' has already been declared/iu.exec(parseError.message);
|
||||
const duplicateArgument = /Argument name clash/iu.test(parseError.message);
|
||||
const message = missingInitializer
|
||||
? `LOCAL_BINDING_REQUIRES_INITIALIZER: '${missingInitializer[1]}' requires an initializer`
|
||||
: duplicateBinding
|
||||
? `DUPLICATE_LOCAL_BINDING: '${duplicateBinding[1]}' is already declared`
|
||||
: duplicateArgument
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: parseError.message;
|
||||
const message = duplicateArgument
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: parseError.message;
|
||||
|
||||
return {
|
||||
severity: "error",
|
||||
|
||||
@@ -2,15 +2,11 @@ import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
resolveCustomJsxComponentName,
|
||||
} from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf } from "./analyzer-ast";
|
||||
import {
|
||||
closestCustomJsxComponentName,
|
||||
customJsxTagName,
|
||||
isRestrictedRecursiveListPath,
|
||||
isSafeLiteralCustomJsxUrl,
|
||||
} from "./analyzer-language";
|
||||
import { closestCustomJsxComponentName, customJsxTagName, isSafeLiteralCustomJsxUrl } from "./analyzer-language";
|
||||
import { CUSTOM_JSX_URL_PROPS, isBlockedCustomJsxProp } from "./policy";
|
||||
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
|
||||
|
||||
@@ -33,7 +29,8 @@ export function analyzeCustomJsxElement(
|
||||
}
|
||||
const nameNode = nodeOf(opening.name);
|
||||
const name = nameNode ? customJsxTagName(nameNode) : null;
|
||||
const descriptor = name ? customJsxComponentByName.get(name) : undefined;
|
||||
const resolvedName = name ? resolveCustomJsxComponentName(name) : null;
|
||||
const descriptor = resolvedName ? customJsxComponentByName.get(resolvedName) : undefined;
|
||||
if (descriptor?.safety === "denied") {
|
||||
context.add(
|
||||
opening,
|
||||
@@ -49,11 +46,8 @@ export function analyzeCustomJsxElement(
|
||||
);
|
||||
}
|
||||
|
||||
const attributeNames = new Set<string>();
|
||||
let hasAttributeSpread = false;
|
||||
for (const attribute of nodesOf(opening.attributes)) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
hasAttributeSpread = true;
|
||||
const argument = nodeOf(attribute.argument);
|
||||
if (argument) context.visit(argument, depth + 1, bindings);
|
||||
continue;
|
||||
@@ -64,7 +58,6 @@ export function analyzeCustomJsxElement(
|
||||
}
|
||||
const attributeNameNode = nodeOf(attribute.name);
|
||||
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
|
||||
attributeNames.add(attributeName);
|
||||
const componentBlockedProp = descriptor?.blockedProps.find(({ name: propName }) => propName === attributeName);
|
||||
if (componentBlockedProp) {
|
||||
context.add(
|
||||
@@ -73,22 +66,23 @@ export function analyzeCustomJsxElement(
|
||||
);
|
||||
} else if (isBlockedCustomJsxProp(attributeName)) {
|
||||
context.add(attribute, `BLOCKED_CAPABILITY: Prop '${attributeName}' is not allowed`);
|
||||
} else if (name && attributeName !== "bind" && !customJsxSupportedPropsByName.get(name)?.has(attributeName)) {
|
||||
} else if (
|
||||
resolvedName &&
|
||||
attributeName !== "bind" &&
|
||||
!customJsxSupportedPropsByName.get(resolvedName)?.has(attributeName)
|
||||
) {
|
||||
context.add(attribute, `UNKNOWN_MANTINE_PROP: '${attributeName}' on ${name} will be passed through`, "warning");
|
||||
} else if (name && attributeName === "bind" && !customJsxBindableComponentNames.has(name)) {
|
||||
} else if (resolvedName && attributeName === "bind" && !customJsxBindableComponentNames.has(resolvedName)) {
|
||||
context.add(attribute, `BINDING_UNAVAILABLE: '${name}' does not have a declarative binding adapter`, "warning");
|
||||
}
|
||||
analyzeAttributeValue(name, attributeName, attribute, depth, bindings, context);
|
||||
analyzeAttributeValue(resolvedName, attributeName, attribute, depth, bindings, context);
|
||||
}
|
||||
|
||||
if (name === "RecursiveList") analyzeRecursiveList(node, opening, attributeNames, hasAttributeSpread, context);
|
||||
nodesOf(node.children).forEach((child) => {
|
||||
if (name === "RecursiveList" && child.type === "JSXExpressionContainer") {
|
||||
const expression = nodeOf(child.expression);
|
||||
if (expression?.type === "ArrowFunctionExpression") {
|
||||
context.visitArrow(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
const expression = child.type === "JSXExpressionContainer" ? nodeOf(child.expression) : null;
|
||||
if (resolvedName === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
context.visitArrow(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
context.visit(child, depth + 1, bindings);
|
||||
});
|
||||
@@ -109,32 +103,6 @@ function analyzeAttributeValue(
|
||||
: value?.type === "JSXExpressionContainer" && nodeOf(value.expression)?.type === "Literal"
|
||||
? nodeOf(value.expression)
|
||||
: null;
|
||||
if (componentName === "RecursiveList" && literalValue?.type === "Literal") {
|
||||
if (
|
||||
["childrenPath", "keyPath"].includes(attributeName) &&
|
||||
(typeof literalValue.value !== "string" || !isRestrictedRecursiveListPath(literalValue.value))
|
||||
) {
|
||||
context.add(attribute, `INVALID_PROP_VALUE: '${attributeName}' must be a safe dotted property path`);
|
||||
}
|
||||
if (
|
||||
attributeName === "maxDepth" &&
|
||||
(typeof literalValue.value !== "number" ||
|
||||
!Number.isInteger(literalValue.value) ||
|
||||
literalValue.value < 1 ||
|
||||
literalValue.value > 32)
|
||||
) {
|
||||
context.add(attribute, "INVALID_PROP_VALUE: 'maxDepth' must be between 1 and 32");
|
||||
}
|
||||
if (
|
||||
attributeName === "maxNodes" &&
|
||||
(typeof literalValue.value !== "number" ||
|
||||
!Number.isInteger(literalValue.value) ||
|
||||
literalValue.value < 1 ||
|
||||
literalValue.value > 2_000)
|
||||
) {
|
||||
context.add(attribute, "INVALID_PROP_VALUE: 'maxNodes' must be between 1 and 2000");
|
||||
}
|
||||
}
|
||||
if (componentName && literalValue?.type === "Literal") {
|
||||
const reason = getInvalidCustomJsxPropValueReason(componentName, attributeName, literalValue.value);
|
||||
if (reason) context.add(attribute, `INVALID_PROP_VALUE: ${reason}`);
|
||||
@@ -155,35 +123,3 @@ function analyzeAttributeValue(
|
||||
context.visit(expression, depth + 1, bindings);
|
||||
}
|
||||
}
|
||||
|
||||
function analyzeRecursiveList(
|
||||
node: AstNode,
|
||||
opening: AstNode,
|
||||
attributeNames: ReadonlySet<string>,
|
||||
hasAttributeSpread: boolean,
|
||||
context: AnalyzerJsxContext,
|
||||
): void {
|
||||
for (const requiredProp of ["data", "childrenPath", "keyPath"]) {
|
||||
if (!hasAttributeSpread && !attributeNames.has(requiredProp)) {
|
||||
context.add(opening, `INVALID_PROP_VALUE: RecursiveList requires '${requiredProp}'`);
|
||||
}
|
||||
}
|
||||
const meaningfulChildren = nodesOf(node.children).filter(
|
||||
(child) => child.type !== "JSXText" || String(child.value ?? "").trim().length > 0,
|
||||
);
|
||||
const templateExpression =
|
||||
meaningfulChildren.length === 1 && meaningfulChildren[0]?.type === "JSXExpressionContainer"
|
||||
? nodeOf(meaningfulChildren[0].expression)
|
||||
: null;
|
||||
if (templateExpression?.type !== "ArrowFunctionExpression") {
|
||||
context.add(node, "RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList requires exactly one inline arrow child");
|
||||
return;
|
||||
}
|
||||
const parameters = nodesOf(templateExpression.params);
|
||||
if (parameters.length === 0 || parameters.length > 2) {
|
||||
context.add(
|
||||
templateExpression,
|
||||
"RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child accepts node and optional metadata parameters",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { nodeOf, staticPropertyName } from "./analyzer-ast";
|
||||
import { CUSTOM_JSX_BLOCKED_PROPERTIES, normalizeCustomJsxProperty } from "./policy";
|
||||
|
||||
export const ROOT_BINDINGS = new Set([
|
||||
"Array",
|
||||
@@ -87,11 +86,6 @@ export function isSafeLiteralCustomJsxUrl(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRestrictedRecursiveListPath(value: string): boolean {
|
||||
if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u.test(value)) return false;
|
||||
return value.split(".").every((segment) => !CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(segment)));
|
||||
}
|
||||
|
||||
export function isStaticallyCallableBinding(node: AstNode): boolean {
|
||||
if (node.type === "Identifier") return callableRootBindings.has(String(node.name));
|
||||
if (node.type !== "MemberExpression") return false;
|
||||
|
||||
@@ -115,83 +115,13 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
}
|
||||
const body = nodeOf(node.body);
|
||||
if (!body) return;
|
||||
if (body.type === "BlockStatement") visitSafeBlock(body, depth + 1, callbackBindings);
|
||||
if (body.type === "BlockStatement")
|
||||
add(body, "UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
else if (canStaticallyProduceCallable(body)) {
|
||||
add(body, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
} else visit(body, depth + 1, callbackBindings);
|
||||
};
|
||||
|
||||
const visitSafeBlock = (block: AstNode, depth: number, bindings: ReadonlySet<string>) => {
|
||||
if (!checkBudget(block, depth)) return;
|
||||
const statements = nodesOf(block.body);
|
||||
const finalStatement = statements.at(-1);
|
||||
if (statements.length === 0 || finalStatement?.type !== "ReturnStatement" || !nodeOf(finalStatement.argument)) {
|
||||
add(block, "BLOCK_REQUIRES_FINAL_RETURN: A safe block must end with exactly one value-returning return");
|
||||
}
|
||||
if (statements.length < 2) {
|
||||
add(block, "INVALID_LOCAL_DECLARATION: A safe block requires at least one const before its final return");
|
||||
}
|
||||
|
||||
let scopedBindings = new Set(bindings);
|
||||
const localNames = new Set<string>();
|
||||
statements.forEach((statement, statementIndex) => {
|
||||
if (!checkBudget(statement, depth + 1)) return;
|
||||
const isFinal = statementIndex === statements.length - 1;
|
||||
if (statement.type === "ReturnStatement") {
|
||||
if (!isFinal) {
|
||||
add(statement, "BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
|
||||
return;
|
||||
}
|
||||
const argument = nodeOf(statement.argument);
|
||||
if (argument && canStaticallyProduceCallable(argument)) {
|
||||
add(argument, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
} else if (argument) visit(argument, depth + 1, scopedBindings);
|
||||
return;
|
||||
}
|
||||
if (statement.type !== "VariableDeclaration") {
|
||||
add(statement, `UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
|
||||
return;
|
||||
}
|
||||
if (statement.kind !== "const") {
|
||||
add(statement, "INVALID_LOCAL_DECLARATION: Only immutable const declarations are allowed");
|
||||
return;
|
||||
}
|
||||
for (const declaration of nodesOf(statement.declarations)) {
|
||||
if (!checkBudget(declaration, depth + 2)) continue;
|
||||
const identifier = nodeOf(declaration.id);
|
||||
if (declaration.type !== "VariableDeclarator" || identifier?.type !== "Identifier") {
|
||||
add(declaration, "INVALID_LOCAL_DECLARATION: Local declarations require a simple identifier");
|
||||
continue;
|
||||
}
|
||||
const name = String(identifier.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
add(identifier, `INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
|
||||
continue;
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
add(identifier, `RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
continue;
|
||||
}
|
||||
if (localNames.has(name)) {
|
||||
add(identifier, `DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
continue;
|
||||
}
|
||||
const initializer = nodeOf(declaration.init);
|
||||
if (!initializer) {
|
||||
add(declaration, `LOCAL_BINDING_REQUIRES_INITIALIZER: '${name}' requires an initializer`);
|
||||
continue;
|
||||
}
|
||||
if (canStaticallyProduceCallable(initializer)) {
|
||||
add(initializer, "CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
continue;
|
||||
}
|
||||
visit(initializer, depth + 1, scopedBindings);
|
||||
localNames.add(name);
|
||||
scopedBindings = new Set(scopedBindings).add(name);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
@@ -221,9 +151,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return;
|
||||
}
|
||||
case "Literal":
|
||||
if (node.regex !== undefined || typeof node.value === "bigint") {
|
||||
add(node, "Regular expressions and bigint literals are not supported");
|
||||
}
|
||||
if (typeof node.value === "bigint") add(node, "BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
if (node.regex !== undefined && !isSafeRegexLiteral(node.regex))
|
||||
add(node, "UNSAFE_REGEX: Use a bounded regex without lookbehind, backreferences, or nested quantifiers");
|
||||
return;
|
||||
case "Identifier": {
|
||||
const name = String(node.name ?? "");
|
||||
@@ -307,17 +237,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
add(node, "CALL_TARGET_NOT_ALLOWED: Optional calls are not supported");
|
||||
}
|
||||
if (callee?.type === "ArrowFunctionExpression") {
|
||||
if (nodesOf(callee.params).length > 0) {
|
||||
add(callee, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
|
||||
}
|
||||
if (arguments_.length > 0) {
|
||||
add(node, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments");
|
||||
}
|
||||
if (nodeOf(callee.body)?.type !== "BlockStatement") {
|
||||
add(callee, "BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block");
|
||||
}
|
||||
visitArrow(callee, depth + 1, bindings);
|
||||
arguments_.forEach((argument) => visit(argument, depth + 1, bindings));
|
||||
add(callee, "CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
return;
|
||||
}
|
||||
if (callee) visit(callee, depth + 1, bindings);
|
||||
@@ -363,7 +283,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return;
|
||||
}
|
||||
case "BlockStatement":
|
||||
add(node, "UNSUPPORTED_BLOCK_STATEMENT: Blocks are only allowed as safe callback or IIFE bodies");
|
||||
add(node, "UNSUPPORTED_BLOCK_STATEMENT: Authored callbacks must use one expression");
|
||||
return;
|
||||
case "AssignmentExpression":
|
||||
case "UpdateExpression":
|
||||
@@ -398,3 +318,11 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function isSafeRegexLiteral(regex: unknown): boolean {
|
||||
if (!regex || typeof regex !== "object") return false;
|
||||
const { pattern, flags } = regex as { pattern?: unknown; flags?: unknown };
|
||||
if (typeof pattern !== "string" || pattern.length > 128 || typeof flags !== "string" || /[^gimsu]/u.test(flags))
|
||||
return false;
|
||||
return !/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(pattern);
|
||||
}
|
||||
@@ -1,28 +1,28 @@
|
||||
import { isSafeCallable } from "./safe-bindings";
|
||||
import { isInterpreterCallback, normalizedSliceIndex, numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
interface CollectionMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
import type { InterpreterCallback } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
import { callStringMethod } from "./string-methods";
|
||||
|
||||
export function callCollectionMethod(
|
||||
receiver: unknown,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
depth: number,
|
||||
context: CollectionMethodContext,
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
if (Array.isArray(receiver)) {
|
||||
if (method === "map" || method === "filter") {
|
||||
if (method === "map" || method === "filter" || method === "flatMap") {
|
||||
const callback = args[0];
|
||||
if (isSafeCallable(callback)) {
|
||||
const result: unknown[] = [];
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = callback(receiver[index] as never);
|
||||
if (method === "map") result.push(callbackResult);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap") result.push(callbackResult);
|
||||
else if (callbackResult) result.push(receiver[index]);
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
@@ -32,7 +32,25 @@ export function callCollectionMethod(
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = context.runCallback(callback, [receiver[index], index, receiver], depth + 1);
|
||||
if (method === "map" || callbackResult) result.push(method === "map" ? callbackResult : receiver[index]);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap" || callbackResult) {
|
||||
result.push(method === "map" || method === "flatMap" ? callbackResult : receiver[index]);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "concat") {
|
||||
const result = [...receiver];
|
||||
for (const value of args) {
|
||||
if (Array.isArray(value)) {
|
||||
context.budget.collection(value.length);
|
||||
result.push(...value);
|
||||
} else {
|
||||
context.budget.collection();
|
||||
result.push(value);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
@@ -155,98 +173,11 @@ export function callCollectionMethod(
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof receiver === "string") {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
let maxCount = 0;
|
||||
if (receiver.length > 0) maxCount = Math.floor(200_001 / receiver.length);
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const split = args[0] === undefined ? [receiver] : receiver.split(String(args[0]), limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
}
|
||||
if (typeof receiver === "string") return callStringMethod(receiver, method, args, context);
|
||||
|
||||
if (receiver instanceof RegExp && method === "test") {
|
||||
const value = String(args[0] ?? "");
|
||||
return { handled: true, value: receiver.test(value) };
|
||||
}
|
||||
|
||||
if (typeof receiver === "number") {
|
||||
@@ -258,6 +189,9 @@ export function callCollectionMethod(
|
||||
const precision = Math.max(1, Math.min(21, numericArgument(args[0], 1)));
|
||||
return { handled: true, value: receiver.toPrecision(precision) };
|
||||
}
|
||||
if (method === "toLocaleString") {
|
||||
return { handled: true, value: context.budget.string(receiver.toLocaleString()) };
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -4,6 +4,5 @@ export * from "./policy";
|
||||
export * from "./safe-bindings";
|
||||
export * from "./bindings";
|
||||
export * from "./runtime-components";
|
||||
export * from "./recursive-list";
|
||||
export * from "./interactive-components";
|
||||
export { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
asNode,
|
||||
asNodeArray,
|
||||
Environment,
|
||||
INTERPRETER_CALLBACK,
|
||||
isInterpreterCallback,
|
||||
SafeJsxError,
|
||||
} from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, Environment, INTERPRETER_CALLBACK, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { RESERVED_LOCAL_BINDINGS } from "./analyzer-language";
|
||||
import { isBlockedCustomJsxLexicalBinding } from "./policy";
|
||||
@@ -16,33 +9,23 @@ interface InterpreterCallbackContext {
|
||||
}
|
||||
|
||||
export function createInterpreterCallback(node: AstNode, environment: Environment): InterpreterCallback {
|
||||
if (node.async || node.generator) {
|
||||
if (node.async || node.generator)
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Async and generator callbacks are not supported");
|
||||
}
|
||||
const parameterNames = new Set<string>();
|
||||
const params = asNodeArray(node.params, "callback parameters").map((param) => {
|
||||
if (param.type !== "Identifier") {
|
||||
if (param.type !== "Identifier")
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Callback parameters must be identifiers");
|
||||
}
|
||||
const name = String(param.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
if (isBlockedCustomJsxLexicalBinding(name) || RESERVED_LOCAL_BINDINGS.has(name))
|
||||
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe callback parameter name`);
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
}
|
||||
if (parameterNames.has(name)) {
|
||||
throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
}
|
||||
if (parameterNames.has(name)) throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
parameterNames.add(name);
|
||||
return name;
|
||||
});
|
||||
return {
|
||||
kind: INTERPRETER_CALLBACK,
|
||||
params,
|
||||
body: asNode(node.body, "callback body"),
|
||||
environment,
|
||||
};
|
||||
const body = asNode(node.body, "callback body");
|
||||
if (body.type === "BlockStatement")
|
||||
throw new SafeJsxError("UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
return { kind: INTERPRETER_CALLBACK, params, body, environment };
|
||||
}
|
||||
|
||||
export function runInterpreterCallback(
|
||||
@@ -51,93 +34,17 @@ export function runInterpreterCallback(
|
||||
depth: number,
|
||||
context: InterpreterCallbackContext,
|
||||
): unknown {
|
||||
context.budget.operation(depth);
|
||||
const values: Record<string, unknown> = Object.create(null);
|
||||
callback.params.forEach((name, index) => {
|
||||
values[name] = args[index];
|
||||
});
|
||||
const environment = new Environment(values, callback.environment);
|
||||
const result =
|
||||
callback.body.type === "BlockStatement"
|
||||
? executeSafeBlock(callback.body, environment, depth + 1, context)
|
||||
: context.evaluate(callback.body, environment, depth + 1);
|
||||
return ensureNonCallableResult(result);
|
||||
}
|
||||
|
||||
function executeSafeBlock(
|
||||
block: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
context: InterpreterCallbackContext,
|
||||
): unknown {
|
||||
context.budget.operation(depth);
|
||||
const statements = asNodeArray(block.body, "safe block statements");
|
||||
const finalStatement = statements.at(-1);
|
||||
if (statements.length === 0 || finalStatement?.type !== "ReturnStatement" || !finalStatement.argument) {
|
||||
throw new SafeJsxError(
|
||||
"BLOCK_REQUIRES_FINAL_RETURN: A safe block must end with exactly one value-returning return",
|
||||
);
|
||||
}
|
||||
if (statements.length < 2) {
|
||||
throw new SafeJsxError(
|
||||
"INVALID_LOCAL_DECLARATION: A safe block requires at least one const before its final return",
|
||||
);
|
||||
}
|
||||
|
||||
let scopedEnvironment = environment;
|
||||
const localNames = new Set<string>();
|
||||
for (let statementIndex = 0; statementIndex < statements.length; statementIndex += 1) {
|
||||
const statement = statements[statementIndex];
|
||||
if (!statement) continue;
|
||||
context.budget.operation(depth + 1);
|
||||
const isFinal = statementIndex === statements.length - 1;
|
||||
if (statement.type === "ReturnStatement") {
|
||||
if (!isFinal) {
|
||||
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
|
||||
}
|
||||
return ensureNonCallableResult(
|
||||
context.evaluate(asNode(statement.argument, "safe block return value"), scopedEnvironment, depth + 1),
|
||||
);
|
||||
}
|
||||
if (statement.type !== "VariableDeclaration") {
|
||||
throw new SafeJsxError(`UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
|
||||
}
|
||||
if (statement.kind !== "const") {
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Only immutable const declarations are allowed");
|
||||
}
|
||||
for (const declaration of asNodeArray(statement.declarations, "local declarations")) {
|
||||
context.budget.operation(depth + 2);
|
||||
const identifier = asNode(declaration.id, "local identifier");
|
||||
if (declaration.type !== "VariableDeclarator" || identifier.type !== "Identifier") {
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Local declarations require a simple identifier");
|
||||
}
|
||||
const name = String(identifier.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
}
|
||||
if (localNames.has(name)) {
|
||||
throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
}
|
||||
const initializer = asNode(declaration.init, `initializer for '${name}'`);
|
||||
if (initializer.type === "ArrowFunctionExpression" || initializer.type === "FunctionExpression") {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
}
|
||||
const value = context.evaluate(initializer, scopedEnvironment, depth + 1);
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
}
|
||||
localNames.add(name);
|
||||
scopedEnvironment = new Environment({ [name]: value }, scopedEnvironment);
|
||||
}
|
||||
}
|
||||
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Safe block did not return a value");
|
||||
}
|
||||
|
||||
function ensureNonCallableResult(value: unknown): unknown {
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) {
|
||||
const result = context.evaluate(callback.body, new Environment(values, callback.environment), depth + 1);
|
||||
if (
|
||||
typeof result === "function" ||
|
||||
(result !== null && typeof result === "object" && "kind" in result && result.kind === INTERPRETER_CALLBACK)
|
||||
) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
}
|
||||
return value;
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
export interface InterpreterMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
@@ -49,6 +49,21 @@ class Interpreter {
|
||||
|
||||
switch (node.type) {
|
||||
case "Literal":
|
||||
if (node.regex !== undefined) {
|
||||
const regex = node.regex as { pattern?: unknown; flags?: unknown };
|
||||
if (
|
||||
typeof regex.pattern !== "string" ||
|
||||
regex.pattern.length > 128 ||
|
||||
typeof regex.flags !== "string" ||
|
||||
/[^gimsu]/u.test(regex.flags) ||
|
||||
/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(regex.pattern)
|
||||
) {
|
||||
throw new SafeJsxError("UNSAFE_REGEX: Invalid regular expression literal");
|
||||
}
|
||||
return new RegExp(regex.pattern, regex.flags);
|
||||
}
|
||||
if (typeof node.value === "bigint")
|
||||
throw new SafeJsxError("BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
return node.value;
|
||||
case "Identifier":
|
||||
return environment.get(String(node.name));
|
||||
@@ -263,22 +278,8 @@ class Interpreter {
|
||||
if (node.optional) throw new SafeJsxError("Optional calls are not supported");
|
||||
const callee = asNode(node.callee, "call target");
|
||||
const argumentNodes = asNodeArray(node.arguments, "call arguments");
|
||||
if (callee.type === "ArrowFunctionExpression") {
|
||||
if (callee.body && asNode(callee.body, "inline derived-value body").type !== "BlockStatement") {
|
||||
throw new SafeJsxError(
|
||||
"BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block",
|
||||
);
|
||||
}
|
||||
if (asNodeArray(callee.params, "inline derived-value parameters").length > 0) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
|
||||
}
|
||||
if (argumentNodes.length > 0) {
|
||||
throw new SafeJsxError(
|
||||
"CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments",
|
||||
);
|
||||
}
|
||||
return this.runCallback(this.createCallback(callee, environment), [], depth + 1);
|
||||
}
|
||||
if (callee.type === "ArrowFunctionExpression")
|
||||
throw new SafeJsxError("CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
const callbackMethod =
|
||||
callee.type === "MemberExpression"
|
||||
? callee.computed
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createElement, Fragment } from "react";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Environment } from "./interpreter-foundation";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { emitRecursiveList } from "./recursive-list-emitter";
|
||||
import { resolveCustomJsxComponentName } from "../core/component-registry";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { CUSTOM_JSX_BLOCKED_TAGS } from "./policy";
|
||||
|
||||
@@ -29,16 +29,16 @@ export function emitJsxElement(
|
||||
): ReactNode {
|
||||
const opening = asNode(node.openingElement, "JSX opening element");
|
||||
const tag = jsxTagName(asNode(opening.name, "JSX tag"));
|
||||
const resolvedTag = resolveCustomJsxComponentName(tag);
|
||||
if (CUSTOM_JSX_BLOCKED_TAGS.has(tag.toLowerCase())) {
|
||||
context.warnings.add(`Blocked element: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
const component = context.components[tag];
|
||||
const component = context.components[resolvedTag];
|
||||
if (!component) {
|
||||
context.warnings.add(`Unknown or unavailable component: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
if (tag === "RecursiveList") return emitRecursiveList(node, environment, depth, component, context);
|
||||
const rawProps: Record<string, unknown> = {};
|
||||
for (const attribute of asNodeArray(opening.attributes, "JSX attributes")) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
@@ -58,11 +58,17 @@ export function emitJsxElement(
|
||||
rawProps[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
diagnoseCustomJsxProps(rawProps, tag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, tag);
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) => {
|
||||
const expression =
|
||||
child.type === "JSXExpressionContainer" ? asNode(child.expression, "JSX child expression") : null;
|
||||
if (resolvedTag === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
const callback = context.createCallback(expression, environment);
|
||||
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
|
||||
}
|
||||
return context.evaluate(child, environment, depth + 1);
|
||||
});
|
||||
diagnoseCustomJsxProps(rawProps, resolvedTag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, resolvedTag);
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "@mantine/core";
|
||||
import type { TreeNodeData } from "@mantine/core";
|
||||
|
||||
import { SafeJsxBudgetError } from "./interpreter-foundation";
|
||||
import {
|
||||
clampWithWarning,
|
||||
DEFAULT_MAX_DEPTH,
|
||||
DEFAULT_MAX_NODES,
|
||||
exceedsRecursiveListNodeLimit,
|
||||
formatPath,
|
||||
HARD_MAX_DEPTH,
|
||||
HARD_MAX_NODES,
|
||||
isObject,
|
||||
parseRestrictedPath,
|
||||
primitiveKey,
|
||||
readRestrictedPath,
|
||||
} from "./recursive-list-helpers";
|
||||
import type { RecursiveListBuildOptions, RecursiveListMetadata } from "./recursive-list-types";
|
||||
|
||||
const OMITTED_LABEL = "Additional levels omitted";
|
||||
|
||||
export function buildTrustedRecursiveList(options: RecursiveListBuildOptions): TreeNodeData[] {
|
||||
const maxDepth = clampWithWarning(
|
||||
options.maxDepth,
|
||||
DEFAULT_MAX_DEPTH,
|
||||
1,
|
||||
HARD_MAX_DEPTH,
|
||||
"maxDepth",
|
||||
options.warnings,
|
||||
);
|
||||
const maxNodes = clampWithWarning(
|
||||
options.maxNodes,
|
||||
DEFAULT_MAX_NODES,
|
||||
1,
|
||||
HARD_MAX_NODES,
|
||||
"maxNodes",
|
||||
options.warnings,
|
||||
);
|
||||
let childrenPath: string[];
|
||||
let keyPath: string[];
|
||||
try {
|
||||
childrenPath = parseRestrictedPath(options.childrenPath, "childrenPath");
|
||||
keyPath = parseRestrictedPath(options.keyPath, "keyPath");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
options.warnings.add(message);
|
||||
options.budget.operation(1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
return [diagnosticNode("diagnostic:path", message)];
|
||||
}
|
||||
const roots = Array.isArray(options.data) ? options.data : isObject(options.data) ? [options.data] : null;
|
||||
if (!roots) {
|
||||
options.warnings.add("RECURSIVE_LIST_INVALID_DATA: data must be an object or an array of objects");
|
||||
options.budget.operation(1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
return [diagnosticNode("diagnostic:root-data", "RecursiveList data must be an object or an array")];
|
||||
}
|
||||
|
||||
const willExceedNodeLimit = exceedsRecursiveListNodeLimit(roots, childrenPath, maxDepth, maxNodes, options.budget);
|
||||
let renderedRowCount = 0;
|
||||
let diagnosticCount = 0;
|
||||
let limitSentinelRendered = false;
|
||||
const usedKeys = new Set<string>();
|
||||
const chargeRow = (depth: number) => {
|
||||
options.budget.operation(depth + 1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
renderedRowCount += 1;
|
||||
};
|
||||
const makeLimitDiagnostic = (path: readonly number[], depth: number): TreeNodeData | null => {
|
||||
if (limitSentinelRendered || renderedRowCount >= maxNodes) return null;
|
||||
options.warnings.add(`RECURSIVE_LIST_NODE_LIMIT: Rendering stopped after ${maxNodes} nodes`);
|
||||
chargeRow(depth);
|
||||
diagnosticCount += 1;
|
||||
limitSentinelRendered = true;
|
||||
return diagnosticNode(`diagnostic:${path.join(".")}:${diagnosticCount}`, OMITTED_LABEL);
|
||||
};
|
||||
const makeDiagnostic = (path: readonly number[], message: string, depth: number): TreeNodeData | null => {
|
||||
if (renderedRowCount >= maxNodes) return null;
|
||||
if (willExceedNodeLimit && renderedRowCount === maxNodes - 1) return makeLimitDiagnostic(path, depth);
|
||||
chargeRow(depth);
|
||||
diagnosticCount += 1;
|
||||
return diagnosticNode(`diagnostic:${path.join(".")}:${diagnosticCount}`, message);
|
||||
};
|
||||
|
||||
const visitSiblings = (
|
||||
values: readonly unknown[],
|
||||
depth: number,
|
||||
parentPath: readonly number[],
|
||||
ancestors: ReadonlySet<object>,
|
||||
): TreeNodeData[] => {
|
||||
const result: TreeNodeData[] = [];
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
if (renderedRowCount >= maxNodes) break;
|
||||
if (willExceedNodeLimit && renderedRowCount === maxNodes - 1) {
|
||||
const omitted = makeLimitDiagnostic(parentPath, depth);
|
||||
if (omitted) result.push(omitted);
|
||||
break;
|
||||
}
|
||||
const value = values[index];
|
||||
const path = [...parentPath, index];
|
||||
if (!isObject(value)) {
|
||||
options.warnings.add(`RECURSIVE_LIST_INVALID_NODE: Node at ${formatPath(path)} is not an object`);
|
||||
const invalid = makeDiagnostic(path, "Invalid tree node omitted", depth);
|
||||
if (invalid) result.push(invalid);
|
||||
continue;
|
||||
}
|
||||
if (ancestors.has(value)) {
|
||||
options.warnings.add(`RECURSIVE_LIST_CYCLE: Cycle detected at ${formatPath(path)}`);
|
||||
const cycle = makeDiagnostic(path, OMITTED_LABEL, depth);
|
||||
if (cycle) result.push(cycle);
|
||||
continue;
|
||||
}
|
||||
|
||||
chargeRow(depth);
|
||||
const rawKey = readRestrictedPath(value, keyPath);
|
||||
const preferredKey = primitiveKey(rawKey);
|
||||
const namespacedPreferredKey = preferredKey === null ? null : `key:${typeof rawKey}:${preferredKey}`;
|
||||
let key = namespacedPreferredKey ?? `path:${path.join(".")}`;
|
||||
if (namespacedPreferredKey === null) {
|
||||
options.warnings.add(`RECURSIVE_LIST_MISSING_KEY: Node at ${formatPath(path)} uses a stable path key`);
|
||||
} else if (usedKeys.has(namespacedPreferredKey)) {
|
||||
key = `path:${path.join(".")}`;
|
||||
options.warnings.add(`RECURSIVE_LIST_DUPLICATE_KEY: '${preferredKey}' uses a stable path key`);
|
||||
}
|
||||
usedKeys.add(key);
|
||||
|
||||
const rawChildren = readRestrictedPath(value, childrenPath);
|
||||
const childValues = rawChildren === undefined || rawChildren === null ? [] : rawChildren;
|
||||
const validChildren = Array.isArray(childValues);
|
||||
const childCount = validChildren ? childValues.length : 0;
|
||||
const metadata: RecursiveListMetadata = Object.freeze({
|
||||
depth,
|
||||
index,
|
||||
path: Object.freeze(path) as unknown as number[],
|
||||
key,
|
||||
hasChildren: childCount > 0,
|
||||
childCount,
|
||||
isLast: index === values.length - 1,
|
||||
});
|
||||
const nextAncestors = new Set(ancestors).add(value);
|
||||
const children: TreeNodeData[] = [];
|
||||
if (!validChildren) {
|
||||
options.warnings.add(
|
||||
`RECURSIVE_LIST_INVALID_CHILDREN: ${options.childrenPath} at ${formatPath(path)} must be an array`,
|
||||
);
|
||||
const invalidChildren = makeDiagnostic(path, `Expected ${options.childrenPath} to be an array`, depth + 1);
|
||||
if (invalidChildren) children.push(invalidChildren);
|
||||
} else if (childCount > 0 && depth + 1 >= maxDepth) {
|
||||
options.warnings.add(`RECURSIVE_LIST_DEPTH_LIMIT: Rendering stopped at depth ${maxDepth}`);
|
||||
const omitted = makeDiagnostic(path, OMITTED_LABEL, depth + 1);
|
||||
if (omitted) children.push(omitted);
|
||||
} else if (childCount > 0) {
|
||||
children.push(...visitSiblings(childValues, depth + 1, path, nextAncestors));
|
||||
}
|
||||
|
||||
let label: ReactNode;
|
||||
try {
|
||||
label = options.render(value, metadata, depth + 1);
|
||||
} catch (error) {
|
||||
if (error instanceof SafeJsxBudgetError) throw error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
options.warnings.add(`RECURSIVE_LIST_BRANCH_ERROR: ${formatPath(path)}: ${message}`);
|
||||
label = (
|
||||
<Text size="xs" c="red">
|
||||
Unable to render this branch: {message}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
result.push({
|
||||
value: key,
|
||||
label,
|
||||
...(children.length > 0 ? { children } : {}),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
return visitSiblings(roots, 0, [], new Set());
|
||||
}
|
||||
|
||||
function diagnosticNode(value: string, message: string): TreeNodeData {
|
||||
return {
|
||||
value,
|
||||
label: (
|
||||
<Text size="xs" c="dimmed" fs="italic">
|
||||
{message}
|
||||
</Text>
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement } from "react";
|
||||
|
||||
import { buildTrustedRecursiveList } from "./recursive-list";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
const supportedProps = new Set([
|
||||
"data",
|
||||
"childrenPath",
|
||||
"keyPath",
|
||||
"maxDepth",
|
||||
"maxNodes",
|
||||
"defaultExpandedDepth",
|
||||
"indent",
|
||||
"gap",
|
||||
"showLines",
|
||||
"bind",
|
||||
]);
|
||||
|
||||
export function emitRecursiveList(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
component: ComponentType<never>,
|
||||
context: JsxEmitterContext,
|
||||
): ReactNode {
|
||||
const opening = asNode(node.openingElement, "RecursiveList opening element");
|
||||
const props: Record<string, unknown> = Object.create(null);
|
||||
for (const attribute of asNodeArray(opening.attributes, "RecursiveList attributes")) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
const spread = context.evaluate(
|
||||
asNode(attribute.argument, "RecursiveList spread attribute"),
|
||||
environment,
|
||||
depth + 1,
|
||||
);
|
||||
if (spread && typeof spread === "object" && !Array.isArray(spread)) {
|
||||
for (const [name, value] of Object.entries(spread)) {
|
||||
props[name] = value;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (attribute.type !== "JSXAttribute") throw new SafeJsxError(`Unsupported JSX attribute: ${attribute.type}`);
|
||||
const nameNode = asNode(attribute.name, "RecursiveList attribute name");
|
||||
if (nameNode.type !== "JSXIdentifier") throw new SafeJsxError("Namespaced JSX attributes are not supported");
|
||||
const rawName = String(nameNode.name);
|
||||
const name = rawName === "bind" ? rawName : normalizedProperty(rawName);
|
||||
if (attribute.value == null) props[name] = true;
|
||||
else {
|
||||
const value = asNode(attribute.value, `RecursiveList ${name} value`);
|
||||
props[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const callback = recursiveListCallback(node, environment, context);
|
||||
const data = props.data;
|
||||
const childrenPath = typeof props.childrenPath === "string" ? props.childrenPath : "";
|
||||
const keyPath = typeof props.keyPath === "string" ? props.keyPath : "";
|
||||
const nodes = buildTrustedRecursiveList({
|
||||
data,
|
||||
childrenPath,
|
||||
keyPath,
|
||||
maxDepth: props.maxDepth,
|
||||
maxNodes: props.maxNodes,
|
||||
budget: context.budget,
|
||||
warnings: context.warnings,
|
||||
render: (value, metadata, callbackDepth) =>
|
||||
context.renderCallback(callback, [value, metadata], depth + callbackDepth + 1),
|
||||
});
|
||||
if (Object.hasOwn(props, "bind")) {
|
||||
context.warnings.add("BINDING_UNAVAILABLE: 'RecursiveList' does not have a declarative binding adapter");
|
||||
}
|
||||
diagnoseCustomJsxProps(props, "RecursiveList").forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const rootProps = sanitizeCustomJsxProps(
|
||||
Object.fromEntries(Object.entries(props).filter(([name]) => !supportedProps.has(name))),
|
||||
"RecursiveList",
|
||||
);
|
||||
const trustedProps = {
|
||||
nodes,
|
||||
defaultExpandedDepth: finiteNumber(props.defaultExpandedDepth),
|
||||
indent: spacing(props.indent),
|
||||
gap: spacing(props.gap),
|
||||
showLines: props.showLines === true,
|
||||
rootProps,
|
||||
};
|
||||
context.budget.rendered();
|
||||
return createElement(component, trustedProps as never);
|
||||
}
|
||||
|
||||
function recursiveListCallback(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
context: JsxEmitterContext,
|
||||
): InterpreterCallback {
|
||||
const meaningfulChildren = asNodeArray(node.children, "RecursiveList children").filter(
|
||||
(child) => child.type !== "JSXText" || String(child.value ?? "").trim().length > 0,
|
||||
);
|
||||
if (meaningfulChildren.length !== 1 || meaningfulChildren[0]?.type !== "JSXExpressionContainer") {
|
||||
throw new SafeJsxError("RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList requires exactly one inline arrow child");
|
||||
}
|
||||
const expression = asNode(meaningfulChildren[0].expression, "RecursiveList template child");
|
||||
if (expression.type !== "ArrowFunctionExpression") {
|
||||
throw new SafeJsxError("RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child must be an inline arrow");
|
||||
}
|
||||
const params = asNodeArray(expression.params, "RecursiveList template parameters");
|
||||
if (params.length === 0 || params.length > 2) {
|
||||
throw new SafeJsxError(
|
||||
"RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child accepts node and optional metadata parameters",
|
||||
);
|
||||
}
|
||||
return context.createCallback(expression, environment);
|
||||
}
|
||||
|
||||
function spacing(value: unknown): string | number | undefined {
|
||||
return typeof value === "string" || typeof value === "number" ? value : undefined;
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import { SafeJsxError } from "./interpreter-foundation";
|
||||
import type { Budget } from "./interpreter-foundation";
|
||||
import { CUSTOM_JSX_BLOCKED_PROPERTIES, normalizeCustomJsxProperty } from "./policy";
|
||||
import { ownProperty } from "./safe-properties";
|
||||
|
||||
export const DEFAULT_MAX_DEPTH = 16;
|
||||
export const HARD_MAX_DEPTH = 32;
|
||||
export const DEFAULT_MAX_NODES = 500;
|
||||
export const HARD_MAX_NODES = 2_000;
|
||||
|
||||
export function exceedsRecursiveListNodeLimit(
|
||||
roots: readonly unknown[],
|
||||
childrenPath: readonly string[],
|
||||
maxDepth: number,
|
||||
maxNodes: number,
|
||||
budget: Budget,
|
||||
) {
|
||||
let rows = 0;
|
||||
const charge = (depth: number) => {
|
||||
budget.operation(depth + 1);
|
||||
rows += 1;
|
||||
return rows > maxNodes;
|
||||
};
|
||||
const visit = (values: readonly unknown[], depth: number, ancestors: ReadonlySet<object>): boolean => {
|
||||
for (const value of values) {
|
||||
if (charge(depth)) return true;
|
||||
if (!isObject(value) || ancestors.has(value)) continue;
|
||||
|
||||
const rawChildren = readRestrictedPath(value, childrenPath);
|
||||
if (rawChildren !== undefined && rawChildren !== null && !Array.isArray(rawChildren)) {
|
||||
if (charge(depth + 1)) return true;
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(rawChildren) || rawChildren.length === 0) continue;
|
||||
if (depth + 1 >= maxDepth) {
|
||||
if (charge(depth + 1)) return true;
|
||||
continue;
|
||||
}
|
||||
if (visit(rawChildren, depth + 1, new Set(ancestors).add(value))) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return visit(roots, 0, new Set());
|
||||
}
|
||||
|
||||
export function parseRestrictedPath(value: string, name: string): string[] {
|
||||
if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u.test(value)) {
|
||||
throw new SafeJsxError(`RECURSIVE_LIST_INVALID_PATH: ${name} must be a dotted property path`);
|
||||
}
|
||||
const segments = value.split(".");
|
||||
for (const segment of segments) {
|
||||
if (CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(segment))) {
|
||||
throw new SafeJsxError(`RECURSIVE_LIST_INVALID_PATH: ${name} contains blocked segment '${segment}'`);
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function readRestrictedPath(value: unknown, path: readonly string[]): unknown {
|
||||
let current = value;
|
||||
for (const segment of path) current = ownProperty(current, segment);
|
||||
return current;
|
||||
}
|
||||
|
||||
export function primitiveKey(value: unknown): string | null {
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : null;
|
||||
}
|
||||
|
||||
export function clampWithWarning(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
minimum: number,
|
||||
maximum: number,
|
||||
name: string,
|
||||
warnings: Set<string>,
|
||||
) {
|
||||
const validNumber = typeof value === "number" && Number.isFinite(value);
|
||||
const number = validNumber ? Math.trunc(value) : fallback;
|
||||
const clamped = Math.min(maximum, Math.max(minimum, number));
|
||||
if (value !== undefined && (!validNumber || value !== number || number !== clamped)) {
|
||||
warnings.add(`RECURSIVE_LIST_LIMIT_CLAMPED: ${name} was clamped to ${clamped}`);
|
||||
}
|
||||
return clamped;
|
||||
}
|
||||
|
||||
export function isObject(value: unknown): value is object {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function formatPath(path: readonly number[]) {
|
||||
return path.length === 0 ? "root" : path.join(".");
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { MantineSpacing, TreeNodeData } from "@mantine/core";
|
||||
|
||||
import type { Budget } from "./interpreter-foundation";
|
||||
|
||||
export interface RecursiveListMetadata {
|
||||
depth: number;
|
||||
index: number;
|
||||
path: number[];
|
||||
key: string;
|
||||
hasChildren: boolean;
|
||||
childCount: number;
|
||||
isLast: boolean;
|
||||
}
|
||||
|
||||
export interface RecursiveListBuildOptions {
|
||||
data: unknown;
|
||||
childrenPath: string;
|
||||
keyPath: string;
|
||||
maxDepth?: unknown;
|
||||
maxNodes?: unknown;
|
||||
budget: Budget;
|
||||
warnings: Set<string>;
|
||||
render(node: unknown, metadata: RecursiveListMetadata, depth: number): ReactNode;
|
||||
}
|
||||
|
||||
export interface TrustedRecursiveListProps {
|
||||
nodes: TreeNodeData[];
|
||||
defaultExpandedDepth?: number;
|
||||
indent?: MantineSpacing;
|
||||
gap?: MantineSpacing;
|
||||
showLines?: boolean;
|
||||
rootProps?: Record<string, unknown>;
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import type { ErrorInfo, ReactNode } from "react";
|
||||
import { Component, useMemo } from "react";
|
||||
import { Box, Group, Text, Tree, useTree } from "@mantine/core";
|
||||
import type { MantineSpacing, RenderTreeNodePayload, TreeNodeData } from "@mantine/core";
|
||||
import { IconChevronRight } from "@tabler/icons-react";
|
||||
|
||||
import { buildTrustedRecursiveList } from "./recursive-list-builder";
|
||||
import type { TrustedRecursiveListProps } from "./recursive-list-types";
|
||||
|
||||
const HARD_MAX_DEPTH = 32;
|
||||
|
||||
export { buildTrustedRecursiveList };
|
||||
export type {
|
||||
RecursiveListBuildOptions,
|
||||
RecursiveListMetadata,
|
||||
TrustedRecursiveListProps,
|
||||
} from "./recursive-list-types";
|
||||
|
||||
export function TrustedRecursiveList({ ...props }: TrustedRecursiveListProps) {
|
||||
return (
|
||||
<RecursiveListErrorBoundary resetKey={props.nodes} code="RECURSIVE_LIST_RENDER_ERROR">
|
||||
<TrustedRecursiveListInner {...props} />
|
||||
</RecursiveListErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function TrustedRecursiveListInner({
|
||||
nodes,
|
||||
defaultExpandedDepth = 4,
|
||||
indent = "lg",
|
||||
gap = "xs",
|
||||
showLines = false,
|
||||
rootProps = {},
|
||||
}: TrustedRecursiveListProps) {
|
||||
const initialExpandedState = useMemo(
|
||||
() => collectInitialExpandedState(nodes, clampInteger(defaultExpandedDepth, 0, HARD_MAX_DEPTH, 4)),
|
||||
[defaultExpandedDepth, nodes],
|
||||
);
|
||||
const tree = useTree({ initialExpandedState });
|
||||
|
||||
return (
|
||||
<Tree
|
||||
{...rootProps}
|
||||
data={nodes}
|
||||
tree={tree}
|
||||
levelOffset={indent}
|
||||
withLines={showLines}
|
||||
renderNode={(payload) => <TrustedRecursiveListNode {...payload} gap={gap} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
class RecursiveListErrorBoundary extends Component<
|
||||
{ children: ReactNode; resetKey: unknown; code: string },
|
||||
{ error: Error | null; resetKey: unknown }
|
||||
> {
|
||||
public state = { error: null, resetKey: this.props.resetKey } as { error: Error | null; resetKey: unknown };
|
||||
public static getDerivedStateFromProps(
|
||||
props: Readonly<{ children: ReactNode; resetKey: unknown; code: string }>,
|
||||
state: Readonly<{ error: Error | null; resetKey: unknown }>,
|
||||
) {
|
||||
if (props.resetKey === state.resetKey) return null;
|
||||
return { error: null, resetKey: props.resetKey };
|
||||
}
|
||||
public static getDerivedStateFromError(error: Error) {
|
||||
return { error };
|
||||
}
|
||||
public componentDidCatch(_error: Error, _info: ErrorInfo) {}
|
||||
public render() {
|
||||
return this.state.error ? (
|
||||
<Text size="xs" c="red">
|
||||
{this.props.code}: {this.state.error.message}
|
||||
</Text>
|
||||
) : (
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function TrustedRecursiveListNode({
|
||||
node,
|
||||
expanded,
|
||||
hasChildren,
|
||||
elementProps,
|
||||
gap,
|
||||
}: RenderTreeNodePayload & { gap: MantineSpacing }) {
|
||||
return (
|
||||
<Group {...elementProps} aria-expanded={hasChildren ? expanded : undefined} gap={gap} wrap="nowrap" py={2}>
|
||||
<Box w={16} h={16} style={{ flex: "0 0 16px" }} aria-hidden>
|
||||
{hasChildren && (
|
||||
<IconChevronRight
|
||||
size={15}
|
||||
style={{ transform: expanded ? "rotate(90deg)" : undefined, transition: "transform 120ms ease" }}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box style={{ minWidth: 0, flex: 1 }}>
|
||||
<RecursiveListErrorBoundary resetKey={node.label} code="RECURSIVE_LIST_BRANCH_RENDER_ERROR">
|
||||
{node.label}
|
||||
</RecursiveListErrorBoundary>
|
||||
</Box>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
function collectInitialExpandedState(nodes: readonly TreeNodeData[], depthLimit: number) {
|
||||
const expanded: Record<string, boolean> = {};
|
||||
const visit = (values: readonly TreeNodeData[], depth: number) => {
|
||||
for (const node of values) {
|
||||
if (!node.children?.length || depth >= depthLimit) continue;
|
||||
expanded[node.value] = true;
|
||||
visit(node.children, depth + 1);
|
||||
}
|
||||
};
|
||||
visit(nodes, 0);
|
||||
return expanded;
|
||||
}
|
||||
|
||||
function clampInteger(value: number, minimum: number, maximum: number, fallback: number) {
|
||||
if (!Number.isFinite(value)) return fallback;
|
||||
return Math.min(maximum, Math.max(minimum, Math.trunc(value)));
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import { SubData } from "../runtime/data";
|
||||
import { RefreshButton } from "../runtime/refresh-button";
|
||||
import { SubFetch } from "../runtime/sub-fetch";
|
||||
import { Collapsible, PaginatedList, StatBar, TabPanel, TabsContainer, TypeBadge } from "./interactive-components";
|
||||
import { TrustedRecursiveList } from "./recursive-list";
|
||||
import { getScopedCustomJsxControlName, isSafeCustomJsxUrl } from "./runtime-component-policy";
|
||||
import { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
@@ -278,7 +277,6 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
ActionButton,
|
||||
ToggleSwitch,
|
||||
RefreshButton,
|
||||
RecursiveList: TrustedRecursiveList,
|
||||
});
|
||||
return components;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export const CUSTOM_JSX_CALLBACK_METHODS: ReadonlySet<string> = new Set([
|
||||
"filter",
|
||||
"find",
|
||||
"findIndex",
|
||||
"flatMap",
|
||||
"map",
|
||||
"reduce",
|
||||
"some",
|
||||
@@ -30,12 +31,16 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
...CUSTOM_JSX_CALLBACK_METHODS,
|
||||
"at",
|
||||
"charAt",
|
||||
"concat",
|
||||
"endsWith",
|
||||
"flat",
|
||||
"flatMap",
|
||||
"includes",
|
||||
"indexOf",
|
||||
"join",
|
||||
"lastIndexOf",
|
||||
"localeCompare",
|
||||
"match",
|
||||
"padEnd",
|
||||
"padStart",
|
||||
"pop",
|
||||
@@ -44,10 +49,12 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
"replaceAll",
|
||||
"reverse",
|
||||
"slice",
|
||||
"search",
|
||||
"split",
|
||||
"startsWith",
|
||||
"substring",
|
||||
"toFixed",
|
||||
"toLocaleString",
|
||||
"toLowerCase",
|
||||
"toPrecision",
|
||||
"toString",
|
||||
@@ -55,4 +62,5 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
"trim",
|
||||
"trimEnd",
|
||||
"trimStart",
|
||||
"test",
|
||||
]);
|
||||
@@ -0,0 +1,119 @@
|
||||
import { numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
|
||||
export function callStringMethod(
|
||||
receiver: string,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp)
|
||||
return { handled: true, value: context.budget.string(receiver.replace(search, replacement)) };
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp) {
|
||||
if (!search.global) throw new SafeJsxError("replaceAll() requires a global regular expression");
|
||||
return { handled: true, value: context.budget.string(receiver.replaceAll(search, replacement)) };
|
||||
}
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
const maxCount = receiver.length > 0 ? Math.floor(200_001 / receiver.length) : 0;
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "localeCompare":
|
||||
return { handled: true, value: receiver.localeCompare(String(args[0] ?? "")) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const separator = args[0] instanceof RegExp ? args[0] : args[0] === undefined ? undefined : String(args[0]);
|
||||
const split = separator === undefined ? [receiver] : receiver.split(separator, limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
case "match": {
|
||||
const pattern = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const matches = receiver.match(pattern);
|
||||
if (matches) context.budget.collection(matches.length);
|
||||
return { handled: true, value: matches ? [...matches] : null };
|
||||
}
|
||||
case "search":
|
||||
return { handled: true, value: receiver.search(args[0] instanceof RegExp ? args[0] : String(args[0] ?? "")) };
|
||||
default:
|
||||
return { handled: false };
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,15 @@ export interface SubFetchMetadata {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
statusText?: string;
|
||||
loading: false;
|
||||
error?: undefined;
|
||||
}
|
||||
|
||||
export interface SubFetchProps {
|
||||
requestId?: string;
|
||||
params?: CustomJsxRuntimeParams;
|
||||
refreshInterval?: number;
|
||||
children?: ReactNode;
|
||||
children?: ReactNode | ((data: unknown, metadata: SubFetchMetadata) => ReactNode);
|
||||
loadingLabel?: string;
|
||||
errorMessage?: string;
|
||||
fallback?: ReactNode;
|
||||
@@ -105,7 +107,12 @@ export function SubFetch(props: SubFetchProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const content = renderContent(props, result?.data);
|
||||
const content = renderContent(props, result?.data, {
|
||||
ok: result?.ok ?? false,
|
||||
status: result?.status ?? 0,
|
||||
statusText: result?.statusText,
|
||||
loading: false,
|
||||
});
|
||||
return <SubFetchDataContext.Provider value={result?.data}>{content}</SubFetchDataContext.Provider>;
|
||||
}
|
||||
|
||||
@@ -113,7 +120,8 @@ function normalizeRefreshInterval(value: number | undefined): number | false {
|
||||
return value && Number.isFinite(value) && value > 0 ? Math.max(1_000, value * 1_000) : false;
|
||||
}
|
||||
|
||||
function renderContent(props: SubFetchProps, data: unknown) {
|
||||
function renderContent(props: SubFetchProps, data: unknown, metadata: SubFetchMetadata) {
|
||||
if (typeof props.children === "function") return props.children(data, metadata);
|
||||
if (props.children) return props.children;
|
||||
if (props.path === undefined && props.as === undefined) return null;
|
||||
const value = getByPath(data, props.path);
|
||||
|
||||
@@ -30,6 +30,6 @@ export {
|
||||
renderBoundValue,
|
||||
renderRequestBody,
|
||||
renderRequestTarget,
|
||||
validateRuntimeParams,
|
||||
resolveCustomWidgetRequestValues,
|
||||
} from "./request-manifest";
|
||||
export type { CustomJsxRuntimeParams } from "./request-manifest";
|
||||
@@ -1,7 +1,12 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { customJsxRequestSchema, customWidgetSecretKinds, customWidgetSourceSchema } from "../core";
|
||||
import type { CustomJsxRequest, CustomWidgetSource } from "../core";
|
||||
import {
|
||||
customWidgetOptionsSchema,
|
||||
customWidgetRequestsSchema,
|
||||
customWidgetSecretKinds,
|
||||
customWidgetSourcesSchema,
|
||||
} from "../core";
|
||||
import type { CustomJsxRequest, CustomWidgetOptions, CustomWidgetSource } from "../core";
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
|
||||
const SESSION_TTL_MS = 10 * 60_000;
|
||||
@@ -17,12 +22,12 @@ const sessionSchema = z.object({
|
||||
id: z.string(),
|
||||
userId: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sources: z.array(customWidgetSourceSchema),
|
||||
sources: customWidgetSourcesSchema,
|
||||
secrets: z.array(encryptedSecretSchema),
|
||||
requests: z.array(customJsxRequestSchema),
|
||||
requests: customWidgetRequestsSchema,
|
||||
name: z.string(),
|
||||
template: z.string(),
|
||||
optionsSchema: z.record(z.string(), z.unknown()),
|
||||
optionDefinitions: customWidgetOptionsSchema,
|
||||
options: z.record(z.string(), z.unknown()),
|
||||
definitionId: z.string().optional(),
|
||||
liveActions: z.boolean(),
|
||||
@@ -34,7 +39,7 @@ const journalEntrySchema = z.object({
|
||||
requestId: z.string(),
|
||||
kind: z.enum(["query", "action"]),
|
||||
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
|
||||
pathTemplate: z.string(),
|
||||
path: z.string(),
|
||||
status: z.number().nullable(),
|
||||
durationMs: z.number().nonnegative(),
|
||||
simulated: z.boolean(),
|
||||
@@ -44,12 +49,12 @@ export type CustomWidgetPreviewJournalEntry = z.infer<typeof journalEntrySchema>
|
||||
|
||||
export interface CreatePreviewSessionInput {
|
||||
userId: string;
|
||||
sources: CustomWidgetSource[];
|
||||
sources: Record<string, CustomWidgetSource>;
|
||||
secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>;
|
||||
requests: CustomJsxRequest[];
|
||||
requests: Record<string, CustomJsxRequest>;
|
||||
name: string;
|
||||
template: string;
|
||||
optionsSchema: Record<string, unknown>;
|
||||
optionDefinitions: CustomWidgetOptions;
|
||||
options: Record<string, unknown>;
|
||||
definitionId?: string;
|
||||
}
|
||||
@@ -80,7 +85,7 @@ export class CustomWidgetPreviewSessionService {
|
||||
}
|
||||
|
||||
public async create(input: CreatePreviewSessionInput) {
|
||||
const sourceIds = new Set(input.sources.map((source) => source.id));
|
||||
const sourceIds = new Set(Object.keys(input.sources));
|
||||
if (input.secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
@@ -96,7 +101,7 @@ export class CustomWidgetPreviewSessionService {
|
||||
requests: input.requests,
|
||||
name: input.name,
|
||||
template: input.template,
|
||||
optionsSchema: input.optionsSchema,
|
||||
optionDefinitions: input.optionDefinitions,
|
||||
options: input.options,
|
||||
definitionId: input.definitionId,
|
||||
liveActions: false,
|
||||
@@ -155,7 +160,7 @@ export class CustomWidgetPreviewSessionService {
|
||||
secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>,
|
||||
) {
|
||||
const session = await this.get(id, userId);
|
||||
const sourceIds = new Set(session.sources.map((source) => source.id));
|
||||
const sourceIds = new Set(Object.keys(session.sources));
|
||||
if (secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
|
||||
@@ -1,47 +1,62 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
|
||||
import { isCustomWidgetParameterIdentifier } from "../core";
|
||||
import type { CustomJsxRequest } from "../core";
|
||||
|
||||
import { collectCustomWidgetRequestReferences } from "../core";
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
import { resolveSameOriginTarget } from "./request-executor";
|
||||
|
||||
export type CustomJsxRuntimeParams = Record<string, string | number | boolean>;
|
||||
type CustomJsxResolvedValues = Record<string, unknown>;
|
||||
|
||||
export const validateRuntimeParams = (request: CustomJsxRequest, params: CustomJsxRuntimeParams) => {
|
||||
const declaredNames = Object.keys(request.parameters).toSorted();
|
||||
const suppliedNames = Object.keys(params).toSorted();
|
||||
export function resolveCustomWidgetRequestValues(
|
||||
request: CustomJsxRequest,
|
||||
options: Record<string, unknown>,
|
||||
suppliedParams: CustomJsxRuntimeParams = {},
|
||||
): CustomJsxResolvedValues {
|
||||
const references = collectCustomWidgetRequestReferences(request);
|
||||
const suppliedNames = Object.keys(suppliedParams).toSorted();
|
||||
const expectedNames = [...references.params].toSorted();
|
||||
if (
|
||||
declaredNames.length !== suppliedNames.length ||
|
||||
declaredNames.some((name, index) => name !== suppliedNames[index])
|
||||
suppliedNames.length !== expectedNames.length ||
|
||||
suppliedNames.some((name, index) => name !== expectedNames[index])
|
||||
) {
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: "Request parameters do not match the manifest" });
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Request parameters do not match the request references",
|
||||
});
|
||||
}
|
||||
for (const [name, expectedType] of Object.entries(request.parameters)) {
|
||||
if (typeof params[name] !== expectedType) {
|
||||
const values: CustomJsxResolvedValues = { ...suppliedParams };
|
||||
for (const name of references.options) {
|
||||
const value = options[name];
|
||||
if (value === undefined) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Request parameter '${name}' must be ${expectedType}`,
|
||||
message: `Widget option '${name}' is missing`,
|
||||
});
|
||||
}
|
||||
values[`option:${name}`] = value;
|
||||
}
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
export const renderBoundValue = (template: unknown, params: CustomJsxRuntimeParams): unknown => {
|
||||
export const renderBoundValue = (template: unknown, values: CustomJsxResolvedValues): unknown => {
|
||||
const substitute = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(substitute);
|
||||
if (value !== null && typeof value === "object") {
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") {
|
||||
const parameter = params[entries[0][1]];
|
||||
if (parameter === undefined) {
|
||||
if (
|
||||
entries.length === 1 &&
|
||||
["$param", "$option"].includes(entries[0]?.[0] ?? "") &&
|
||||
typeof entries[0]?.[1] === "string"
|
||||
) {
|
||||
const prefix = entries[0][0] === "$option" ? "option:" : "";
|
||||
const resolved = values[`${prefix}${entries[0][1]}`];
|
||||
if (resolved === undefined)
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Unknown body parameter '${entries[0][1]}'`,
|
||||
message: `Unknown request value '${entries[0][1]}'`,
|
||||
});
|
||||
}
|
||||
return parameter;
|
||||
return resolved;
|
||||
}
|
||||
return Object.fromEntries(entries.map(([key, child]) => [key, substitute(child)]));
|
||||
}
|
||||
@@ -50,42 +65,35 @@ export const renderBoundValue = (template: unknown, params: CustomJsxRuntimePara
|
||||
return substitute(template);
|
||||
};
|
||||
|
||||
export const renderRequestBody = (
|
||||
template: CustomJsxRequest["bodyTemplate"],
|
||||
params: CustomJsxRuntimeParams,
|
||||
): string | undefined => {
|
||||
if (template === undefined) return undefined;
|
||||
return JSON.stringify(renderBoundValue(template, params));
|
||||
};
|
||||
export const renderRequestBody = (request: CustomJsxRequest, values: CustomJsxResolvedValues): string | undefined =>
|
||||
request.body === undefined ? undefined : JSON.stringify(renderBoundValue(request.body, values));
|
||||
|
||||
export const renderRequestTarget = (baseUrl: string, request: CustomJsxRequest, params: CustomJsxRuntimeParams) => {
|
||||
validateRuntimeParams(request, params);
|
||||
const path = request.pathTemplate.replaceAll(/\{([^{}]+)\}/g, (_placeholder, name: string) => {
|
||||
if (!isCustomWidgetParameterIdentifier(name)) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Path template contains an invalid placeholder '${name}'`,
|
||||
});
|
||||
}
|
||||
const value = params[name];
|
||||
if (value === undefined) {
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: `Unknown path parameter '${name}'` });
|
||||
}
|
||||
return encodeURIComponent(String(value));
|
||||
});
|
||||
if (/[{}]/.test(path)) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Path template contains an invalid placeholder",
|
||||
});
|
||||
}
|
||||
const target = resolveSameOriginTarget(baseUrl, new URL(path, baseUrl));
|
||||
for (const [name, template] of Object.entries(request.queryTemplate ?? {})) {
|
||||
const value = renderBoundValue(template, params);
|
||||
export const renderRequestTarget = (baseUrl: string, request: CustomJsxRequest, values: CustomJsxResolvedValues) => {
|
||||
const path = request.path.replaceAll(
|
||||
/\{(option|param):([A-Za-z][A-Za-z0-9_-]*)\}/gu,
|
||||
(_match, kind: string, name: string) => {
|
||||
const value = values[kind === "option" ? `option:${name}` : name];
|
||||
if (value === undefined)
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: `Unknown path value '${name}'` });
|
||||
if (!["string", "number", "boolean"].includes(typeof value))
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Path value '${name}' must resolve to text, number, or boolean`,
|
||||
});
|
||||
return encodeURIComponent(String(value));
|
||||
},
|
||||
);
|
||||
if (/[{}]/u.test(path))
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: "Request path contains an invalid placeholder" });
|
||||
const base = new URL(baseUrl);
|
||||
base.pathname = `${base.pathname.replace(/\/$/u, "")}${path}` || "/";
|
||||
const target = resolveSameOriginTarget(baseUrl, base);
|
||||
for (const [name, template] of Object.entries(request.query ?? {})) {
|
||||
const value = renderBoundValue(template, values);
|
||||
if (!["string", "number", "boolean"].includes(typeof value)) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Query parameter '${name}' must resolve to a string, number, or boolean`,
|
||||
message: `Query value '${name}' must resolve to text, number, or boolean`,
|
||||
});
|
||||
}
|
||||
target.searchParams.set(name, String(value));
|
||||
@@ -93,9 +101,7 @@ export const renderRequestTarget = (baseUrl: string, request: CustomJsxRequest,
|
||||
return target;
|
||||
};
|
||||
|
||||
export const hashRuntimeParams = (params: CustomJsxRuntimeParams) => {
|
||||
const stableParams = Object.fromEntries(
|
||||
Object.entries(params).toSorted(([left], [right]) => left.localeCompare(right)),
|
||||
);
|
||||
return createHash("sha256").update(JSON.stringify(stableParams)).digest("hex");
|
||||
};
|
||||
export function hashRuntimeParams(params: CustomJsxResolvedValues) {
|
||||
const stable = Object.fromEntries(Object.entries(params).toSorted(([left], [right]) => left.localeCompare(right)));
|
||||
return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CUSTOM_WIDGET_AI_EVALUATION_CASES } from "../../scripts/ai-evaluation-cases";
|
||||
import { buildEvaluationPrompt, buildRepairPrompt, judgePasses, parseJudgeResult } from "../../scripts/ai-evaluation";
|
||||
|
||||
describe("AI authoring evaluation", () => {
|
||||
it("defines five distinct complex scenarios", () => {
|
||||
expect(CUSTOM_WIDGET_AI_EVALUATION_CASES).toHaveLength(5);
|
||||
expect(new Set(CUSTOM_WIDGET_AI_EVALUATION_CASES.map((entry) => entry.id)).size).toBe(5);
|
||||
});
|
||||
|
||||
it("uses the exact clipboard prompt and grounded API notes", () => {
|
||||
const testCase = CUSTOM_WIDGET_AI_EVALUATION_CASES.at(0);
|
||||
if (!testCase) throw new Error("Expected at least one AI evaluation case");
|
||||
const prompt = buildEvaluationPrompt(testCase);
|
||||
expect(prompt.length).toBeLessThanOrEqual(12_000);
|
||||
expect(prompt).toContain("Verified API notes");
|
||||
expect(prompt).not.toContain("customWidget_validate");
|
||||
expect(prompt).not.toContain("homarr://");
|
||||
});
|
||||
|
||||
it("keeps validation failures concrete during repair", () => {
|
||||
const prompt = buildRepairPrompt("original", "bad response", [
|
||||
{ path: ["requests", "list", "path"], message: "Required" },
|
||||
]);
|
||||
expect(prompt).toContain("requests.list.path: Required");
|
||||
expect(prompt).toContain("bad response");
|
||||
});
|
||||
|
||||
it("requires a strong overall and category score", () => {
|
||||
const categories = {
|
||||
schemaAndBindings: 90,
|
||||
apiAndRequestDesign: 90,
|
||||
runtimeCompatibility: 90,
|
||||
visualHierarchy: 90,
|
||||
responsiveAndTheme: 90,
|
||||
loadingEmptyErrorSuccess: 90,
|
||||
accessibility: 90,
|
||||
actionSafety: 90,
|
||||
simplicity: 90,
|
||||
};
|
||||
expect(
|
||||
judgePasses({ total: 90, verdict: "pass", categories, strengths: [], problems: [], highestImpactFixes: [] }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
judgePasses({
|
||||
total: 90,
|
||||
verdict: "pass",
|
||||
categories: { ...categories, accessibility: 64 },
|
||||
strengths: [],
|
||||
problems: [],
|
||||
highestImpactFixes: [],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes a judge verdict from numeric scores", () => {
|
||||
const parsed = parseJudgeResult(
|
||||
JSON.stringify({
|
||||
total: 84,
|
||||
verdict: "fail",
|
||||
categories: {
|
||||
schemaAndBindings: 85,
|
||||
apiAndRequestDesign: 82,
|
||||
runtimeCompatibility: 84,
|
||||
visualHierarchy: 86,
|
||||
responsiveAndTheme: 83,
|
||||
loadingEmptyErrorSuccess: 82,
|
||||
accessibility: 80,
|
||||
actionSafety: 87,
|
||||
simplicity: 85,
|
||||
},
|
||||
strengths: [],
|
||||
problems: [],
|
||||
highestImpactFixes: [],
|
||||
}),
|
||||
);
|
||||
expect(parsed.verdict).toBe("pass");
|
||||
});
|
||||
});
|
||||
@@ -1,109 +1,48 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { buildCustomWidgetAiPrompt, CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION } from "../core/ai-prompt";
|
||||
|
||||
import {
|
||||
buildCustomWidgetAiPrompt,
|
||||
buildCustomWidgetMcpPrompt,
|
||||
CUSTOM_WIDGET_MANTINE_VERSION,
|
||||
} from "../core/ai-prompt";
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
|
||||
describe("buildCustomWidgetAiPrompt", () => {
|
||||
test("is concise and describes the one-widget v2 contract", () => {
|
||||
describe("AI prompt", () => {
|
||||
it("is self-contained, request-first, and compact", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
null,
|
||||
null,
|
||||
"Create a Portainer widget",
|
||||
"https://example.com/docs",
|
||||
"Create a beautiful Pokédex",
|
||||
"https://pokeapi.co/docs/v2",
|
||||
);
|
||||
expect(prompt).toContain("homarr-custom-widget-v2");
|
||||
expect(prompt).toContain("Return exactly two fenced blocks");
|
||||
expect(prompt).toContain("Never include credentials");
|
||||
expect(prompt).toContain("Every declared parameter needs an explicit value source");
|
||||
expect(prompt).toContain('"optionsBinding"');
|
||||
expect(prompt).toContain("Never infer a binding from matching names");
|
||||
expect(prompt).toContain("Create a Portainer widget");
|
||||
expect(prompt.startsWith("Please create this Homarr Custom JSX v2 widget:\n\nCreate a Portainer widget")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(prompt).not.toMatch(/\bMCP\b|homarr:\/\/|customWidget_|\btools?\b/iu);
|
||||
expect(prompt.length).toBeLessThanOrEqual(8_000);
|
||||
expect(prompt.length).toBeLessThanOrEqual(12_000);
|
||||
expect(prompt.indexOf("Create a beautiful Pokédex")).toBeLessThan(prompt.indexOf("Manifest contract"));
|
||||
expect(prompt).toContain('"requests": {');
|
||||
expect(prompt).toContain("{option:name}");
|
||||
expect(prompt).toContain("Example — Service dashboard");
|
||||
expect(prompt).toContain("Example — Search and action");
|
||||
expect(prompt).toContain("visual hierarchy");
|
||||
expect(prompt).toContain('template set exactly to "__HOMARR_TEMPLATE__"');
|
||||
expect(prompt).toContain('trigger="manual"');
|
||||
expect(prompt).toContain("never write `=> {` anywhere");
|
||||
expect(prompt).toContain('"choicesFrom"');
|
||||
expect(prompt).toContain("must not shadow the reserved roots");
|
||||
expect(prompt.endsWith(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps release metadata lightweight and synchronized", async () => {
|
||||
const mantinePackage = JSON.parse(
|
||||
await readFile(resolve(import.meta.dirname, "../../../../node_modules/@mantine/core/package.json"), "utf8"),
|
||||
) as { version: string };
|
||||
const source = await readFile(resolve(import.meta.dirname, "../core/ai-prompt.ts"), "utf8");
|
||||
|
||||
expect(CUSTOM_WIDGET_MANTINE_VERSION).toBe(mantinePackage.version);
|
||||
expect(source).not.toContain("skill-content.generated.json");
|
||||
expect(source).not.toContain("component-catalog.generated.json");
|
||||
expect(source).toContain('from "./component-catalog"');
|
||||
expect(source).not.toContain('from "./authoring-resources"');
|
||||
it("does not claim offline MCP tools or embed the component catalog", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(undefined, null, null, "Build a widget");
|
||||
expect(prompt).not.toContain("customWidget_validate");
|
||||
expect(prompt).not.toContain("homarr://");
|
||||
expect(prompt).not.toContain("OFFLINE BUNDLE");
|
||||
expect(prompt.match(/Recommended components:/gu)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("includes an existing widget without exposing secret fields", () => {
|
||||
const secret = "TOP-SECRET-123";
|
||||
const source = CUSTOM_WIDGET_STARTER.sources[0];
|
||||
if (!source) throw new Error("Starter widget requires one source");
|
||||
it("redacts secrets and preserves the final instruction when optional context is large", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
JSON.stringify({ token: secret }),
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [{ ...source, baseUrl: `https://user:${secret}@example.com?api_key=${secret}` }],
|
||||
secrets: [{ sourceId: "default", kind: "apiKey", value: secret }],
|
||||
},
|
||||
`Improve it with API key: ${secret}`,
|
||||
`https://example.com/docs?token=${secret}`,
|
||||
JSON.stringify({ token: "sensitive", data: "x".repeat(20_000) }),
|
||||
null,
|
||||
"Build it",
|
||||
);
|
||||
expect(prompt).toContain('"$schema": "homarr-custom-widget-v2"');
|
||||
expect(prompt).not.toContain(secret);
|
||||
expect(prompt).not.toContain("user:");
|
||||
expect(prompt).not.toContain("api_key=");
|
||||
});
|
||||
|
||||
test("redacts camel-case credentials and invalid structured editor drafts", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(undefined, null, {
|
||||
sources: '[{"baseUrl":"https://user:password@example.com?accessToken=VALUE"}]',
|
||||
requests: '[{"bodyTemplate":{"clientSecret":"VALUE"}}]',
|
||||
template: "<Text>accessToken: VALUE</Text>",
|
||||
});
|
||||
expect(prompt).not.toContain("password@");
|
||||
expect(prompt).not.toContain('clientSecret": "VALUE');
|
||||
expect(prompt).not.toContain("accessToken: VALUE");
|
||||
});
|
||||
|
||||
test("redacts malformed URLs without recursing", () => {
|
||||
expect(buildCustomWidgetAiPrompt(undefined, null, null, "Inspect http://[", null)).toContain("[REDACTED_URL]");
|
||||
});
|
||||
|
||||
test("preserves balanced fences and the output contract when optional content exceeds the prompt budget", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
JSON.stringify({ items: Array.from({ length: 2_000 }, (_, index) => ({ index, label: `item-${index}` })) }),
|
||||
{ ...CUSTOM_WIDGET_STARTER, template: `<Stack>${"<Text>Large widget</Text>".repeat(1_000)}</Stack>` },
|
||||
"Improve this large widget",
|
||||
);
|
||||
|
||||
expect(prompt.length).toBeLessThanOrEqual(8_000);
|
||||
expect(prompt).toContain("content omitted to fit the prompt budget");
|
||||
expect(prompt.match(/```/gu)?.length ?? 0).toBe(4);
|
||||
expect(prompt.endsWith("Homarr will validate the result after it is pasted into the workbench.")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCustomWidgetMcpPrompt", () => {
|
||||
test("describes tool-driven iteration without embedding the copy/paste output contract", () => {
|
||||
const prompt = buildCustomWidgetMcpPrompt("Create two Portainer widgets", "https://example.com/docs");
|
||||
expect(prompt).toContain("customWidget_previewCreate");
|
||||
expect(prompt).toContain("homarr://custom-widgets/schema");
|
||||
expect(prompt).toContain("Create two Portainer widgets");
|
||||
expect(prompt).not.toContain("Return exactly two fenced blocks");
|
||||
expect(prompt.length).toBeLessThan(8_000);
|
||||
expect(prompt).not.toContain("sensitive");
|
||||
expect(prompt.endsWith(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBe(true);
|
||||
expect(prompt.length).toBeLessThanOrEqual(12_000);
|
||||
});
|
||||
});
|
||||
@@ -1,119 +1,31 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getCustomWidgetComponent,
|
||||
getCustomWidgetComponentCatalog,
|
||||
getCustomWidgetSkill,
|
||||
getCustomWidgetSkillContent,
|
||||
} from "../core/authoring-resources";
|
||||
import { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "../core/ai-prompt";
|
||||
import { customJsxAuthoringCatalog } from "../core/component-catalog";
|
||||
import {
|
||||
CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES,
|
||||
CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG,
|
||||
CUSTOM_WIDGET_OFFLINE_BUNDLE,
|
||||
CUSTOM_WIDGET_SKILL_FILES,
|
||||
CUSTOM_WIDGET_SKILL_MD,
|
||||
} from "../core/embedded-ai-prompt";
|
||||
|
||||
const repositoryRoot = resolve(import.meta.dirname, "../../../..");
|
||||
const skillRoot = resolve(repositoryRoot, ".agents/skills/homarr-custom-widget");
|
||||
const generatedPath = resolve(repositoryRoot, "packages/custom-widgets/src/core/skill-content.generated.json");
|
||||
const MAX_OFFLINE_BUNDLE_CHARACTERS = 1_600_000;
|
||||
const expectedPaths = [
|
||||
"SKILL.md",
|
||||
"references/schema.md",
|
||||
"references/widget-schema.json",
|
||||
"references/runtime.md",
|
||||
"references/security.md",
|
||||
"references/components.md",
|
||||
"references/component-catalog.json",
|
||||
"references/examples.json",
|
||||
"references/mantine-core.md",
|
||||
"references/mantine-dates.md",
|
||||
"references/mantine-charts.md",
|
||||
"references/homarr-components.md",
|
||||
] as const;
|
||||
|
||||
describe("custom widget Agent Skill", () => {
|
||||
test("keeps every generated skill file synchronized with the repository source", async () => {
|
||||
const expectedFiles = await Promise.all(
|
||||
expectedPaths.map(async (path) => ({
|
||||
path,
|
||||
content: normalizeMarkdown(await readFile(resolve(skillRoot, path), "utf8")),
|
||||
})),
|
||||
);
|
||||
expect(CUSTOM_WIDGET_SKILL_FILES).toEqual(expectedFiles);
|
||||
expect(await readFile(generatedPath, "utf8")).toBe(
|
||||
`${JSON.stringify({ schemaVersion: 1, files: expectedFiles }, null, 2)}\n`,
|
||||
);
|
||||
expect(CUSTOM_WIDGET_SKILL_MD).toBe(expectedFiles[0]?.content);
|
||||
expect(getCustomWidgetSkill().skillMd).toBe(expectedFiles[0]?.content);
|
||||
});
|
||||
|
||||
test("builds a complete self-verifying offline bundle", () => {
|
||||
for (const file of CUSTOM_WIDGET_SKILL_FILES.filter(
|
||||
({ path }) => !["references/component-catalog.json", "references/examples.json"].includes(path),
|
||||
)) {
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(`--- BEGIN SKILL FILE: ${file.path} ---`);
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(file.content.trimEnd());
|
||||
}
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(
|
||||
`--- BEGIN CANONICAL COMPONENT CATALOG ---\n${CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG}\n--- END CANONICAL COMPONENT CATALOG ---`,
|
||||
);
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(
|
||||
`--- BEGIN CANONICAL RUNTIME EXAMPLES ---\n${CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES}\n--- END CANONICAL RUNTIME EXAMPLES ---`,
|
||||
);
|
||||
const firstComponent = customJsxAuthoringCatalog.components[0];
|
||||
const lastComponent = customJsxAuthoringCatalog.components.at(-1);
|
||||
expect(firstComponent).toBeDefined();
|
||||
expect(lastComponent).toBeDefined();
|
||||
expect(CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG).toContain(JSON.stringify(firstComponent));
|
||||
expect(CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG).toContain(JSON.stringify(lastComponent));
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain("Custom Widget authoring version: 2.0.0");
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain("Mantine version: 9.4.1");
|
||||
expect(
|
||||
CUSTOM_WIDGET_OFFLINE_BUNDLE.endsWith(
|
||||
`${CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL}\nCharacters: ${CUSTOM_WIDGET_OFFLINE_BUNDLE.length}`,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE.length).toBeLessThanOrEqual(MAX_OFFLINE_BUNDLE_CHARACTERS);
|
||||
});
|
||||
|
||||
test("publishes repository-based skills.sh installation metadata", () => {
|
||||
describe("authoring resources", () => {
|
||||
it("returns the concise skills.sh discovery shape", () => {
|
||||
const skill = getCustomWidgetSkill();
|
||||
expect(skill.skillsShUrl).toBe("https://www.skills.sh/homarr-labs/homarr/homarr-custom-widget");
|
||||
expect(skill.sourceUrl).toBe("https://github.com/homarr-labs/homarr/tree/HEAD/.agents/skills/homarr-custom-widget");
|
||||
expect(skill.installCommand).toBe(
|
||||
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget",
|
||||
expect(skill).toMatchObject({ name: "homarr-custom-widget", version: "2.0.0" });
|
||||
expect(skill.skillsShUrl).toContain("skills.sh/homarr-labs/homarr");
|
||||
expect(skill.sourceUrl).toContain("/tree/HEAD/.agents/skills/homarr-custom-widget");
|
||||
expect(skill.installCommand).toContain("--skill homarr-custom-widget");
|
||||
expect(skill).not.toHaveProperty("files");
|
||||
expect(skill).not.toHaveProperty("componentCatalog");
|
||||
expect(getCustomWidgetSkillContent()).toBe(skill.skillMd);
|
||||
expect(skill.skillMd.trim()).toBe(
|
||||
readFileSync(new URL("../../../../.agents/skills/homarr-custom-widget/SKILL.md", import.meta.url), "utf8").trim(),
|
||||
);
|
||||
expect(skill.files).toBe(CUSTOM_WIDGET_SKILL_FILES);
|
||||
expect(skill.componentCatalog).toBe(customJsxAuthoringCatalog);
|
||||
expect(skill.examples).toEqual(expect.arrayContaining([expect.objectContaining({ id: "pokemon-evolution-tree" })]));
|
||||
expect(skill).not.toHaveProperty("sha256");
|
||||
expect(skill).not.toHaveProperty("downloadUrl");
|
||||
});
|
||||
|
||||
test("publishes safe icon names with the Tabler icon component", () => {
|
||||
expect(getCustomWidgetComponent("TablerIcon")?.knownValues?.name).toContain("server");
|
||||
});
|
||||
|
||||
test("serves the canonical catalog and derives detailed component resources from it", () => {
|
||||
expect(getCustomWidgetComponentCatalog()).toBe(customJsxAuthoringCatalog);
|
||||
const textInput = getCustomWidgetComponent("TextInput");
|
||||
expect(textInput).toMatchObject({
|
||||
schemaVersion: customJsxAuthoringCatalog.schemaVersion,
|
||||
mantineVersion: customJsxAuthoringCatalog.mantineVersion,
|
||||
bind: { type: "string", initialProp: "defaultValue" },
|
||||
});
|
||||
expect(textInput?.props).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ name: "label", type: expect.stringContaining("ReactNode") })]),
|
||||
);
|
||||
it("keeps the full catalog retrieval-based", () => {
|
||||
expect(getCustomWidgetComponentCatalog().components.length).toBeGreaterThan(100);
|
||||
expect(getCustomWidgetComponent("Stack")?.name).toBe("Stack");
|
||||
expect(getCustomWidgetComponent("Icon")?.knownValues?.name.length).toBeGreaterThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
function normalizeMarkdown(value: string) {
|
||||
return `${value.replace(/\r\n?/gu, "\n").trimEnd()}\n`;
|
||||
}
|
||||
@@ -91,9 +91,7 @@ describe("Custom JSX authoring catalog", () => {
|
||||
const switchComponent = customJsxAuthoringCatalog.components.find(({ name }) => name === "Switch");
|
||||
expect(switchComponent?.bind).toEqual({ type: "boolean", initialProp: "defaultChecked" });
|
||||
|
||||
const recursiveList = customJsxAuthoringCatalog.components.find(({ name }) => name === "RecursiveList");
|
||||
expect(recursiveList?.props.find(({ name }) => name === "childrenPath")?.required).toBe(true);
|
||||
expect(recursiveList?.accessibilityRequirements.length).toBeGreaterThan(0);
|
||||
expect(customJsxAuthoringCatalog.components.some(({ name }) => name === "RecursiveList")).toBe(false);
|
||||
|
||||
const portal = customJsxAuthoringCatalog.components.find(({ name }) => name === "Portal");
|
||||
expect(portal?.safety).toBe("denied");
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
GENERATED_COMPONENT_REFERENCE_PATHS,
|
||||
getComponentReferenceAnchor,
|
||||
renderCustomWidgetComponentReferences,
|
||||
} from "../../scripts/component-docs";
|
||||
import { customJsxAuthoringCatalog } from "../core/component-catalog";
|
||||
|
||||
const repositoryRoot = resolve(import.meta.dirname, "../../../..");
|
||||
const skillReferenceRoot = resolve(repositoryRoot, ".agents/skills/homarr-custom-widget/references");
|
||||
|
||||
describe("generated Custom Widget component references", () => {
|
||||
test("match the canonical static catalog byte for byte", async () => {
|
||||
const generated = renderCustomWidgetComponentReferences(customJsxAuthoringCatalog);
|
||||
const checkedIn = Object.fromEntries(
|
||||
await Promise.all(
|
||||
GENERATED_COMPONENT_REFERENCE_PATHS.map(async (path) => [
|
||||
path,
|
||||
await readFile(resolve(skillReferenceRoot, path), "utf8"),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(checkedIn).toEqual(generated);
|
||||
});
|
||||
|
||||
test("documents catalog versions and the complete component inventory", () => {
|
||||
const generated = renderCustomWidgetComponentReferences(customJsxAuthoringCatalog);
|
||||
const combined = GENERATED_COMPONENT_REFERENCE_PATHS.map((path) => generated[path]).join("\n");
|
||||
|
||||
expect(generated["components.md"]).toContain(`Catalog schema v${customJsxAuthoringCatalog.schemaVersion}`);
|
||||
expect(generated["components.md"]).toContain(`Custom Widget ${customJsxAuthoringCatalog.customWidgetVersion}`);
|
||||
expect(generated["components.md"]).toContain(`Mantine ${customJsxAuthoringCatalog.mantineVersion}`);
|
||||
|
||||
for (const component of customJsxAuthoringCatalog.components)
|
||||
expect(combined, component.name).toContain(component.name);
|
||||
});
|
||||
|
||||
test("keeps detailed records only for Homarr-owned runtime components", () => {
|
||||
const generated = renderCustomWidgetComponentReferences(customJsxAuthoringCatalog);
|
||||
const homarrComponents = customJsxAuthoringCatalog.components.filter(
|
||||
(component) => component.package === "@homarr/widgets",
|
||||
);
|
||||
for (const component of homarrComponents) {
|
||||
const reference = generated["homarr-components.md"];
|
||||
expect(reference).toContain(`<a id="${getComponentReferenceAnchor(component.name)}"></a>`);
|
||||
expect(reference).toContain(`### \`${component.name}\``);
|
||||
for (const prop of component.props) {
|
||||
expect(reference).toContain(`<code>${prop.name}</code>`);
|
||||
expect(reference).toContain(`<code>${escapeHtml(customJsxAuthoringCatalog.types[prop.typeRef] ?? "")}</code>`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps schema, runtime, and security references human-authored", () => {
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("schema.md");
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("runtime.md");
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("security.md");
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-core.md");
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-dates.md");
|
||||
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-charts.md");
|
||||
});
|
||||
});
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("|", "|");
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "../core/ai-prompt";
|
||||
import { CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION } from "../core/ai-prompt";
|
||||
import {
|
||||
buildCustomWidgetAiPromptWithEmbeddedSkill,
|
||||
CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT,
|
||||
CUSTOM_WIDGET_SKILL_FILES,
|
||||
} from "../core/embedded-ai-prompt";
|
||||
|
||||
describe("buildCustomWidgetAiPromptWithEmbeddedSkill", () => {
|
||||
test("stays behind dedicated package exports instead of the core barrel", async () => {
|
||||
const packageRoot = resolve(import.meta.dirname, "../..");
|
||||
const [manifestSource, coreIndexSource] = await Promise.all([
|
||||
readFile(resolve(packageRoot, "package.json"), "utf8"),
|
||||
readFile(resolve(packageRoot, "src/core/index.ts"), "utf8"),
|
||||
]);
|
||||
const manifest = JSON.parse(manifestSource) as { exports: Record<string, string> };
|
||||
|
||||
expect(manifest.exports["./authoring-prompt"]).toBe("./src/core/ai-prompt.ts");
|
||||
expect(manifest.exports["./authoring-resources"]).toBe("./src/core/authoring-resources.ts");
|
||||
expect(manifest.exports["./embedded-authoring-prompt"]).toBe("./src/core/embedded-ai-prompt.ts");
|
||||
expect(coreIndexSource).not.toContain('export * from "./ai-prompt"');
|
||||
expect(coreIndexSource).not.toContain('export * from "./authoring-resources"');
|
||||
expect(coreIndexSource).not.toContain('export * from "./component-catalog"');
|
||||
expect(coreIndexSource).not.toContain('export * from "./component-registry"');
|
||||
expect(coreIndexSource).not.toContain('export * from "./embedded-ai-prompt"');
|
||||
});
|
||||
|
||||
test("embeds the complete release-matched offline authoring bundle", () => {
|
||||
const prompt = buildCustomWidgetAiPromptWithEmbeddedSkill(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
"Create a status widget",
|
||||
);
|
||||
|
||||
expect(prompt.startsWith("Please create this Homarr Custom JSX v2 widget:\n\nCreate a status widget")).toBe(true);
|
||||
expect(prompt).toContain("This clipboard workflow has no Homarr MCP tools, repository access, or local files.");
|
||||
expect(prompt).toContain(CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT);
|
||||
for (const file of CUSTOM_WIDGET_SKILL_FILES.filter(
|
||||
({ path }) => !["references/component-catalog.json", "references/examples.json"].includes(path),
|
||||
)) {
|
||||
expect(prompt).toContain(`--- BEGIN SKILL FILE: ${file.path} ---`);
|
||||
expect(prompt).toContain(file.content.trimEnd());
|
||||
}
|
||||
expect(prompt).toContain('"name":"ActionButton"');
|
||||
expect(prompt).toContain('"name":"SubFetch"');
|
||||
expect(prompt).toContain("RecursiveList");
|
||||
expect(prompt).toContain("--- BEGIN CANONICAL COMPONENT CATALOG ---");
|
||||
expect(prompt).toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
|
||||
expect(prompt.lastIndexOf(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBeGreaterThan(
|
||||
prompt.indexOf("# Homarr Custom Widget offline authoring bundle"),
|
||||
);
|
||||
expect(prompt.length).toBeGreaterThan(500_000);
|
||||
expect(prompt.length).toBeLessThanOrEqual(1_700_000);
|
||||
expect(prompt.endsWith(`${CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL}\nCharacters: ${prompt.length}`)).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps the embedded bundle outside balanced prompt fences for a large existing widget", () => {
|
||||
const prompt = buildCustomWidgetAiPromptWithEmbeddedSkill(
|
||||
undefined,
|
||||
JSON.stringify({ items: Array.from({ length: 2_000 }, (_, index) => ({ index })) }),
|
||||
{ template: "<Text>Large</Text>".repeat(2_000) },
|
||||
"Repair this widget",
|
||||
);
|
||||
const beforeBundle = prompt.slice(0, prompt.indexOf("This clipboard workflow has no Homarr MCP tools"));
|
||||
|
||||
expect(beforeBundle.match(/```/gu)?.length ?? 0).toBe(4);
|
||||
expect(beforeBundle).toContain("Homarr will validate the result after it is pasted into the workbench.");
|
||||
expect(prompt).toContain("# Homarr Custom Widget offline authoring bundle");
|
||||
expect(prompt.length).toBeLessThanOrEqual(1_700_000);
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
```json
|
||||
{
|
||||
"$schema": "homarr-custom-widget-v2",
|
||||
"name": "Pokédex",
|
||||
"description": "Browse Pokémon from PokeAPI, view stats/types/abilities, and keep a list of favorites. Every section can be shown or hidden.",
|
||||
"iconUrl": "https://raw.githubusercontent.com/PokeAPI/media/master/logo/pokeapi_256.png",
|
||||
"sources": [
|
||||
{
|
||||
"id": "default",
|
||||
"name": "PokeAPI",
|
||||
"baseUrl": "https://pokeapi.co/api/v2",
|
||||
"networkScope": "public",
|
||||
"auth": { "type": "none" }
|
||||
}
|
||||
],
|
||||
"requests": [
|
||||
{
|
||||
"id": "list",
|
||||
"sourceId": "default",
|
||||
"kind": "query",
|
||||
"method": "GET",
|
||||
"pathTemplate": "/pokemon",
|
||||
"parameters": { "pokemonLimit": { "type": "number" } },
|
||||
"queryTemplate": { "limit": { "$param": "pokemonLimit" }, "offset": 0 },
|
||||
"auth": "inherit",
|
||||
"minimumBoardPermission": "view",
|
||||
"trigger": "load",
|
||||
"invalidates": []
|
||||
},
|
||||
{
|
||||
"id": "detail",
|
||||
"sourceId": "default",
|
||||
"kind": "query",
|
||||
"method": "GET",
|
||||
"pathTemplate": "/pokemon/{name}",
|
||||
"parameters": { "name": { "type": "string" } },
|
||||
"auth": "inherit",
|
||||
"minimumBoardPermission": "view",
|
||||
"trigger": "manual",
|
||||
"invalidates": []
|
||||
}
|
||||
],
|
||||
"optionsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pokemonLimit": {
|
||||
"type": "number",
|
||||
"title": "Number of Pokémon to load",
|
||||
"minimum": 1,
|
||||
"maximum": 1000,
|
||||
"x-homarr": { "control": "number" }
|
||||
},
|
||||
"showSprite": { "type": "boolean", "title": "Show sprite image", "x-homarr": { "control": "switch" } },
|
||||
"showTypes": { "type": "boolean", "title": "Show type badges", "x-homarr": { "control": "switch" } },
|
||||
"showStats": { "type": "boolean", "title": "Show base stats", "x-homarr": { "control": "switch" } },
|
||||
"showAbilities": { "type": "boolean", "title": "Show abilities", "x-homarr": { "control": "switch" } },
|
||||
"showPhysical": { "type": "boolean", "title": "Show height and weight", "x-homarr": { "control": "switch" } },
|
||||
"showFavoritesBar": {
|
||||
"type": "boolean",
|
||||
"title": "Show favorites-only toggle",
|
||||
"x-homarr": { "control": "switch" }
|
||||
},
|
||||
"accentColor": { "type": "string", "title": "Accent color", "x-homarr": { "control": "color" } }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"defaultOptions": {
|
||||
"pokemonLimit": 151,
|
||||
"showSprite": true,
|
||||
"showTypes": true,
|
||||
"showStats": true,
|
||||
"showAbilities": true,
|
||||
"showPhysical": true,
|
||||
"showFavoritesBar": true,
|
||||
"accentColor": "#e3350d"
|
||||
},
|
||||
"stateSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"selectedPokemon": { "type": "string" },
|
||||
"favorites": { "type": "array", "items": { "type": "string" } },
|
||||
"favoritesOnly": { "type": "boolean" }
|
||||
}
|
||||
},
|
||||
"defaultState": { "selectedPokemon": "", "favorites": [], "favoritesOnly": false },
|
||||
"template": "**HOMARR\_TEMPLATE**"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { HomarrCustomWidgetV2Input } from "../../core/custom-jsx-schema";
|
||||
|
||||
export const PORTAINER_REFERENCE_WIDGET: HomarrCustomWidgetV2Input = {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Portainer containers",
|
||||
description: "Monitor and control Docker containers through Portainer.",
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/portainer.svg",
|
||||
sources: {
|
||||
default: {
|
||||
name: "Portainer",
|
||||
baseUrl: "https://portainer.example.com",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", name: "X-API-Key" },
|
||||
},
|
||||
},
|
||||
requests: {
|
||||
containers: {
|
||||
path: "/api/endpoints/{option:endpointId}/docker/containers/json",
|
||||
query: { all: { $option: "showAll" } },
|
||||
cacheSeconds: 20,
|
||||
},
|
||||
start: {
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/api/endpoints/{option:endpointId}/docker/containers/{param:id}/start",
|
||||
confirmation: "Start this container?",
|
||||
invalidates: ["containers"],
|
||||
},
|
||||
stop: {
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/api/endpoints/{option:endpointId}/docker/containers/{param:id}/stop",
|
||||
confirmation: { title: "Stop container", message: "The service will become unavailable.", destructive: true },
|
||||
invalidates: ["containers"],
|
||||
},
|
||||
restart: {
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/api/endpoints/{option:endpointId}/docker/containers/{param:id}/restart",
|
||||
confirmation: "Restart this container?",
|
||||
invalidates: ["containers"],
|
||||
},
|
||||
},
|
||||
options: {
|
||||
endpointId: { label: "Environment ID", control: "number", default: 2, min: 1 },
|
||||
showAll: { label: "Include stopped containers", control: "switch", default: true },
|
||||
},
|
||||
template: `<Stack gap="md" p="md" h="100%">
|
||||
<Group justify="space-between" align="flex-start">
|
||||
<Stack gap={2}><Group gap="xs"><ThemeIcon color="blue" variant="light"><Icon name="brand-docker" /></ThemeIcon><Title order={3}>Containers</Title></Group><Text size="xs" c="dimmed">Portainer environment {options.endpointId}</Text></Stack>
|
||||
<RefreshButton />
|
||||
</Group>
|
||||
{status.containers?.loading ? <Stack gap="xs"><Skeleton height={68} radius="md" /><Skeleton height={68} radius="md" /><Skeleton height={68} radius="md" /></Stack> : status.containers?.error ? <Alert color="red" title="Portainer is unavailable">{status.containers.error}</Alert> : (data.containers ?? []).length === 0 ? <Alert color="gray" title="No containers">No containers matched this environment.</Alert> : <Stack gap="md">
|
||||
<SimpleGrid cols={{ base: 1, xs: 3 }}>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Total</Text><Text size="xl" fw={700}>{data.containers.length}</Text></Paper>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Running</Text><Text size="xl" fw={700} c="green">{data.containers.filter(container => container.State === "running").length}</Text></Paper>
|
||||
<Paper withBorder p="sm" radius="md"><Text size="xs" c="dimmed">Stopped</Text><Text size="xl" fw={700} c="dimmed">{data.containers.filter(container => container.State !== "running").length}</Text></Paper>
|
||||
</SimpleGrid>
|
||||
<ScrollArea h={230} type="auto"><Stack gap="xs">{data.containers.map(container => <Paper key={container.Id} withBorder p="sm" radius="md"><Group justify="space-between" align="flex-start" wrap="wrap"><Stack gap={3}><Group gap="xs"><Text fw={650}>{container.Names?.[0]?.replace("/", "") ?? container.Id.slice(0, 12)}</Text><Badge color={container.State === "running" ? "green" : "gray"} variant="light">{container.State}</Badge></Group><Text size="xs" c="dimmed" lineClamp={1}>{container.Image}</Text><Text size="xs" c="dimmed">{container.Status}</Text></Stack><Group gap="xs">{container.State === "running" ? <ActionButton requestId="stop" params={{ id: container.Id }} color="red" variant="light">Stop</ActionButton> : <ActionButton requestId="start" params={{ id: container.Id }} color="green" variant="light">Start</ActionButton>}<ActionButton requestId="restart" params={{ id: container.Id }} variant="light">Restart</ActionButton></Group></Group></Paper>)}</Stack></ScrollArea>
|
||||
</Stack>}
|
||||
</Stack>`,
|
||||
};
|
||||
@@ -1,89 +1,52 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import {
|
||||
CUSTOM_WIDGET_STARTER,
|
||||
getImportReview,
|
||||
parseCustomWidgetAiResponse,
|
||||
parseCustomWidgetClipboard,
|
||||
parseCustomWidgetClipboardDetailed,
|
||||
} from "../core/import";
|
||||
} from "../core";
|
||||
|
||||
const response = (manifest: unknown, jsx = "<Text>Ready</Text>") =>
|
||||
`\`\`\`json\n${JSON.stringify(manifest, null, 2)}\n\`\`\`\n\`\`\`jsx\n${jsx}\n\`\`\``;
|
||||
|
||||
describe("Custom Widget imports", () => {
|
||||
it("accepts the canonical raw JSON export", () => {
|
||||
expect(parseCustomWidgetClipboard(JSON.stringify(CUSTOM_WIDGET_STARTER))?.$schema).toBe("homarr-custom-widget-v2");
|
||||
it("accepts exactly one lean manifest and JSX block", () => {
|
||||
const result = parseCustomWidgetAiResponse(response({ ...CUSTOM_WIDGET_STARTER, template: "__HOMARR_TEMPLATE__" }));
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) expect(result.widget.template).toBe("<Text>Ready</Text>");
|
||||
});
|
||||
|
||||
it("combines one widget.json block and one widget.jsx block", () => {
|
||||
const manifest = { ...CUSTOM_WIDGET_STARTER, template: "__HOMARR_TEMPLATE__" };
|
||||
it("rejects the unreleased superseded schema without normalization", () => {
|
||||
const result = parseCustomWidgetAiResponse(
|
||||
`\`\`\`json\n${JSON.stringify(manifest)}\n\`\`\`\n\`\`\`jsx\n<Text>{options.title}</Text>\n\`\`\``,
|
||||
response({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: Object.values(CUSTOM_WIDGET_STARTER.sources),
|
||||
requests: [],
|
||||
optionsSchema: {},
|
||||
defaultOptions: {},
|
||||
template: "__HOMARR_TEMPLATE__",
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({ success: true, widget: { template: "<Text>{options.title}</Text>" } });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes common AI parameter objects but keeps strict imports strict", () => {
|
||||
const request = {
|
||||
id: "detail",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/pokemon/{name}",
|
||||
parameters: { name: { type: "string" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
};
|
||||
const manifest = { ...CUSTOM_WIDGET_STARTER, requests: [request], template: "__HOMARR_TEMPLATE__" };
|
||||
expect(parseCustomWidgetClipboardDetailed(JSON.stringify(manifest)).success).toBe(false);
|
||||
it("reports missing fences and removed local state", () => {
|
||||
expect(parseCustomWidgetAiResponse(JSON.stringify(CUSTOM_WIDGET_STARTER)).success).toBe(false);
|
||||
const result = parseCustomWidgetAiResponse(
|
||||
`\`\`\`json\n${JSON.stringify(manifest)}\n\`\`\`\n\`\`\`jsx\n<Text>Pokemon</Text>\n\`\`\``,
|
||||
response({ ...CUSTOM_WIDGET_STARTER, stateSchema: {}, template: "__HOMARR_TEMPLATE__" }),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
widget: { requests: [{ parameters: { name: "string" } }] },
|
||||
warnings: [{ code: "NORMALIZED_PARAMETER_TYPE" }],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) expect(result.issues.some(({ code }) => code === "REMOVED_LOCAL_STATE")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns multiple actionable issues for the supplied malformed Pokemon response", async () => {
|
||||
const response = await readFile(resolve(import.meta.dirname, "fixtures/pokedex-ai-response.md"), "utf8");
|
||||
const result = parseCustomWidgetAiResponse(response);
|
||||
expect(result).toMatchObject({ success: false });
|
||||
if (result.success) throw new Error("Expected malformed response to fail");
|
||||
expect(result.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "INVALID_JSON" }),
|
||||
expect.objectContaining({ code: "INVALID_JSON_ESCAPE" }),
|
||||
expect.objectContaining({ code: "AI_JSX_BLOCK_REQUIRED" }),
|
||||
expect.objectContaining({ code: "REMOVED_LOCAL_STATE" }),
|
||||
]),
|
||||
);
|
||||
it("returns a capability review from keyed records", () => {
|
||||
const review = getImportReview(CUSTOM_WIDGET_STARTER);
|
||||
expect(review).toMatchObject({ origins: ["https://example.com"], authTypes: ["none"], hasActions: false });
|
||||
});
|
||||
|
||||
it("rejects removed fields, legacy displays, and missing JSX fences explicitly", () => {
|
||||
expect(
|
||||
parseCustomWidgetClipboard(JSON.stringify({ displayType: "raw", displayConfig: { type: "raw" } })),
|
||||
).toBeNull();
|
||||
const result = parseCustomWidgetAiResponse(
|
||||
`\`\`\`json\n${JSON.stringify({ ...CUSTOM_WIDGET_STARTER, stateSchema: {} })}\n\`\`\``,
|
||||
);
|
||||
expect(result).toMatchObject({ success: false });
|
||||
if (result.success) throw new Error("Expected removed state to fail");
|
||||
expect(result.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "REMOVED_LOCAL_STATE" }),
|
||||
expect.objectContaining({ code: "AI_JSX_BLOCK_REQUIRED" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns all useful schema issues instead of a nullable failure", () => {
|
||||
const result = parseCustomWidgetClipboardDetailed(JSON.stringify({ $schema: "homarr-custom-widget-v2" }));
|
||||
expect(result).toMatchObject({ success: false });
|
||||
if (result.success) throw new Error("Expected invalid widget to fail");
|
||||
expect(result.issues.length).toBeGreaterThan(1);
|
||||
expect(result.issues.some((issue) => issue.path?.includes("name"))).toBe(true);
|
||||
it("keeps strict clipboard import compatible with canonical exports", () => {
|
||||
const result = parseCustomWidgetClipboardDetailed(JSON.stringify(CUSTOM_WIDGET_STARTER));
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -39,6 +39,19 @@ describe("shared Custom JSX policy", () => {
|
||||
expect(diagnostics.filter(({ severity }) => severity === "error")).toEqual([]);
|
||||
});
|
||||
|
||||
test("accepts the concise Icon alias used by the AI prompt", () => {
|
||||
expect(validateCustomJsxTemplate('<ThemeIcon><Icon name="brand-docker" /></ThemeIcon>')).toEqual([]);
|
||||
});
|
||||
|
||||
test("accepts common bounded formatting and collection operations", () => {
|
||||
expect(
|
||||
validateCustomJsxTemplate(
|
||||
'<Text>{[1, 2].concat([3]).flatMap(value => [value]).map(value => value.toLocaleString()).join(", ")}</Text>',
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(validateCustomJsxTemplate('<Text>{"b".localeCompare("a")}</Text>')).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([...CUSTOM_JSX_BLOCKED_PROPERTIES])(
|
||||
"blocks reflective property %s in diagnostics and runtime",
|
||||
(property) => {
|
||||
@@ -265,63 +278,36 @@ describe("shared Custom JSX policy", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("supports sequential immutable local bindings in collection callbacks", () => {
|
||||
const template = `<Text>{data.items.map((item) => {
|
||||
const segments = item.url.split("/").filter((part) => part);
|
||||
const identifier = segments.at(-1);
|
||||
const label = item.name.toUpperCase();
|
||||
return <Text key={identifier}>#{identifier} {label}</Text>;
|
||||
})}</Text>`;
|
||||
|
||||
test("supports expression callbacks", () => {
|
||||
const template =
|
||||
'<Text>{data.items.filter((item) => item.visible).map((item) => item.name.toUpperCase()).join(", ")}</Text>';
|
||||
expect(validateCustomJsxTemplate(template).filter(({ severity }) => severity === "error")).toEqual([]);
|
||||
const rendered = renderSafeJsx({
|
||||
template,
|
||||
components: {
|
||||
Text: ((props: { children?: unknown }) => createElement("span", null, props.children as never)) as never,
|
||||
},
|
||||
bindings: { data: { items: [{ name: "bulbasaur", url: "https://pokeapi.co/api/v2/pokemon/1/" }] } },
|
||||
bindings: { data: { items: [{ name: "Bulbasaur", visible: true }] } },
|
||||
});
|
||||
expect(renderToStaticMarkup(rendered.node)).toContain("#1 BULBASAUR");
|
||||
expect(renderToStaticMarkup(rendered.node)).toContain("BULBASAUR");
|
||||
});
|
||||
|
||||
test("supports controlled zero-argument IIFEs for page-level derived values", () => {
|
||||
const template = `{(() => {
|
||||
const visible = data.items.filter((item) => item.visible);
|
||||
return <Text>{visible.map((item) => item.name).join(", ")}</Text>;
|
||||
})()}`;
|
||||
|
||||
test("supports bounded regex string operations", () => {
|
||||
const template = '<Text>{data.name.replace(/[^a-z]/gi, "-")}</Text>';
|
||||
expect(validateCustomJsxTemplate(template).filter(({ severity }) => severity === "error")).toEqual([]);
|
||||
const rendered = renderSafeJsx({
|
||||
template,
|
||||
components: {
|
||||
Text: ((props: { children?: unknown }) => createElement("span", null, props.children as never)) as never,
|
||||
},
|
||||
bindings: {
|
||||
data: {
|
||||
items: [
|
||||
{ name: "Bulbasaur", visible: true },
|
||||
{ name: "Mew", visible: false },
|
||||
],
|
||||
},
|
||||
},
|
||||
bindings: { data: { name: "Bulba saur!" } },
|
||||
});
|
||||
expect(renderToStaticMarkup(rendered.node)).toContain("Bulbasaur");
|
||||
expect(renderToStaticMarkup(rendered.node)).not.toContain("Mew");
|
||||
expect(renderToStaticMarkup(rendered.node)).toContain("Bulba-saur-");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["callback return", "{data.items.map((item) => Number)}"],
|
||||
["safe-block return", "{data.items.map((item) => { const value = item; return Math.round; })}"],
|
||||
["conditional local", "{data.items.map((item) => { const value = true ? Math.round : item; return value; })}"],
|
||||
["IIFE return", "{(() => { const value = 1; return Number; })()}"],
|
||||
])("rejects callable values escaping an authored %s", (_name, template) => {
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("CALLBACK_VALUE_NOT_ALLOWED") }),
|
||||
]),
|
||||
);
|
||||
expect(() => renderSafeJsx({ template, components, bindings: createCustomJsxBindings({ items: [1] }) })).toThrow(
|
||||
"CALLBACK_VALUE_NOT_ALLOWED",
|
||||
test.each(["/(a+)+$/", "/(?<=a)b/", "/(a)\\1/"])("rejects unsafe regex %s", (pattern) => {
|
||||
expect(validateCustomJsxTemplate(`<Text>{${pattern}.test(data.name)}</Text>`)).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining("UNSAFE_REGEX") })]),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -333,14 +319,20 @@ describe("shared Custom JSX policy", () => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test.each([
|
||||
["expression body", "{(() => <Text>value</Text>)()}", "BLOCK_REQUIRES_FINAL_RETURN"],
|
||||
["optional call", "{(() => { const value = 1; return <Text>{value}</Text>; })?.()}", "CALL_TARGET_NOT_ALLOWED"],
|
||||
])("rejects unsupported derived-value IIFE form: %s", (_name, template, code) => {
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining(code) })]),
|
||||
);
|
||||
expect(() => renderSafeJsx({ template, components, bindings })).toThrow();
|
||||
test("rejects IIFEs and callback statement blocks", () => {
|
||||
for (const template of [
|
||||
"{(() => <Text>value</Text>)()}",
|
||||
"{data.items.map((item) => { const value = item; return value; })}",
|
||||
]) {
|
||||
expect(
|
||||
validateCustomJsxTemplate(template).some(
|
||||
({ message }) => message.includes("IIFE") || message.includes("UNSUPPORTED_BLOCK_STATEMENT"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(() =>
|
||||
renderSafeJsx({ template, components, bindings: createCustomJsxBindings({ items: [1] }) }),
|
||||
).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizes duplicate callback parameter parse diagnostics", () => {
|
||||
@@ -355,47 +347,6 @@ describe("shared Custom JSX policy", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[
|
||||
"let mutation",
|
||||
`{data.items.map((item) => { let value = item; return <Text>{value}</Text>; })}`,
|
||||
"INVALID_LOCAL_DECLARATION",
|
||||
],
|
||||
[
|
||||
"destructuring",
|
||||
`{data.items.map((item) => { const { name } = item; return <Text>{name}</Text>; })}`,
|
||||
"INVALID_LOCAL_DECLARATION",
|
||||
],
|
||||
[
|
||||
"reserved binding",
|
||||
`{data.items.map((item) => { const data = item; return <Text>{data}</Text>; })}`,
|
||||
"RESERVED_LOCAL_BINDING",
|
||||
],
|
||||
[
|
||||
"stored callback",
|
||||
`{data.items.map((item) => { const callback = () => item; return <Text>{item}</Text>; })}`,
|
||||
"CALLBACK_VALUE_NOT_ALLOWED",
|
||||
],
|
||||
[
|
||||
"unsupported if",
|
||||
`{data.items.map((item) => { if (item) return <Text />; return <Text />; })}`,
|
||||
"UNSUPPORTED_BLOCK_STATEMENT",
|
||||
],
|
||||
["missing final return", `{data.items.map((item) => { const value = item; })}`, "BLOCK_REQUIRES_FINAL_RETURN"],
|
||||
["return-only block", `{data.items.map((item) => { return <Text>{item}</Text>; })}`, "INVALID_LOCAL_DECLARATION"],
|
||||
[
|
||||
"parameterized IIFE",
|
||||
`{((value) => { const label = value; return <Text>{label}</Text>; })()}`,
|
||||
"CALLBACK_VALUE_NOT_ALLOWED",
|
||||
],
|
||||
["IIFE arguments", `{((value) => { return <Text>{value}</Text>; })(data.value)}`, "CALLBACK_VALUE_NOT_ALLOWED"],
|
||||
])("rejects unsafe block grammar: %s", (_name, template, code) => {
|
||||
expect(validateCustomJsxTemplate(template).some(({ message }) => message.includes(code))).toBe(true);
|
||||
expect(() =>
|
||||
renderSafeJsx({ template, components, bindings: { data: { items: [{ name: "Bulbasaur" }], value: "value" } } }),
|
||||
).toThrow(code);
|
||||
});
|
||||
|
||||
test("rejects callback values outside controlled call sites", () => {
|
||||
const template = "<Text>{(item) => item}</Text>";
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
@@ -410,62 +361,18 @@ describe("shared Custom JSX policy", () => {
|
||||
"keeps blocked lexical binding %s aligned between diagnostics and runtime",
|
||||
(name) => {
|
||||
const parameterTemplate = `{data.items.map((${name}) => <Text>{${name}}</Text>)}`;
|
||||
const localTemplate = `{data.items.map((item) => { const ${name} = item; return <Text>{${name}}</Text>; })}`;
|
||||
|
||||
for (const template of [parameterTemplate, localTemplate]) {
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("INVALID_LOCAL_DECLARATION") }),
|
||||
]),
|
||||
);
|
||||
expect(() => renderSafeJsx({ template, components, bindings: { data: { items: [1] } } })).toThrow(
|
||||
"INVALID_LOCAL_DECLARATION",
|
||||
);
|
||||
}
|
||||
expect(validateCustomJsxTemplate(parameterTemplate)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("INVALID_LOCAL_DECLARATION") }),
|
||||
]),
|
||||
);
|
||||
expect(() =>
|
||||
renderSafeJsx({ template: parameterTemplate, components, bindings: { data: { items: [1] } } }),
|
||||
).toThrow("INVALID_LOCAL_DECLARATION");
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects host and interpreter functions stored in local const bindings", () => {
|
||||
const template = `{data.items.map((item) => {
|
||||
const round = Math.round;
|
||||
return <Text>{item}</Text>;
|
||||
})}`;
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("CALLBACK_VALUE_NOT_ALLOWED") }),
|
||||
]),
|
||||
);
|
||||
expect(() =>
|
||||
renderSafeJsx({
|
||||
template,
|
||||
components,
|
||||
bindings: { data: { items: [1] }, Math },
|
||||
}),
|
||||
).toThrow("CALLBACK_VALUE_NOT_ALLOWED");
|
||||
});
|
||||
|
||||
test("maps parse failures to missing and duplicate local binding diagnostics", () => {
|
||||
expect(
|
||||
validateCustomJsxTemplate(`{data.items.map((item) => { const value; return <Text>{item}</Text>; })}`),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("LOCAL_BINDING_REQUIRES_INITIALIZER") }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
validateCustomJsxTemplate(
|
||||
`{data.items.map((item) => { const value = item; const value = item; return <Text>{value}</Text>; })}`,
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("DUPLICATE_LOCAL_BINDING") }),
|
||||
]),
|
||||
);
|
||||
expect(validateCustomJsxTemplate('<Text>{"const fake;" + }</Text>')[0]?.message).not.toContain(
|
||||
"LOCAL_BINDING_REQUIRES_INITIALIZER",
|
||||
);
|
||||
});
|
||||
|
||||
test.each(['{data.items["ma" + "p"]((item) => item).join(",")}', '{data.items[`map`]((item) => item).join(",")}'])(
|
||||
"keeps analyzer and runtime aligned for static computed collection callbacks",
|
||||
(template) => {
|
||||
@@ -475,19 +382,4 @@ describe("shared Custom JSX policy", () => {
|
||||
).not.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
["assignment", `{data.items.map((item) => { const value = (item = 2); return <Text>{value}</Text>; })}`],
|
||||
["update", `{data.items.map((item) => { const value = item++; return <Text>{value}</Text>; })}`],
|
||||
["new", `{data.items.map((item) => { const value = new Date(item); return <Text>{value}</Text>; })}`],
|
||||
])("uses precise safe-block diagnostics for %s expressions", (_name, template) => {
|
||||
expect(validateCustomJsxTemplate(template)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("UNSUPPORTED_BLOCK_STATEMENT") }),
|
||||
]),
|
||||
);
|
||||
expect(() => renderSafeJsx({ template, components, bindings: { data: { items: [1] }, Date } })).toThrow(
|
||||
"UNSUPPORTED_BLOCK_STATEMENT",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
customWidgetDefinitionSchema,
|
||||
customWidgetOptionControls,
|
||||
customWidgetOptionSchema,
|
||||
getCustomWidgetDefaultOptions,
|
||||
validateCustomWidgetOptions,
|
||||
} from "../core";
|
||||
|
||||
const defaultsByControl: Record<(typeof customWidgetOptionControls)[number], unknown> = {
|
||||
text: "value",
|
||||
textarea: "long value",
|
||||
number: 2,
|
||||
switch: true,
|
||||
select: "one",
|
||||
multiSelect: ["one"],
|
||||
slider: 50,
|
||||
date: "2026-07-21",
|
||||
time: "12:30",
|
||||
color: "#228be6",
|
||||
icon: "server",
|
||||
url: "https://example.com",
|
||||
duration: 30,
|
||||
timeZone: "Europe/Paris",
|
||||
json: { nested: true },
|
||||
};
|
||||
|
||||
describe("lean Custom Widget options", () => {
|
||||
it("treats an empty dynamic choices item path as the response root", () => {
|
||||
expect(
|
||||
customWidgetOptionSchema.parse({
|
||||
label: "Printer",
|
||||
control: "select",
|
||||
default: "",
|
||||
choicesFrom: {
|
||||
request: "printers",
|
||||
itemsPath: "",
|
||||
valuePath: "id",
|
||||
labelPath: "name",
|
||||
},
|
||||
}).choicesFrom?.itemsPath,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(customWidgetOptionControls)("accepts the %s control and infers its default type", (control) => {
|
||||
const option = {
|
||||
label: control,
|
||||
control,
|
||||
default: defaultsByControl[control],
|
||||
...(["select", "multiSelect"].includes(control) ? { choices: [{ label: "One", value: "one" }] } : {}),
|
||||
};
|
||||
expect(customWidgetOptionSchema.safeParse(option).success).toBe(true);
|
||||
});
|
||||
|
||||
it("builds and validates a complete instance configuration", () => {
|
||||
const options = Object.fromEntries(
|
||||
customWidgetOptionControls.map((control) => [
|
||||
control,
|
||||
customWidgetOptionSchema.parse({
|
||||
label: control,
|
||||
control,
|
||||
default: defaultsByControl[control],
|
||||
...(["select", "multiSelect"].includes(control) ? { choices: [{ label: "One", value: "one" }] } : {}),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const configuration = getCustomWidgetDefaultOptions(options);
|
||||
expect(validateCustomWidgetOptions(options, configuration)).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects duplicate static choice values", () => {
|
||||
expect(
|
||||
customWidgetOptionSchema.safeParse({
|
||||
label: "Environment",
|
||||
control: "select",
|
||||
default: "prod",
|
||||
choices: [
|
||||
{ label: "Production", value: "prod" },
|
||||
{ label: "Duplicate", value: "prod" },
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps dynamic choices on a load query without invocation parameters", () => {
|
||||
const result = customWidgetDefinitionSchema.safeParse({
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Dynamic options",
|
||||
sources: { default: { baseUrl: "https://example.com", networkScope: "public", auth: "none" } },
|
||||
requests: { environments: { path: "/environments" } },
|
||||
options: {
|
||||
environment: {
|
||||
label: "Environment",
|
||||
control: "select",
|
||||
default: "",
|
||||
choicesFrom: { request: "environments", valuePath: "id", labelPath: "name" },
|
||||
},
|
||||
},
|
||||
template: "<Text>{options.environment}</Text>",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,89 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { customWidgetDefinitionSchema } from "../core";
|
||||
import { CustomWidgetPreviewSessionService } from "../server";
|
||||
import type { CreatePreviewSessionInput } from "../server";
|
||||
|
||||
function createHarness() {
|
||||
let now = 1_000;
|
||||
let id = 0;
|
||||
const service = new CustomWidgetPreviewSessionService({
|
||||
createId: () => `id-${++id}`,
|
||||
encrypt: (value) => `encrypted:${value}`,
|
||||
decrypt: (value) => value.replace("encrypted:", ""),
|
||||
now: () => now,
|
||||
});
|
||||
return {
|
||||
service,
|
||||
advance: (milliseconds: number) => {
|
||||
now += milliseconds;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const input: CreatePreviewSessionInput = {
|
||||
userId: "user-1",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "API",
|
||||
baseUrl: "https://example.com/api",
|
||||
auth: { type: "bearer" },
|
||||
networkScope: "public",
|
||||
},
|
||||
],
|
||||
secrets: [{ sourceId: "default", kind: "apiKey", value: "secret" }],
|
||||
requests: [],
|
||||
const definition = customWidgetDefinitionSchema.parse({
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Preview",
|
||||
template: "<Text>Preview</Text>",
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
options: {},
|
||||
};
|
||||
sources: { default: { baseUrl: "https://example.com", networkScope: "public", auth: "bearer" } },
|
||||
requests: { data: { path: "/data" } },
|
||||
options: { limit: { label: "Limit", control: "number", default: 10 } },
|
||||
template: "<Text>{data.data?.name}</Text>",
|
||||
});
|
||||
|
||||
describe("preview session service", () => {
|
||||
it("stores secrets encrypted and returns them only through the decrypting boundary", async () => {
|
||||
const { service } = createHarness();
|
||||
const created = await service.create(input);
|
||||
const session = await service.get(created.id, input.userId);
|
||||
expect(session.secrets[0]?.value).toBe("encrypted:secret");
|
||||
describe("preview sessions", () => {
|
||||
it("stores keyed definitions and encrypted secrets", async () => {
|
||||
let id = 0;
|
||||
const service = new CustomWidgetPreviewSessionService({
|
||||
createId: () => `id-${++id}`,
|
||||
encrypt: (value) => `encrypted:${value}`,
|
||||
decrypt: (value) => value.replace("encrypted:", ""),
|
||||
now: () => 1_000,
|
||||
});
|
||||
const created = await service.create({
|
||||
userId: "user",
|
||||
sources: definition.sources,
|
||||
requests: definition.requests,
|
||||
name: definition.name,
|
||||
template: definition.template,
|
||||
optionDefinitions: definition.options,
|
||||
options: { limit: 10 },
|
||||
secrets: [{ sourceId: "default", kind: "apiKey", value: "secret" }],
|
||||
});
|
||||
const session = await service.get(created.id, "user");
|
||||
expect(session.requests.data?.path).toBe("/data");
|
||||
expect(session.secrets[0]?.value).not.toBe("secret");
|
||||
expect(service.getSecrets(session, "default")).toEqual([{ kind: "apiKey", value: "secret" }]);
|
||||
});
|
||||
|
||||
it("stores the selected instance options for load-query bindings", async () => {
|
||||
const { service } = createHarness();
|
||||
const created = await service.create({ ...input, options: { environmentId: 7 } });
|
||||
const session = await service.get(created.id, input.userId);
|
||||
expect(session.options).toEqual({ environmentId: 7 });
|
||||
});
|
||||
|
||||
it("isolates sessions by user and expires them after ten minutes", async () => {
|
||||
const { service, advance } = createHarness();
|
||||
const created = await service.create(input);
|
||||
await expect(service.get(created.id, "other-user")).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
const second = await service.create(input);
|
||||
advance(10 * 60_000 + 1);
|
||||
await expect(service.get(second.id, input.userId)).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("updates live-action approval and caps the newest-first journal", async () => {
|
||||
const { service } = createHarness();
|
||||
const created = await service.create(input);
|
||||
const approved = await service.setLiveActions(created.id, input.userId, true);
|
||||
expect(approved.liveActions).toBe(true);
|
||||
const session = await service.get(created.id, input.userId);
|
||||
for (let index = 0; index < 52; index += 1) {
|
||||
await service.appendJournal(session, {
|
||||
requestId: `request-${index}`,
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/data",
|
||||
status: 200,
|
||||
durationMs: 1,
|
||||
simulated: false,
|
||||
});
|
||||
}
|
||||
const journal = await service.getJournal(created.id, input.userId);
|
||||
expect(journal).toHaveLength(50);
|
||||
expect(journal[0]?.requestId).toBe("request-51");
|
||||
expect(journal.at(-1)?.requestId).toBe("request-2");
|
||||
it("keeps journal paths redacted and bounded to the session", async () => {
|
||||
let id = 0;
|
||||
const service = new CustomWidgetPreviewSessionService({
|
||||
createId: () => `id-${++id}`,
|
||||
encrypt: String,
|
||||
decrypt: String,
|
||||
});
|
||||
const created = await service.create({
|
||||
userId: "user",
|
||||
sources: definition.sources,
|
||||
requests: definition.requests,
|
||||
name: definition.name,
|
||||
template: definition.template,
|
||||
optionDefinitions: definition.options,
|
||||
options: { limit: 10 },
|
||||
secrets: [],
|
||||
});
|
||||
const session = await service.get(created.id, "user");
|
||||
await service.appendJournal(session, {
|
||||
requestId: "data",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
path: "/data",
|
||||
status: 200,
|
||||
durationMs: 5,
|
||||
simulated: false,
|
||||
});
|
||||
expect((await service.getJournal(created.id, "user"))[0]).toMatchObject({ path: "/data", status: 200 });
|
||||
});
|
||||
});
|
||||
@@ -1,330 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, createElement } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { validateCustomJsxTemplate } from "../jsx/analyzer";
|
||||
import { Budget, DEFAULT_BUDGETS } from "../jsx/interpreter-foundation";
|
||||
import { SafeJsxError } from "../jsx/interpreter-foundation";
|
||||
import { renderSafeJsx } from "../jsx/interpreter";
|
||||
import { buildTrustedRecursiveList, TrustedRecursiveList } from "../jsx/recursive-list";
|
||||
|
||||
describe("RecursiveList", () => {
|
||||
test("renders arbitrary-depth data through the trusted template slot", () => {
|
||||
const template = `<RecursiveList data={data.chain} childrenPath="children" keyPath="name" defaultExpandedDepth={16}>
|
||||
{(node, meta) => {
|
||||
const label = node.name.toUpperCase();
|
||||
return <Text>{meta.depth}: {label}</Text>;
|
||||
}}
|
||||
</RecursiveList>`;
|
||||
expect(validateCustomJsxTemplate(template).filter(({ severity }) => severity === "error")).toEqual([]);
|
||||
const rendered = renderSafeJsx({
|
||||
template,
|
||||
components: {
|
||||
RecursiveList: TrustedRecursiveList as never,
|
||||
Text: ((props: { children?: unknown }) => createElement("span", null, props.children as never)) as never,
|
||||
},
|
||||
bindings: { data: { chain: deepTree(8) } },
|
||||
});
|
||||
const html = renderToStaticMarkup(createElement(MantineProvider, null, rendered.node));
|
||||
expect(html).toContain("0: LEVEL-0");
|
||||
expect(html).toContain("7: LEVEL-7");
|
||||
expect(html).toContain('role="tree"');
|
||||
expect(html).toContain('role="treeitem"');
|
||||
expect(html).toContain('aria-expanded="true"');
|
||||
});
|
||||
|
||||
test("contains malformed children, cycles, depth limits, and node limits", () => {
|
||||
const cycle: Record<string, unknown> = { name: "cycle" };
|
||||
cycle.children = [cycle];
|
||||
const malformed = { name: "malformed", children: "not-an-array" };
|
||||
const warnings = new Set<string>();
|
||||
const nodes = buildTrustedRecursiveList({
|
||||
data: [cycle, malformed],
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxDepth: 2,
|
||||
maxNodes: 20,
|
||||
warnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: (node) => String((node as { name: string }).name),
|
||||
});
|
||||
expect(nodes).toHaveLength(2);
|
||||
expect(nodes[0]?.children?.[0]?.label).toBeTruthy();
|
||||
expect(nodes[1]?.children?.[0]?.label).toBeTruthy();
|
||||
expect([...warnings]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("RECURSIVE_LIST_CYCLE"),
|
||||
expect.stringContaining("RECURSIVE_LIST_INVALID_CHILDREN"),
|
||||
]),
|
||||
);
|
||||
|
||||
const cappedWarnings = new Set<string>();
|
||||
const capped = buildTrustedRecursiveList({
|
||||
data: Array.from({ length: 100 }, (_, index) => (index % 2 === 0 ? index : { name: `node-${index}` })),
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxNodes: 4,
|
||||
warnings: cappedWarnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: () => null,
|
||||
});
|
||||
expect(capped).toHaveLength(4);
|
||||
expect(countTreeNodes(capped)).toBe(4);
|
||||
expect([...cappedWarnings]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("RECURSIVE_LIST_INVALID_NODE"),
|
||||
expect.stringContaining("RECURSIVE_LIST_NODE_LIMIT"),
|
||||
]),
|
||||
);
|
||||
|
||||
const exactWarnings = new Set<string>();
|
||||
const exact = buildTrustedRecursiveList({
|
||||
data: Array.from({ length: 4 }, (_, index) => ({ name: `exact-${index}` })),
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxNodes: 4,
|
||||
warnings: exactWarnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: (node) => (node as { name: string }).name,
|
||||
});
|
||||
expect(exact).toHaveLength(4);
|
||||
expect([...exactWarnings].some((warning) => warning.includes("NODE_LIMIT"))).toBe(false);
|
||||
|
||||
const oneRoot = buildTrustedRecursiveList({
|
||||
data: { name: "only" },
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxNodes: 1,
|
||||
warnings: new Set(),
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: (node) => (node as { name: string }).name,
|
||||
});
|
||||
expect(oneRoot).toHaveLength(1);
|
||||
expect(oneRoot[0]?.label).toBe("only");
|
||||
|
||||
const nestedWarnings = new Set<string>();
|
||||
const nestedCapped = buildTrustedRecursiveList({
|
||||
data: [{ name: "malformed", children: "not-an-array" }, { name: "later" }],
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxNodes: 2,
|
||||
warnings: nestedWarnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: (node) => (node as { name: string }).name,
|
||||
});
|
||||
expect(countTreeNodes(nestedCapped)).toBe(2);
|
||||
expect([...nestedWarnings]).toEqual(expect.arrayContaining([expect.stringContaining("RECURSIVE_LIST_NODE_LIMIT")]));
|
||||
|
||||
const depthWarnings = new Set<string>();
|
||||
const depthLimited = buildTrustedRecursiveList({
|
||||
data: deepTree(8),
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
maxDepth: 2,
|
||||
warnings: depthWarnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: () => null,
|
||||
});
|
||||
expect(depthLimited[0]?.children?.[0]?.children?.[0]?.label).toBeTruthy();
|
||||
expect([...depthWarnings]).toEqual(expect.arrayContaining([expect.stringContaining("RECURSIVE_LIST_DEPTH_LIMIT")]));
|
||||
});
|
||||
|
||||
test("rejects unsafe paths and invalid authored slots", () => {
|
||||
const warnings = new Set<string>();
|
||||
const invalidPath = buildTrustedRecursiveList({
|
||||
data: { name: "root" },
|
||||
childrenPath: "__proto__.children",
|
||||
keyPath: "name",
|
||||
warnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: () => null,
|
||||
});
|
||||
expect(invalidPath).toHaveLength(1);
|
||||
expect([...warnings]).toEqual(expect.arrayContaining([expect.stringContaining("RECURSIVE_LIST_INVALID_PATH")]));
|
||||
expect(
|
||||
validateCustomJsxTemplate(
|
||||
'<RecursiveList data={data.tree} childrenPath="children" keyPath="name"><Text>Unsafe</Text></RecursiveList>',
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ message: expect.stringContaining("RECURSIVE_LIST_TEMPLATE_REQUIRED") }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
validateCustomJsxTemplate(
|
||||
"<RecursiveList data={data.tree} childrenPath={3} keyPath={false}>{(node) => node.name}</RecursiveList>",
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining("INVALID_PROP_VALUE") })]),
|
||||
);
|
||||
expect(
|
||||
validateCustomJsxTemplate(
|
||||
'<RecursiveList data={data.tree} childrenPath="children" keyPath="name" maxNodes={1.5}>{(node) => node.name}</RecursiveList>',
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining("INVALID_PROP_VALUE") })]),
|
||||
);
|
||||
});
|
||||
|
||||
test("uses namespaced primitive keys and stable path fallbacks", () => {
|
||||
const warnings = new Set<string>();
|
||||
const nodes = buildTrustedRecursiveList({
|
||||
data: [{ id: 1 }, { id: "1" }, { id: true }, { id: "duplicate" }, { id: "duplicate" }, {}],
|
||||
childrenPath: "children",
|
||||
keyPath: "id",
|
||||
warnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: () => null,
|
||||
});
|
||||
expect(nodes.map(({ value }) => value)).toEqual([
|
||||
"key:number:1",
|
||||
"key:string:1",
|
||||
"key:boolean:true",
|
||||
"key:string:duplicate",
|
||||
"path:4",
|
||||
"path:5",
|
||||
]);
|
||||
expect([...warnings]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("RECURSIVE_LIST_DUPLICATE_KEY"),
|
||||
expect.stringContaining("RECURSIVE_LIST_MISSING_KEY"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("contains ordinary branch errors even when their text resembles a budget failure", () => {
|
||||
const warnings = new Set<string>();
|
||||
const nodes = buildTrustedRecursiveList({
|
||||
data: { name: "root" },
|
||||
childrenPath: "children",
|
||||
keyPath: "name",
|
||||
warnings,
|
||||
budget: new Budget(DEFAULT_BUDGETS),
|
||||
render: () => {
|
||||
throw new SafeJsxError("API field exceeded the operation limit yesterday");
|
||||
},
|
||||
});
|
||||
expect(nodes).toHaveLength(1);
|
||||
expect(nodes[0]?.label).toBeTruthy();
|
||||
expect([...warnings]).toEqual(expect.arrayContaining([expect.stringContaining("RECURSIVE_LIST_BRANCH_ERROR")]));
|
||||
});
|
||||
|
||||
test("diagnoses unsafe spread props and consumes unsupported bind without crashing", () => {
|
||||
const template = `<RecursiveList {...data.props} bind="tree" data={data.tree} childrenPath="children" keyPath="name">
|
||||
{(node) => <Text>{node.name}</Text>}
|
||||
</RecursiveList>`;
|
||||
const rendered = renderSafeJsx({
|
||||
template,
|
||||
components: {
|
||||
RecursiveList: TrustedRecursiveList as never,
|
||||
Text: ((props: { children?: unknown }) => createElement("span", null, props.children as never)) as never,
|
||||
},
|
||||
bindings: {
|
||||
data: {
|
||||
tree: { name: "root" },
|
||||
props: { onClick: () => undefined, href: "javascript:alert(1)" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(rendered.warnings).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("BINDING_UNAVAILABLE"),
|
||||
expect.stringContaining("BLOCKED_CAPABILITY"),
|
||||
expect.stringContaining("INVALID_PROP_VALUE"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("contains a branch render error and resets it when a corrected node model arrives", async () => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
window.matchMedia = vi.fn().mockImplementation(() => ({
|
||||
matches: false,
|
||||
media: "",
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const BrokenLabel = () => {
|
||||
throw new Error("broken label");
|
||||
};
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<TrustedRecursiveList
|
||||
nodes={[
|
||||
{ value: "broken", label: <BrokenLabel /> },
|
||||
{ value: "healthy", label: "Healthy sibling" },
|
||||
]}
|
||||
/>
|
||||
</MantineProvider>,
|
||||
);
|
||||
});
|
||||
expect(host.textContent).toContain("RECURSIVE_LIST_BRANCH_RENDER_ERROR");
|
||||
expect(host.textContent).toContain("Healthy sibling");
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<TrustedRecursiveList nodes={[{ value: "recovered", label: "Recovered" }]} />
|
||||
</MantineProvider>,
|
||||
);
|
||||
});
|
||||
expect(host.textContent).toContain("Recovered");
|
||||
expect(host.textContent).not.toContain("RECURSIVE_LIST_RENDER_ERROR");
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
consoleError.mockRestore();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("shares the parent interpreter operation budget across every recursive callback", () => {
|
||||
const template = `<RecursiveList data={data.chain} childrenPath="children" keyPath="name" defaultExpandedDepth={16}>
|
||||
{(node) => {
|
||||
const label = node.name;
|
||||
return <Text>{label}</Text>;
|
||||
}}
|
||||
</RecursiveList>`;
|
||||
expect(() =>
|
||||
renderSafeJsx({
|
||||
template,
|
||||
components: {
|
||||
RecursiveList: TrustedRecursiveList as never,
|
||||
Text: (() => null) as never,
|
||||
},
|
||||
bindings: { data: { chain: deepTree(8) } },
|
||||
budgets: { maxOperations: 30 },
|
||||
}),
|
||||
).toThrow("operation limit");
|
||||
});
|
||||
});
|
||||
|
||||
function deepTree(depth: number) {
|
||||
const root: { name: string; children?: unknown[] } = { name: "level-0" };
|
||||
let current = root;
|
||||
for (let index = 1; index < depth; index += 1) {
|
||||
const child: { name: string; children?: unknown[] } = { name: `level-${index}` };
|
||||
current.children = [child];
|
||||
current = child;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
function countTreeNodes(nodes: readonly { children?: readonly unknown[] }[]): number {
|
||||
return nodes.reduce(
|
||||
(count, node) => count + 1 + countTreeNodes((node.children ?? []) as readonly { children?: readonly unknown[] }[]),
|
||||
0,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema, parseCustomWidgetAiResponse } from "../core";
|
||||
import { collectCustomWidgetRequestReferences } from "../core/request-schema";
|
||||
import { PORTAINER_REFERENCE_WIDGET } from "./fixtures/reference-widgets";
|
||||
|
||||
describe("reference widget capabilities", () => {
|
||||
it("validates a full Pokédex with list and manual detail requests", () => {
|
||||
const pokedex = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-pokedex");
|
||||
expect(pokedex).toBeDefined();
|
||||
const parsed = customWidgetDefinitionSchema.parse(pokedex?.widget);
|
||||
expect(parsed.requests.pokemon?.trigger).toBe("load");
|
||||
expect(parsed.requests.detail?.trigger).toBe("manual");
|
||||
});
|
||||
|
||||
it("round-trips the full Pokédex through the exact two-block AI paste format", () => {
|
||||
const pokedex = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-pokedex")?.widget;
|
||||
if (!pokedex) throw new Error("Pokédex seed was not found");
|
||||
const { template, ...manifest } = pokedex;
|
||||
const parsed = parseCustomWidgetAiResponse(
|
||||
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
|
||||
);
|
||||
expect(parsed.success).toBe(true);
|
||||
if (parsed.success) expect(parsed.widget.template).toBe(template);
|
||||
});
|
||||
|
||||
it("validates a polished Portainer dashboard with start, stop, and restart actions", () => {
|
||||
const parsed = customWidgetDefinitionSchema.parse(PORTAINER_REFERENCE_WIDGET);
|
||||
expect(parsed.sources.default?.auth).toEqual({ type: "apiKeyHeader", name: "X-API-Key" });
|
||||
expect(Object.keys(parsed.requests)).toEqual(["containers", "start", "stop", "restart"]);
|
||||
for (const action of ["start", "stop", "restart"] as const) {
|
||||
const request = parsed.requests[action];
|
||||
if (!request) throw new Error(`Portainer ${action} request was not found`);
|
||||
expect(request.kind).toBe("action");
|
||||
expect(request.invalidates).toEqual(["containers"]);
|
||||
expect([...collectCustomWidgetRequestReferences(request).params]).toEqual(["id"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips the Portainer dashboard through AI paste", () => {
|
||||
const { template, ...manifest } = PORTAINER_REFERENCE_WIDGET;
|
||||
const parsed = parseCustomWidgetAiResponse(
|
||||
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
|
||||
);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,97 +1,84 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveCustomWidgetOptionsBinding } from "../core";
|
||||
import type { CustomJsxRequest } from "../core";
|
||||
import { hashRuntimeParams, renderRequestBody, renderRequestTarget, validateRuntimeParams } from "../server";
|
||||
import { customJsxRequestSchema } from "../core";
|
||||
import { renderRequestBody, renderRequestTarget, resolveCustomWidgetRequestValues } from "../server";
|
||||
|
||||
const request: CustomJsxRequest = {
|
||||
id: "device",
|
||||
sourceId: "default",
|
||||
const request = customJsxRequestSchema.parse({
|
||||
kind: "action",
|
||||
method: "PATCH",
|
||||
pathTemplate: "/devices/{device}/state",
|
||||
parameters: { device: "string", enabled: "boolean", level: "number" },
|
||||
bodyTemplate: { enabled: { $param: "enabled" }, nested: { level: { $param: "level" } } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
queryTemplate: { verbose: true, level: { $param: "level" } },
|
||||
};
|
||||
method: "POST",
|
||||
path: "/devices/{option:room}/{param:id}",
|
||||
query: { verbose: true, level: { $param: "level" } },
|
||||
body: { enabled: { $param: "enabled" }, room: { $option: "room" } },
|
||||
});
|
||||
|
||||
describe("named request manifest rendering", () => {
|
||||
it("validates exact parameter names and declared primitive types", () => {
|
||||
expect(() => validateRuntimeParams(request, { device: "lamp", enabled: true, level: 5 })).not.toThrow();
|
||||
expect(() => validateRuntimeParams(request, { device: "lamp", enabled: true })).toThrow("match the manifest");
|
||||
expect(() => validateRuntimeParams(request, { device: "lamp", enabled: true, level: "5" })).toThrow(
|
||||
"must be number",
|
||||
describe("lean request bindings", () => {
|
||||
it("infers and resolves option and invocation references", () => {
|
||||
const values = resolveCustomWidgetRequestValues(
|
||||
request,
|
||||
{ room: "office" },
|
||||
{ id: "lamp/1", level: 5, enabled: true },
|
||||
);
|
||||
expect(renderRequestTarget("https://example.com/api/", request, values).toString()).toBe(
|
||||
"https://example.com/api/devices/office/lamp%2F1?verbose=true&level=5",
|
||||
);
|
||||
expect(JSON.parse(renderRequestBody(request, values) ?? "null")).toEqual({ enabled: true, room: "office" });
|
||||
});
|
||||
|
||||
it("encodes path placeholders and preserves JSON parameter types", () => {
|
||||
const params = { device: "living room/1", enabled: true, level: 5 };
|
||||
expect(renderRequestTarget("https://example.com/api", request, params).pathname).toBe(
|
||||
"/devices/living%20room%2F1/state",
|
||||
it("rejects missing and extra invocation params", () => {
|
||||
expect(() => resolveCustomWidgetRequestValues(request, { room: "office" }, { id: "lamp", level: 5 })).toThrow(
|
||||
"do not match",
|
||||
);
|
||||
expect(renderRequestTarget("https://example.com/api", request, params).searchParams.get("level")).toBe("5");
|
||||
expect(JSON.parse(renderRequestBody(request.bodyTemplate, params) ?? "null")).toEqual({
|
||||
enabled: true,
|
||||
nested: { level: 5 },
|
||||
});
|
||||
|
||||
const camelCaseRequest: CustomJsxRequest = {
|
||||
...request,
|
||||
pathTemplate: "/endpoints/{endpointId}",
|
||||
parameters: { endpointId: "string" },
|
||||
queryTemplate: undefined,
|
||||
bodyTemplate: undefined,
|
||||
};
|
||||
expect(renderRequestTarget("https://example.com", camelCaseRequest, { endpointId: "local/1" }).pathname).toBe(
|
||||
"/endpoints/local%2F1",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unresolved or malformed placeholders", () => {
|
||||
expect(() =>
|
||||
renderRequestTarget(
|
||||
"https://example.com",
|
||||
{ ...request, pathTemplate: "/{missing}" },
|
||||
{ device: "lamp", enabled: true, level: 5 },
|
||||
resolveCustomWidgetRequestValues(
|
||||
request,
|
||||
{ room: "office" },
|
||||
{ id: "lamp", level: 5, enabled: true, extra: true },
|
||||
),
|
||||
).toThrow("Unknown path parameter");
|
||||
expect(() =>
|
||||
renderRequestTarget(
|
||||
"https://example.com",
|
||||
{ ...request, pathTemplate: "/{1invalid}" },
|
||||
{ device: "lamp", enabled: true, level: 5 },
|
||||
),
|
||||
).toThrow("invalid placeholder");
|
||||
).toThrow("do not match");
|
||||
});
|
||||
|
||||
it("hashes parameters independently of object insertion order", () => {
|
||||
expect(hashRuntimeParams({ a: 1, b: "two" })).toBe(hashRuntimeParams({ b: "two", a: 1 }));
|
||||
});
|
||||
|
||||
it("resolves only explicit option and literal bindings for automatic requests", () => {
|
||||
const loadRequest: CustomJsxRequest = {
|
||||
...request,
|
||||
kind: "query",
|
||||
trigger: "load",
|
||||
optionsBinding: {
|
||||
device: { $option: "selectedDevice" },
|
||||
enabled: true,
|
||||
level: { $option: "volume" },
|
||||
},
|
||||
};
|
||||
expect(resolveCustomWidgetOptionsBinding(loadRequest, { selectedDevice: "lamp", volume: 5 })).toEqual({
|
||||
device: "lamp",
|
||||
enabled: true,
|
||||
level: 5,
|
||||
});
|
||||
expect(() => resolveCustomWidgetOptionsBinding({ ...loadRequest, optionsBinding: undefined }, {})).toThrow(
|
||||
"has no explicit option binding",
|
||||
it("rejects missing options and non-primitive URL values", () => {
|
||||
expect(() => resolveCustomWidgetRequestValues(request, {}, { id: "lamp", level: 5, enabled: true })).toThrow(
|
||||
"room",
|
||||
);
|
||||
expect(() => resolveCustomWidgetOptionsBinding(loadRequest, { device: "lamp", level: 5 })).toThrow(
|
||||
"option 'selectedDevice'",
|
||||
const values = resolveCustomWidgetRequestValues(request, { room: [] }, { id: "lamp", level: 5, enabled: true });
|
||||
expect(() => renderRequestTarget("https://example.com", request, values)).toThrow("Path value");
|
||||
});
|
||||
|
||||
it("supports structured options in JSON bodies", () => {
|
||||
const bodyRequest = customJsxRequestSchema.parse({
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/rules",
|
||||
body: { entities: { $option: "entities" }, rule: { $option: "rule" } },
|
||||
});
|
||||
const values = resolveCustomWidgetRequestValues(bodyRequest, {
|
||||
entities: ["light.office", "light.desk"],
|
||||
rule: { transition: 2 },
|
||||
});
|
||||
expect(JSON.parse(renderRequestBody(bodyRequest, values) ?? "null")).toEqual({
|
||||
entities: ["light.office", "light.desk"],
|
||||
rule: { transition: 2 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a source base path", () => {
|
||||
const pokemon = customJsxRequestSchema.parse({ path: "/pokemon" });
|
||||
expect(renderRequestTarget("https://pokeapi.co/api/v2", pokemon, {}).toString()).toBe(
|
||||
"https://pokeapi.co/api/v2/pokemon",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["start", "stop", "restart"])("renders a Portainer %s action without duplicating declarations", (action) => {
|
||||
const portainer = customJsxRequestSchema.parse({
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: `/api/endpoints/{option:endpointId}/docker/containers/{param:id}/${action}`,
|
||||
invalidates: ["containers"],
|
||||
});
|
||||
const values = resolveCustomWidgetRequestValues(portainer, { endpointId: 2 }, { id: "abc/123" });
|
||||
expect(renderRequestTarget("https://portainer.example", portainer, values).pathname).toBe(
|
||||
`/api/endpoints/2/docker/containers/abc%2F123/${action}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -106,6 +106,26 @@ async function settle() {
|
||||
}
|
||||
|
||||
describe("Custom Widget runtime ports", () => {
|
||||
it("renders common safe collection and number formatting operations", async () => {
|
||||
const components = createCustomJsxComponents({
|
||||
TablerIcon: (() => null) as never,
|
||||
copyLabels: { copy: "Copy", copied: "Copied" },
|
||||
});
|
||||
await render(
|
||||
<CustomJsxRenderer
|
||||
template={
|
||||
'<Text>{[1, 2].concat([3]).flatMap(value => [value]).map(value => value.toLocaleString()).join(" · ")}</Text>'
|
||||
}
|
||||
data={{}}
|
||||
components={components}
|
||||
createBindings={() => ({})}
|
||||
messages={{ noTemplate: "No template", templateWarnings: (count) => `${count} warnings` }}
|
||||
/>,
|
||||
createPort(),
|
||||
);
|
||||
expect(host.textContent).toContain("1 · 2 · 3");
|
||||
});
|
||||
|
||||
it("removes unsafe dynamic link targets at runtime", async () => {
|
||||
const components = createCustomJsxComponents({
|
||||
TablerIcon: (() => null) as never,
|
||||
@@ -288,6 +308,26 @@ describe("Custom Widget runtime ports", () => {
|
||||
expect(host.querySelector("button, p, code, [role='alert']")).toBeNull();
|
||||
});
|
||||
|
||||
it("uses a built-in manual trigger and passes successful request metadata to children", async () => {
|
||||
const port = createPort();
|
||||
await render(
|
||||
<SubFetch requestId="details" trigger="manual">
|
||||
{(data, metadata) => (
|
||||
<span>{`${(data as { name: string }).name}:${metadata.status}:${String(metadata.loading)}`}</span>
|
||||
)}
|
||||
</SubFetch>,
|
||||
port,
|
||||
);
|
||||
expect(port.query).not.toHaveBeenCalled();
|
||||
expect(host.textContent).toContain("Load");
|
||||
|
||||
await act(async () => (host.querySelector("button") as HTMLButtonElement).click());
|
||||
await settle();
|
||||
|
||||
expect(port.query).toHaveBeenCalledOnce();
|
||||
expect(host.textContent).toContain("Bulbasaur:200:false");
|
||||
});
|
||||
|
||||
it("passes cancellation to the port when the component unmounts", async () => {
|
||||
let signal: AbortSignal | undefined;
|
||||
const port = createPort({
|
||||
|
||||
@@ -1,596 +1,95 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BUNDLED_CUSTOM_WIDGETS } from "../core/bundled-widgets";
|
||||
import { customJsxExamples, CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import { getCustomWidgetSecretRequirements } from "../core/secret-requirements";
|
||||
import { customJsxRequestSchema, customWidgetCreateSchema, customWidgetDefinitionSchema } from "../core/schema";
|
||||
import { validateCustomWidgetOptions } from "../core/options";
|
||||
import {
|
||||
CUSTOM_WIDGET_STARTER,
|
||||
customWidgetDefinitionSchema,
|
||||
customJsxRequestSchema,
|
||||
getCustomWidgetDefaultOptions,
|
||||
getCustomWidgetSecretRequirements,
|
||||
} from "../core";
|
||||
|
||||
describe("Custom JSX v2 validation", () => {
|
||||
test.each(customJsxExamples)("validates $id", (example) => {
|
||||
expect(() => customWidgetDefinitionSchema.parse(example.widget)).not.toThrow();
|
||||
});
|
||||
|
||||
test.each(BUNDLED_CUSTOM_WIDGETS)("validates bundled definition $id", ({ widget }) => {
|
||||
const result = customWidgetDefinitionSchema.safeParse(widget);
|
||||
expect(result.success, result.error?.issues.map((issue) => issue.message).join("; ")).toBe(true);
|
||||
});
|
||||
|
||||
test.each(["q", "http://["])("reports an incomplete URL inline without throwing: %s", (value) => {
|
||||
const source = { ...CUSTOM_WIDGET_STARTER.sources[0], baseUrl: value };
|
||||
|
||||
expect(() => customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [source] })).not.toThrow();
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [source] }).success).toBe(false);
|
||||
expect(() => customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: value })).not.toThrow();
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: value }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps the bundled seed set stable, disabled-ready, and credential-free", () => {
|
||||
expect(BUNDLED_CUSTOM_WIDGETS.map(({ id }) => id)).toEqual([
|
||||
"seed-dog-facts",
|
||||
"seed-currency-exchange",
|
||||
"seed-jellyfin",
|
||||
"seed-pokedex",
|
||||
]);
|
||||
for (const { widget } of BUNDLED_CUSTOM_WIDGETS) {
|
||||
expect(JSON.stringify(widget)).not.toMatch(/"(?:apiKey|password|secret|token)"\s*:/iu);
|
||||
}
|
||||
});
|
||||
|
||||
test("derives every credential required by widget sources", () => {
|
||||
expect(
|
||||
getCustomWidgetSecretRequirements([
|
||||
{
|
||||
id: "default",
|
||||
name: "Example API",
|
||||
baseUrl: "https://api.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "bearer" },
|
||||
},
|
||||
{
|
||||
id: "portainer",
|
||||
name: "Portainer",
|
||||
baseUrl: "https://portainer.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-API-Key" },
|
||||
},
|
||||
{
|
||||
id: "basic",
|
||||
name: "Basic API",
|
||||
baseUrl: "https://basic.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "basic" },
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
expect.objectContaining({ sourceId: "default", kind: "apiKey", authType: "bearer" }),
|
||||
expect.objectContaining({ sourceId: "portainer", kind: "apiKey", destination: "X-API-Key" }),
|
||||
expect.objectContaining({ sourceId: "basic", kind: "username" }),
|
||||
expect.objectContaining({ sourceId: "basic", kind: "password" }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects every legacy schema", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, $schema: "homarr-custom-widget-v3" }).success,
|
||||
).toBe(false);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ displayType: "raw", displayConfig: { type: "raw" } }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("allows query POST and action GET while keeping actions manual", () => {
|
||||
const base = {
|
||||
sourceId: "default",
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none" as const,
|
||||
trigger: "manual" as const,
|
||||
};
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "query",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
minimumBoardPermission: "view",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "action",
|
||||
kind: "action",
|
||||
method: "GET",
|
||||
minimumBoardPermission: "modify",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "action",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
trigger: "load",
|
||||
minimumBoardPermission: "modify",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "delete-query",
|
||||
kind: "query",
|
||||
method: "DELETE",
|
||||
minimumBoardPermission: "full",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("requires explicit parameter sources for load queries", () => {
|
||||
const optionsSchema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
endpointId: { type: "string" },
|
||||
wrongType: { type: "boolean" },
|
||||
},
|
||||
required: ["endpointId"],
|
||||
additionalProperties: false as const,
|
||||
};
|
||||
const request = {
|
||||
id: "containers",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/endpoints/{endpointId}/containers",
|
||||
parameters: { endpointId: "string" as const, showAll: "boolean" as const },
|
||||
queryTemplate: { all: { $param: "showAll" } },
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
};
|
||||
|
||||
const missing = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [request],
|
||||
optionsSchema,
|
||||
defaultOptions: { endpointId: "local" },
|
||||
describe("lean Custom Widget schema", () => {
|
||||
it("applies request defaults", () => {
|
||||
expect(customJsxRequestSchema.parse({ path: "/status" })).toMatchObject({
|
||||
source: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
trigger: "load",
|
||||
auth: "inherit",
|
||||
permission: "view",
|
||||
});
|
||||
expect(missing.success).toBe(false);
|
||||
if (missing.success) throw new Error("Expected missing bindings to fail");
|
||||
expect(missing.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: ["requests", 0, "optionsBinding", "endpointId"],
|
||||
message: expect.stringContaining("explicit option reference or literal"),
|
||||
}),
|
||||
expect.objectContaining({ path: ["requests", 0, "optionsBinding", "showAll"] }),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
...request,
|
||||
optionsBinding: { endpointId: { $option: "endpointId" }, showAll: false },
|
||||
},
|
||||
],
|
||||
optionsSchema,
|
||||
defaultOptions: { endpointId: "local" },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
...request,
|
||||
optionsBinding: { endpointId: { $option: "wrongType" }, showAll: false },
|
||||
},
|
||||
],
|
||||
optionsSchema,
|
||||
defaultOptions: { endpointId: "local" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("uses the same parameter identifier grammar for declarations and path placeholders", () => {
|
||||
const request = {
|
||||
id: "detail",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
parameters: { endpointId: "string" as const },
|
||||
optionsBinding: { endpointId: "local" },
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
};
|
||||
expect(customJsxRequestSchema.safeParse({ ...request, pathTemplate: "/endpoints/{endpointId}" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(customJsxRequestSchema.safeParse({ ...request, pathTemplate: "/endpoints/{1invalid}" }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("requires invoking components to provide params for parameterized manual requests", () => {
|
||||
const request = {
|
||||
id: "detail",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/items/{id}",
|
||||
parameters: { id: "string" as const },
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "manual" as const,
|
||||
};
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [request],
|
||||
template: '<SubFetch requestId="detail" />',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [request],
|
||||
template: '<SubFetch requestId="detail" params={{ id: inputs.selectedId }} />',
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
...request,
|
||||
trigger: "load",
|
||||
optionsBinding: { id: "fixed" },
|
||||
},
|
||||
],
|
||||
template: '<SubFetch requestId="detail" params={{ id: inputs.selectedId }} />',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects reserved headers, duplicate IDs, and unknown sources", () => {
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "missing",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
};
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: [request] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({ ...request, sourceId: "default", staticHeaders: { Authorization: "secret" } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...request,
|
||||
sourceId: "default",
|
||||
confirmation: { title: "Ignored", message: "Ignored" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(customJsxRequestSchema.safeParse({ ...request, sourceId: "default", invalidates: ["status"] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
customWidgetCreateSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
secrets: [
|
||||
{ sourceId: "default", kind: "apiKey", value: "one" },
|
||||
{ sourceId: "default", kind: "apiKey", value: "two" },
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts multi-source actions, dynamic options, conditions, and temporary inputs", () => {
|
||||
const result = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [
|
||||
{
|
||||
id: "sonarr",
|
||||
name: "Sonarr",
|
||||
baseUrl: "http://sonarr:8989",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Api-Key" },
|
||||
},
|
||||
{
|
||||
id: "radarr",
|
||||
name: "Radarr",
|
||||
baseUrl: "http://radarr:7878",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Api-Key" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "list-calendars",
|
||||
sourceId: "sonarr",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
pathTemplate: "/api/v3/calendar",
|
||||
parameters: { start: "string" },
|
||||
optionsBinding: { start: { $option: "start" } },
|
||||
bodyTemplate: { start: { $param: "start" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
},
|
||||
{
|
||||
id: "monitor-series",
|
||||
sourceId: "sonarr",
|
||||
kind: "action",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v3/series/{seriesId}",
|
||||
parameters: { seriesId: "number" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
confirmation: { title: "Monitor series", message: "Monitor this series?" },
|
||||
invalidates: ["list-calendars"],
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
start: { type: "string", title: "Start date", "x-homarr": { control: "date", order: 1 } },
|
||||
calendarId: {
|
||||
type: "integer",
|
||||
title: "Calendar",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: {
|
||||
requestId: "list-calendars",
|
||||
itemsPath: "$.data.environments",
|
||||
valuePath: "$.Id",
|
||||
labelPath: "$.Name",
|
||||
},
|
||||
},
|
||||
},
|
||||
advancedColor: { type: "string", "x-homarr": { control: "color", advanced: true } },
|
||||
},
|
||||
required: ["start"],
|
||||
additionalProperties: false,
|
||||
if: { properties: { start: { const: "today" } } },
|
||||
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
|
||||
then: { properties: { advancedColor: { type: "string" } } },
|
||||
},
|
||||
defaultOptions: { start: "today" },
|
||||
template:
|
||||
'<Stack><DatePicker bind="selectedDate"/><ActionButton requestId="monitor-series" params={{ seriesId: 1 }}>Monitor</ActionButton></Stack>',
|
||||
expect(customJsxRequestSchema.parse({ kind: "action", path: "/restart" })).toMatchObject({
|
||||
trigger: "manual",
|
||||
permission: "modify",
|
||||
});
|
||||
expect(customJsxRequestSchema.parse({ method: "DELETE", path: "/item" })).toMatchObject({
|
||||
permission: "full",
|
||||
confirmation: { destructive: true },
|
||||
});
|
||||
expect(result.success, result.error?.issues.map((issue) => issue.message).join("; ")).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects unsafe source URLs, auth overrides, invalid defaults, and missing dynamic requests", () => {
|
||||
const unsafeSource = { ...CUSTOM_WIDGET_STARTER.sources[0], baseUrl: "https://user:pass@example.com?token=nope" };
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [unsafeSource] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
it("validates keyed sources, requests and options", () => {
|
||||
const result = customWidgetDefinitionSchema.parse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: {
|
||||
list: { path: "/items/{option:category}", query: { limit: { $option: "limit" } } },
|
||||
search: { trigger: "manual", path: "/search", query: { q: { $param: "query" } } },
|
||||
restart: { kind: "action", method: "POST", path: "/items/{param:id}/restart", invalidates: ["list"] },
|
||||
},
|
||||
options: {
|
||||
category: { label: "Category", control: "text", default: "all" },
|
||||
limit: { label: "Limit", control: "number", default: 20, min: 1, max: 100 },
|
||||
},
|
||||
});
|
||||
expect(Object.keys(result.requests)).toEqual(["list", "search", "restart"]);
|
||||
expect(getCustomWidgetDefaultOptions(result.options)).toEqual({ category: "all", limit: 20 });
|
||||
});
|
||||
|
||||
const source = {
|
||||
...CUSTOM_WIDGET_STARTER.sources[0],
|
||||
auth: { type: "apiKeyHeader" as const, headerName: "X-Api-Key" },
|
||||
};
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "inherit" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
staticHeaders: { "x-api-key": "not-a-secret" },
|
||||
};
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [source], requests: [request] })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, defaultOptions: { apiKey: "not-exportable" } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { accessToken: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
it("defaults omitted options to an empty map", () => {
|
||||
const { options: _options, ...withoutOptions } = CUSTOM_WIDGET_STARTER;
|
||||
expect(customWidgetDefinitionSchema.parse(withoutOptions).options).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects invocation params on load and unknown options", () => {
|
||||
const loadParam = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: { bad: { path: "/{param:id}" } },
|
||||
});
|
||||
expect(loadParam.success).toBe(false);
|
||||
const unknownOption = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: { bad: { path: "/{option:missing}" } },
|
||||
});
|
||||
expect(unknownOption.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed placeholders and removed public fields", () => {
|
||||
expect(customJsxRequestSchema.safeParse({ path: "/items/{id}" }).success).toBe(false);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, optionsSchema: {} }).success).toBe(false);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, stateSchema: {} }).success).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
...request,
|
||||
sourceId: "default",
|
||||
auth: "none",
|
||||
staticHeaders: { "X-Custom": "Bearer not-exportable-token" },
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...request,
|
||||
sourceId: "default",
|
||||
auth: "none",
|
||||
staticHeaders: { "X-API-Key": "not-exportable" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
id: "action",
|
||||
sourceId: "default",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/action",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
invalidates: ["missing"],
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
endpoint: {
|
||||
type: "string",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: { requestId: "missing", valuePath: "$.id", labelPath: "$.name" },
|
||||
},
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("requires literal temporary input bindings", () => {
|
||||
it("keeps auth secrets outside the document", () => {
|
||||
const definition = customWidgetDefinitionSchema.parse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: {
|
||||
default: { baseUrl: "https://example.com", networkScope: "public", auth: "bearer" },
|
||||
admin: { baseUrl: "https://example.net", networkScope: "private", auth: "basic" },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
getCustomWidgetSecretRequirements(definition.sources).map(({ sourceId, kind }) => `${sourceId}:${kind}`),
|
||||
).toEqual(["default:apiKey", "admin:username", "admin:password"]);
|
||||
});
|
||||
|
||||
it("supports official Mantine compound names and separates bigint diagnostics", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: '<DatePicker bind="selectedDate" />',
|
||||
template: "<Radio.Group><Radio.Card><Radio.Indicator /></Radio.Card></Radio.Group>",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: "<DatePicker bind={inputs.selectedDate} />",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: "<Text>{state.search}</Text>",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("validates values declared only by the active conditional branch", () => {
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: { mode: { type: "string", enum: ["simple", "advanced"] } },
|
||||
required: ["mode"],
|
||||
additionalProperties: false,
|
||||
if: { properties: { mode: { const: "advanced" } } },
|
||||
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
|
||||
then: {
|
||||
properties: { color: { type: "string" } },
|
||||
required: ["color"],
|
||||
},
|
||||
};
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "advanced", color: "blue" })).toEqual([]);
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "advanced" })).toEqual([
|
||||
{ path: "configuration.color", message: "This field is required" },
|
||||
]);
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "simple", color: "blue" })).toEqual([
|
||||
{ path: "configuration.color", message: "Unknown option" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects unsafe custom authentication header names", () => {
|
||||
const result = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER.sources[0],
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Forwarded-Authorization" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects prototype-pollution keys in structured authored data", () => {
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "POST" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
bodyTemplate: JSON.parse('{"constructor":{"prototype":{"polluted":true}}}') as unknown,
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "manual" as const,
|
||||
};
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: [request] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects option controls, enum values, and icon URLs that do not match their declared capability", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: "javascript:alert(1)" }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://user:password@example.com/icon.png",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://example.com/icon.png?accessToken=literal-secret",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: '<Text>apiKey="literal-secret"</Text>',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { enabled: { type: "boolean", "x-homarr": { control: "slider" } } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
defaultOptions: { enabled: true },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { count: { type: "integer", enum: [1, "two"] } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
defaultOptions: { count: 1 },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
const result = customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, template: "<Text>{1n}</Text>" });
|
||||
expect(result.success ? "" : result.error.issues[0]?.message).toContain("BIGINT_NOT_SUPPORTED");
|
||||
});
|
||||
});
|
||||
@@ -1,218 +1,164 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analyzeJsxTemplate,
|
||||
analyzeCustomWidgetAccessibility,
|
||||
analyzeRequestManifest,
|
||||
appendDataPath,
|
||||
createResponseTreeNode,
|
||||
CUSTOM_JSX_TEMPLATE_LIMIT,
|
||||
DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||
customWidgetFormSchema,
|
||||
renameCustomWidgetRequest,
|
||||
} from "../workbench";
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import { CUSTOM_WIDGET_STARTER, customWidgetDefinitionSchema } from "../core";
|
||||
import {
|
||||
CUSTOM_WIDGET_OPTIONS_EXAMPLES,
|
||||
CUSTOM_WIDGET_REQUEST_EXAMPLES,
|
||||
getCustomWidgetDefaultOptionsJsonSchema,
|
||||
getCustomWidgetOptionsJsonSchema,
|
||||
getCustomWidgetRequestsJsonSchema,
|
||||
} from "../core/schema-references";
|
||||
import {
|
||||
customJsxSafeBlockCompletions,
|
||||
getCustomJsxComponentPropCompletions,
|
||||
getCustomJsxLocalConstCompletions,
|
||||
} from "../workbench/code-language";
|
||||
analyzeCustomWidgetAccessibility,
|
||||
analyzeJsxTemplate,
|
||||
analyzeRequestManifest,
|
||||
appendDataPath,
|
||||
createResponseTreeNode,
|
||||
CUSTOM_JSX_TEMPLATE_LIMIT,
|
||||
customWidgetFormSchema,
|
||||
DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||
renameCustomWidgetOption,
|
||||
renameCustomWidgetRequest,
|
||||
} from "../workbench";
|
||||
import { getCustomJsxComponentPropCompletions } from "../workbench/code-language";
|
||||
|
||||
describe("Custom Widget workbench contracts", () => {
|
||||
it("always provides a valid starter template", () => {
|
||||
expect(DEFAULT_CUSTOM_WIDGET_FORM_VALUES.template.trim()).not.toBe("");
|
||||
expect(
|
||||
customWidgetFormSchema.safeParse({
|
||||
...DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||
name: "Example",
|
||||
url: "https://example.com/api",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
it("provides valid lean starter form values", () => {
|
||||
expect(customWidgetFormSchema.safeParse(DEFAULT_CUSTOM_WIDGET_FORM_VALUES).success).toBe(true);
|
||||
expect(JSON.parse(DEFAULT_CUSTOM_WIDGET_FORM_VALUES.sources)).toHaveProperty("default");
|
||||
});
|
||||
|
||||
it("accepts 50,000 template characters and rejects 50,001", () => {
|
||||
expect(analyzeJsxTemplate("x".repeat(CUSTOM_JSX_TEMPLATE_LIMIT))).not.toEqual(
|
||||
it("validates keyed request manifests", () => {
|
||||
expect(analyzeRequestManifest(JSON.stringify(CUSTOM_WIDGET_REQUEST_EXAMPLES.full))).toEqual([]);
|
||||
expect(analyzeRequestManifest("[]")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "invalidRequestManifest" })]),
|
||||
);
|
||||
expect(getCustomWidgetRequestsJsonSchema()).toMatchObject({ type: "object" });
|
||||
expect(getCustomWidgetOptionsJsonSchema()).toMatchObject({ type: "object" });
|
||||
expect(CUSTOM_WIDGET_OPTIONS_EXAMPLES.full.limit.default).toBe(20);
|
||||
});
|
||||
|
||||
it("enforces the template size and named request references", () => {
|
||||
expect(analyzeJsxTemplate("x".repeat(CUSTOM_JSX_TEMPLATE_LIMIT + 1))).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "templateTooLong" })]),
|
||||
);
|
||||
expect(analyzeJsxTemplate("x".repeat(CUSTOM_JSX_TEMPLATE_LIMIT + 1))).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "templateTooLong", severity: "error" })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("validates full request manifests rather than accepting any JSON array", () => {
|
||||
expect(analyzeRequestManifest("[]")).toEqual([]);
|
||||
expect(analyzeRequestManifest('[{"id":"broken"}]')).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "invalidRequestManifest", severity: "error" })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("generates schema references and examples from canonical validators", () => {
|
||||
expect(getCustomWidgetRequestsJsonSchema()).toMatchObject({ type: "array" });
|
||||
expect(getCustomWidgetOptionsJsonSchema()).toMatchObject({ type: "object" });
|
||||
expect(getCustomWidgetDefaultOptionsJsonSchema()).toMatchObject({ type: "object" });
|
||||
expect(analyzeRequestManifest(JSON.stringify(CUSTOM_WIDGET_REQUEST_EXAMPLES.full))).toEqual([]);
|
||||
expect(CUSTOM_WIDGET_OPTIONS_EXAMPLES.full.defaults).toMatchObject({ limit: 20 });
|
||||
});
|
||||
|
||||
it("validates named request references and rejects inline network capabilities", () => {
|
||||
expect(analyzeJsxTemplate('<SubFetch requestId="known" />', { requestIds: ["known"] })).toEqual([]);
|
||||
expect(analyzeJsxTemplate('<SubFetch requestId="missing" url="/api" />', { requestIds: ["known"] })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "inlineRequestProps" }),
|
||||
expect.objectContaining({ code: "unknownRequest", value: "missing" }),
|
||||
expect.objectContaining({ code: "unknownRequest" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts named temporary inputs and diagnoses dynamic bindings", () => {
|
||||
expect(analyzeJsxTemplate('<DatePicker bind="selectedDate" />')).toEqual([]);
|
||||
expect(analyzeJsxTemplate("<DatePicker bind={inputs.selectedDate} />")).toEqual(
|
||||
it("supports temporary inputs and diagnoses incompatible bindings", () => {
|
||||
expect(analyzeJsxTemplate('<TextInput bind="filter"/><Switch bind="filter"/>')).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "bindingTypeConflict" })]),
|
||||
);
|
||||
expect(analyzeJsxTemplate("<TextInput bind={inputs.filter} />")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "dynamicInputBinding" })]),
|
||||
);
|
||||
expect(analyzeJsxTemplate('<Calendar bind="selectedDate" />')).toEqual(
|
||||
});
|
||||
|
||||
it("does not advertise statement blocks or IIFEs", () => {
|
||||
expect(
|
||||
analyzeJsxTemplate("<Text>{data.items.map(item => { const name = item.name; return name; })}</Text>"),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "ast", value: expect.stringContaining("BINDING_UNAVAILABLE") }),
|
||||
expect.objectContaining({ code: "ast", value: expect.stringContaining("UNSUPPORTED_BLOCK_STATEMENT") }),
|
||||
]),
|
||||
);
|
||||
expect(analyzeJsxTemplate('<TextInput bind="filter"/><Switch bind="filter"/>')).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "bindingTypeConflict", value: "filter" })]),
|
||||
expect(analyzeJsxTemplate("<Text>{(() => data.name)()}</Text>")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "ast", value: expect.stringContaining("IIFEs") })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("completes only earlier immutable locals from the active block, even with unrelated syntax errors", () => {
|
||||
const source = `{data.first.map((item) => { const sibling = ; return sibling; })}
|
||||
{data.second.map((item) => {
|
||||
const current = item;
|
||||
return <Text>{current}</Text>;
|
||||
const future = item;
|
||||
})}`;
|
||||
const cursor = source.indexOf("return <Text>");
|
||||
const labels = getCustomJsxLocalConstCompletions(source, cursor).map(({ label }) => label);
|
||||
expect(labels).toContain("current");
|
||||
expect(labels).not.toContain("sibling");
|
||||
expect(labels).not.toContain("future");
|
||||
});
|
||||
|
||||
it("does not complete the active or future declarator", () => {
|
||||
const source = `{data.items.map((item) => {
|
||||
const first = item, current = fir, future = current;
|
||||
return future;
|
||||
})}`;
|
||||
const cursor = source.indexOf("= fir") + "= fir".length;
|
||||
const labels = getCustomJsxLocalConstCompletions(source, cursor).map(({ label }) => label);
|
||||
expect(labels).toContain("first");
|
||||
expect(labels).not.toContain("current");
|
||||
expect(labels).not.toContain("future");
|
||||
});
|
||||
|
||||
it("completes callback parameters and publishes safe-block snippets", () => {
|
||||
const source = `{data.items.map((item, index, collection) => {
|
||||
const value = item;
|
||||
return <Text>{value}</Text>;
|
||||
})}`;
|
||||
const cursor = source.indexOf("return <Text>");
|
||||
const labels = getCustomJsxLocalConstCompletions(source, cursor).map(({ label }) => label);
|
||||
expect(labels).toEqual(expect.arrayContaining(["item", "index", "collection", "value"]));
|
||||
expect(customJsxSafeBlockCompletions.map(({ label }) => label)).toEqual(["map block", "derived value IIFE"]);
|
||||
});
|
||||
|
||||
it("uses canonical component prop types for contextual JSX completions", () => {
|
||||
const textInput = getCustomJsxComponentPropCompletions("TextInput");
|
||||
expect(textInput).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "label=", detail: expect.stringContaining("ReactNode") }),
|
||||
expect.objectContaining({ label: "bind=", detail: "string" }),
|
||||
]),
|
||||
it("supports compound names and contextual prop completions", () => {
|
||||
expect(analyzeJsxTemplate("<Card.Section><Tabs.List /></Card.Section>")).toEqual([]);
|
||||
expect(getCustomJsxComponentPropCompletions("TextInput")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ label: "bind=" })]),
|
||||
);
|
||||
expect(getCustomJsxComponentPropCompletions("Portal")).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the AST security policy for computed reflective access while accepting benign fetch text", () => {
|
||||
expect(analyzeJsxTemplate("<Text>{data['con' + 'structor']}</Text>")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "ast", severity: "error" })]),
|
||||
);
|
||||
expect(analyzeJsxTemplate("<Text>fetch the latest status</Text>")).toEqual([]);
|
||||
});
|
||||
|
||||
it("builds safe response-tree paths for identifiers, arrays, and arbitrary object keys", () => {
|
||||
expect(appendDataPath("data", "items", false)).toBe("data.items");
|
||||
expect(appendDataPath("data.items", "0", true)).toBe("data.items[0]");
|
||||
expect(appendDataPath("data", "first-name", false)).toBe('data["first-name"]');
|
||||
const tree = createResponseTreeNode({ items: [{ name: "one" }] }, "data", "data");
|
||||
expect(tree.children?.[0]?.children?.[0]?.children?.[0]?.value).toBe("data.items[0].name");
|
||||
});
|
||||
|
||||
it("renames a request and every canonical reference atomically", () => {
|
||||
it("renames keyed request references atomically", () => {
|
||||
const renamed = renameCustomWidgetRequest(
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
id: "items",
|
||||
sourceId: "default",
|
||||
...customWidgetDefinitionSchema.parse(CUSTOM_WIDGET_STARTER),
|
||||
requests: {
|
||||
items: {
|
||||
source: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/items",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
path: "/items",
|
||||
auth: "inherit",
|
||||
permission: "view",
|
||||
trigger: "load",
|
||||
confirmation: undefined,
|
||||
},
|
||||
{
|
||||
id: "refresh",
|
||||
sourceId: "default",
|
||||
refresh: {
|
||||
source: "default",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/refresh",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "modify",
|
||||
path: "/refresh",
|
||||
auth: "inherit",
|
||||
permission: "modify",
|
||||
trigger: "manual",
|
||||
confirmation: undefined,
|
||||
invalidates: ["items"],
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
item: {
|
||||
type: "string",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: { requestId: "items", valuePath: "$.id", labelPath: "$.name" },
|
||||
},
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
template: '<Stack><SubFetch requestId="items" />{data["items"]}{status.items.ok}</Stack>',
|
||||
options: {
|
||||
item: {
|
||||
label: "Item",
|
||||
control: "select",
|
||||
default: "",
|
||||
choicesFrom: { request: "items", valuePath: "id", labelPath: "name" },
|
||||
},
|
||||
},
|
||||
template: '<Stack>{data["items"]}{status.items.ok}</Stack>',
|
||||
},
|
||||
"items",
|
||||
"inventory",
|
||||
);
|
||||
|
||||
expect(renamed.requests[0]?.id).toBe("inventory");
|
||||
expect(renamed.requests[1]?.invalidates).toEqual(["inventory"]);
|
||||
expect(JSON.stringify(renamed.optionsSchema)).toContain('"requestId":"inventory"');
|
||||
expect(renamed.template).toBe(
|
||||
'<Stack><SubFetch requestId="inventory" />{data["inventory"]}{status.inventory.ok}</Stack>',
|
||||
);
|
||||
expect(renamed.requests.inventory).toBeDefined();
|
||||
expect(renamed.requests.refresh?.invalidates).toEqual(["inventory"]);
|
||||
expect(renamed.options.item?.choicesFrom?.request).toBe("inventory");
|
||||
expect(renamed.template).toContain("inventory");
|
||||
});
|
||||
|
||||
it("reports common accessibility omissions in preview", () => {
|
||||
it("renames option references atomically", () => {
|
||||
const renamed = renameCustomWidgetOption(
|
||||
customWidgetDefinitionSchema.parse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
options: { room: { label: "Room", control: "text", default: "office" } },
|
||||
requests: {
|
||||
status: {
|
||||
path: "/rooms/{option:room}",
|
||||
query: { selected: { $option: "room" } },
|
||||
body: { room: { $option: "room" } },
|
||||
},
|
||||
},
|
||||
template: '<Text>{options.room}{options["room"]}</Text>',
|
||||
}),
|
||||
"room",
|
||||
"roomId",
|
||||
);
|
||||
expect(renamed.options.roomId?.default).toBe("office");
|
||||
expect(renamed.requests.status?.path).toBe("/rooms/{option:roomId}");
|
||||
expect(renamed.requests.status?.query).toEqual({ selected: { $option: "roomId" } });
|
||||
expect(renamed.requests.status?.body).toEqual({ room: { $option: "roomId" } });
|
||||
expect(renamed.template).toBe('<Text>{options.roomId}{options["roomId"]}</Text>');
|
||||
});
|
||||
|
||||
it("builds response paths and accessibility diagnostics", () => {
|
||||
expect(appendDataPath("data", "first-name", false)).toBe('data["first-name"]');
|
||||
expect(
|
||||
analyzeCustomWidgetAccessibility('<Stack><Image src="/image.png"/><ActionIcon/><TextInput /></Stack>'),
|
||||
).toEqual(["imageAlt", "actionIconLabel", "inputLabel"]);
|
||||
expect(
|
||||
analyzeCustomWidgetAccessibility(
|
||||
'<Stack><Image src="/image.png" alt="Preview"/><ActionIcon aria-label="Refresh"/><TextInput label="Search" /></Stack>',
|
||||
),
|
||||
).toEqual([]);
|
||||
createResponseTreeNode({ items: [{ name: "one" }] }, "data", "data").children?.[0]?.children?.[0]?.children?.[0]
|
||||
?.value,
|
||||
).toBe("data.items[0].name");
|
||||
expect(analyzeCustomWidgetAccessibility('<Image src="/image.png"/><ActionIcon/><TextInput />')).toEqual([
|
||||
"imageAlt",
|
||||
"actionIconLabel",
|
||||
"inputLabel",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getCustomJsxBindingType } from "../core/component-registry";
|
||||
import { customJsxRequestSchema } from "../core/request-schema";
|
||||
import { z } from "zod/v4";
|
||||
import { CUSTOM_JSX_LIMITS, validateCustomJsxTemplate } from "../jsx";
|
||||
|
||||
export type EditorDiagnosticCode =
|
||||
@@ -103,7 +104,7 @@ export function analyzeJsxTemplate(
|
||||
|
||||
export function analyzeRequestManifest(value: string): EditorDiagnostic[] {
|
||||
try {
|
||||
const result = customJsxRequestSchema.array().safeParse(JSON.parse(value) as unknown);
|
||||
const result = z.record(z.string(), customJsxRequestSchema).safeParse(JSON.parse(value) as unknown);
|
||||
if (result.success) return [];
|
||||
return result.error.issues.map((issue) => ({
|
||||
code: "invalidRequestManifest",
|
||||
@@ -116,11 +117,13 @@ export function analyzeRequestManifest(value: string): EditorDiagnostic[] {
|
||||
}
|
||||
}
|
||||
|
||||
export function parseRequestManifest(value: string): unknown[] {
|
||||
export function parseRequestManifest(value: string): Record<string, unknown> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return [];
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ export interface CustomWidgetCodeEditorProps {
|
||||
completions?: Completion[];
|
||||
revealText?: string;
|
||||
revealKey?: number;
|
||||
insertText?: string;
|
||||
insertKey?: number;
|
||||
readOnly?: boolean;
|
||||
reference?: CustomWidgetSchemaReferenceData;
|
||||
height?: string;
|
||||
|
||||
@@ -51,6 +51,17 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
});
|
||||
editorView.focus();
|
||||
}, [editorCreated, editorInstanceId, props.revealKey, props.revealText]);
|
||||
useEffect(() => {
|
||||
const editorView = editorViews.get(editorInstanceId);
|
||||
if (!editorView || !props.insertText) return;
|
||||
const selection = editorView.state.selection.main;
|
||||
editorView.dispatch({
|
||||
changes: { from: selection.from, to: selection.to, insert: props.insertText },
|
||||
selection: { anchor: selection.from + props.insertText.length },
|
||||
scrollIntoView: true,
|
||||
});
|
||||
editorView.focus();
|
||||
}, [editorCreated, editorInstanceId, props.insertKey, props.insertText]);
|
||||
const handleCreateEditor = useCallback(
|
||||
(view: EditorViewType) => {
|
||||
editorViews.set(editorInstanceId, view);
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { snippetCompletion } from "@codemirror/autocomplete";
|
||||
import type { Completion, CompletionSource } from "@codemirror/autocomplete";
|
||||
import { jsxLanguage } from "@codemirror/lang-javascript";
|
||||
import { hoverTooltip } from "@codemirror/view";
|
||||
|
||||
import {
|
||||
@@ -41,72 +39,18 @@ const iconCompletions: Completion[] = customJsxTablerIconNames.map((name) => ({
|
||||
detail: "Safe Tabler icon",
|
||||
}));
|
||||
|
||||
export const customJsxSafeBlockCompletions: Completion[] = [
|
||||
snippetCompletion("map((item) => {\n\tconst value = ${};\n\treturn ${};\n})", {
|
||||
label: "map block",
|
||||
detail: "Safe immutable collection callback",
|
||||
type: "snippet",
|
||||
}),
|
||||
snippetCompletion("(() => {\n\tconst value = ${};\n\treturn ${};\n})()", {
|
||||
label: "derived value IIFE",
|
||||
detail: "Safe page-level derived value",
|
||||
type: "snippet",
|
||||
}),
|
||||
];
|
||||
|
||||
const rootBindingCompletions: Completion[] = [...ROOT_BINDINGS].toSorted().map((label) => ({
|
||||
label,
|
||||
type: ["data", "status", "options", "inputs"].includes(label) ? "variable" : "function",
|
||||
detail: "Safe Custom JSX binding",
|
||||
}));
|
||||
|
||||
export function getCustomJsxLocalConstCompletions(source: string, cursor: number): Completion[] {
|
||||
const wrapped = `<>${source}</>`;
|
||||
const target = cursor + 2;
|
||||
let activeNode = jsxLanguage.parser.parse(wrapped).resolveInner(target, -1);
|
||||
while (activeNode.name !== "Block") {
|
||||
const parent = activeNode.parent;
|
||||
if (!parent) return [];
|
||||
activeNode = parent;
|
||||
}
|
||||
const completions: Completion[] = [];
|
||||
let arrow = activeNode.parent;
|
||||
while (arrow && arrow.name !== "ArrowFunction") arrow = arrow.parent;
|
||||
arrow
|
||||
?.getChild("ParamList")
|
||||
?.getChildren("VariableDefinition")
|
||||
.forEach((definition) => {
|
||||
completions.push({
|
||||
label: wrapped.slice(definition.from, definition.to),
|
||||
type: "variable",
|
||||
detail: "Safe callback parameter",
|
||||
});
|
||||
});
|
||||
for (let statement = activeNode.firstChild; statement; statement = statement.nextSibling) {
|
||||
if (statement.name !== "VariableDeclaration" || statement.from >= target) continue;
|
||||
if (statement.firstChild?.name !== "const") continue;
|
||||
const definitions = statement.getChildren("VariableDefinition");
|
||||
definitions.forEach((definition, index) => {
|
||||
const nextDefinition = definitions[index + 1];
|
||||
const declaratorFinished = nextDefinition ? nextDefinition.from <= target : statement.to < target;
|
||||
if (!declaratorFinished) return;
|
||||
completions.push({
|
||||
label: wrapped.slice(definition.from, definition.to),
|
||||
type: "variable",
|
||||
detail: "Safe local const",
|
||||
});
|
||||
});
|
||||
}
|
||||
return completions;
|
||||
}
|
||||
|
||||
export const createCustomJsxCompletionSource =
|
||||
(additional: Completion[]): CompletionSource =>
|
||||
(context) => {
|
||||
const word = context.matchBefore(/[A-Za-z](?:[\w."'_-]|\[|\])*/u);
|
||||
if (!word && !context.explicit) return null;
|
||||
const source = context.state.doc.toString();
|
||||
const localCompletions = getCustomJsxLocalConstCompletions(source, context.pos);
|
||||
const componentName = activeOpeningComponent(source, context.pos);
|
||||
const contextualCompletions = componentName
|
||||
? [
|
||||
@@ -116,13 +60,7 @@ export const createCustomJsxCompletionSource =
|
||||
: componentCompletions;
|
||||
return {
|
||||
from: word?.from ?? context.pos,
|
||||
options: [
|
||||
...localCompletions,
|
||||
...customJsxSafeBlockCompletions,
|
||||
...rootBindingCompletions,
|
||||
...contextualCompletions,
|
||||
...additional,
|
||||
],
|
||||
options: [...rootBindingCompletions, ...contextualCompletions, ...additional],
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -11,22 +11,13 @@ const jsonObjectString = z.string().superRefine((value, ctx) => {
|
||||
}
|
||||
});
|
||||
|
||||
const jsonArrayString = z.string().superRefine((value, ctx) => {
|
||||
try {
|
||||
if (!Array.isArray(JSON.parse(value))) throw new Error();
|
||||
} catch {
|
||||
ctx.addIssue({ code: "custom", message: "Must be a JSON array" });
|
||||
}
|
||||
});
|
||||
|
||||
export const customWidgetFormSchema = z.object({
|
||||
name: z.string().trim().min(1).max(128),
|
||||
description: z.string().max(512),
|
||||
iconUrl: z.union([z.literal(""), z.string().url()]),
|
||||
sources: jsonArrayString,
|
||||
requests: jsonArrayString,
|
||||
optionsSchema: jsonObjectString,
|
||||
defaultOptions: jsonObjectString,
|
||||
sources: jsonObjectString,
|
||||
requests: jsonObjectString,
|
||||
options: jsonObjectString,
|
||||
template: z.string().min(1).max(50_000),
|
||||
secrets: z.array(
|
||||
z.object({ sourceId: z.string(), kind: z.string(), value: z.string(), hasValue: z.boolean().optional() }),
|
||||
@@ -54,8 +45,7 @@ export const DEFAULT_CUSTOM_WIDGET_FORM_VALUES: CustomWidgetFormValues = {
|
||||
iconUrl: CUSTOM_WIDGET_STARTER.iconUrl ?? "",
|
||||
sources: JSON.stringify(CUSTOM_WIDGET_STARTER.sources, null, 2),
|
||||
requests: JSON.stringify(CUSTOM_WIDGET_STARTER.requests, null, 2),
|
||||
optionsSchema: JSON.stringify(CUSTOM_WIDGET_STARTER.optionsSchema, null, 2),
|
||||
defaultOptions: JSON.stringify(CUSTOM_WIDGET_STARTER.defaultOptions, null, 2),
|
||||
options: JSON.stringify(CUSTOM_WIDGET_STARTER.options, null, 2),
|
||||
template: CUSTOM_WIDGET_STARTER.template,
|
||||
secrets: [],
|
||||
};
|
||||
@@ -5,7 +5,7 @@ export interface PreviewNamedRequest {
|
||||
id: string;
|
||||
kind: "query" | "action";
|
||||
method: string;
|
||||
pathTemplate: string;
|
||||
path: string;
|
||||
minimumBoardPermission?: string;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface PreviewJournalEntry {
|
||||
id: string;
|
||||
requestId: string;
|
||||
method: string;
|
||||
pathTemplate: string;
|
||||
path: string;
|
||||
simulated: boolean;
|
||||
status: number | null;
|
||||
durationMs: number;
|
||||
@@ -82,7 +82,7 @@ export function PreviewRequestPanel({
|
||||
{request.id}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" ff="monospace" lineClamp={1}>
|
||||
{request.pathTemplate}
|
||||
{request.path}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
@@ -111,7 +111,7 @@ export function PreviewRequestPanel({
|
||||
{entry.requestId}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" ff="monospace" truncate>
|
||||
{entry.pathTemplate}
|
||||
{entry.path}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
|
||||
@@ -11,20 +11,26 @@ export const redactPreviewUrl = (value: string): string => {
|
||||
};
|
||||
|
||||
export const getPreviewNamedRequests = (definition: Record<string, unknown>): PreviewNamedRequest[] => {
|
||||
if (!Array.isArray(definition.requests)) return [];
|
||||
return definition.requests.filter(
|
||||
(request): request is PreviewNamedRequest =>
|
||||
request !== null &&
|
||||
typeof request === "object" &&
|
||||
"id" in request &&
|
||||
typeof request.id === "string" &&
|
||||
"kind" in request &&
|
||||
(request.kind === "query" || request.kind === "action") &&
|
||||
"method" in request &&
|
||||
typeof request.method === "string" &&
|
||||
"pathTemplate" in request &&
|
||||
typeof request.pathTemplate === "string",
|
||||
);
|
||||
if (!definition.requests || typeof definition.requests !== "object" || Array.isArray(definition.requests)) return [];
|
||||
return Object.entries(definition.requests as Record<string, unknown>).flatMap(([id, candidate]) => {
|
||||
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return [];
|
||||
const request = candidate as Record<string, unknown>;
|
||||
if (
|
||||
(request.kind !== "query" && request.kind !== "action") ||
|
||||
typeof request.method !== "string" ||
|
||||
typeof request.path !== "string"
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
id,
|
||||
kind: request.kind,
|
||||
method: request.method,
|
||||
path: request.path,
|
||||
minimumBoardPermission: typeof request.permission === "string" ? request.permission : undefined,
|
||||
},
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
export type CustomWidgetAccessibilityIssue = "imageAlt" | "actionIconLabel" | "inputLabel";
|
||||
|
||||
@@ -9,25 +9,55 @@ export function renameCustomWidgetRequest(
|
||||
): HomarrCustomWidgetV2 {
|
||||
const parsedId = customWidgetIdentifierSchema.safeParse(nextId);
|
||||
if (!parsedId.success) throw new Error(parsedId.error.issues[0]?.message ?? "Invalid request ID");
|
||||
if (!definition.requests.some((request) => request.id === currentId))
|
||||
throw new Error(`Unknown request '${currentId}'`);
|
||||
if (currentId !== nextId && definition.requests.some((request) => request.id === nextId)) {
|
||||
if (!definition.requests[currentId]) throw new Error(`Unknown request '${currentId}'`);
|
||||
if (currentId !== nextId && definition.requests[nextId]) {
|
||||
throw new Error(`Request '${nextId}' already exists`);
|
||||
}
|
||||
|
||||
const candidate = {
|
||||
...definition,
|
||||
requests: definition.requests.map((request) => ({
|
||||
...request,
|
||||
id: request.id === currentId ? nextId : request.id,
|
||||
invalidates: request.invalidates?.map((id) => (id === currentId ? nextId : id)),
|
||||
})),
|
||||
optionsSchema: replaceDynamicOptionRequest(definition.optionsSchema, currentId, nextId),
|
||||
requests: Object.fromEntries(
|
||||
Object.entries(definition.requests).map(([id, request]) => [
|
||||
id === currentId ? nextId : id,
|
||||
{ ...request, invalidates: request.invalidates?.map((entry) => (entry === currentId ? nextId : entry)) },
|
||||
]),
|
||||
),
|
||||
options: replaceDynamicOptionRequest(definition.options, currentId, nextId),
|
||||
template: replaceTemplateRequestReferences(definition.template, currentId, nextId),
|
||||
};
|
||||
return customWidgetDefinitionSchema.parse(candidate);
|
||||
}
|
||||
|
||||
export function renameCustomWidgetOption(
|
||||
definition: HomarrCustomWidgetV2,
|
||||
currentName: string,
|
||||
nextName: string,
|
||||
): HomarrCustomWidgetV2 {
|
||||
const parsedName = customWidgetIdentifierSchema.safeParse(nextName);
|
||||
if (!parsedName.success) throw new Error(parsedName.error.issues[0]?.message ?? "Invalid option name");
|
||||
if (!definition.options[currentName]) throw new Error(`Unknown option '${currentName}'`);
|
||||
if (currentName !== nextName && definition.options[nextName]) throw new Error(`Option '${nextName}' already exists`);
|
||||
|
||||
return customWidgetDefinitionSchema.parse({
|
||||
...definition,
|
||||
options: Object.fromEntries(
|
||||
Object.entries(definition.options).map(([name, option]) => [name === currentName ? nextName : name, option]),
|
||||
),
|
||||
requests: Object.fromEntries(
|
||||
Object.entries(definition.requests).map(([id, request]) => [
|
||||
id,
|
||||
{
|
||||
...request,
|
||||
path: request.path.replaceAll(`{option:${currentName}}`, `{option:${nextName}}`),
|
||||
query: replaceOptionReferences(request.query, currentName, nextName),
|
||||
body: replaceOptionReferences(request.body, currentName, nextName),
|
||||
},
|
||||
]),
|
||||
),
|
||||
template: replaceTemplateOptionReferences(definition.template, currentName, nextName),
|
||||
});
|
||||
}
|
||||
|
||||
function replaceDynamicOptionRequest<T>(value: T, currentId: string, nextId: string): T {
|
||||
if (Array.isArray(value)) return value.map((entry) => replaceDynamicOptionRequest(entry, currentId, nextId)) as T;
|
||||
if (value === null || typeof value !== "object") return value;
|
||||
@@ -35,7 +65,7 @@ function replaceDynamicOptionRequest<T>(value: T, currentId: string, nextId: str
|
||||
const replaced = Object.fromEntries(
|
||||
Object.entries(record).map(([key, child]) => [key, replaceDynamicOptionRequest(child, currentId, nextId)]),
|
||||
);
|
||||
if (record.requestId === currentId && "valuePath" in record && "labelPath" in record) replaced.requestId = nextId;
|
||||
if (record.request === currentId && "valuePath" in record && "labelPath" in record) replaced.request = nextId;
|
||||
return replaced as T;
|
||||
}
|
||||
|
||||
@@ -47,6 +77,25 @@ function replaceTemplateRequestReferences(template: string, currentId: string, n
|
||||
.replace(new RegExp(`((?:data|status)\\.)${escaped}\\b`, "gu"), `$1${nextId}`);
|
||||
}
|
||||
|
||||
function replaceOptionReferences<T>(value: T, currentName: string, nextName: string): T {
|
||||
if (Array.isArray(value)) return value.map((entry) => replaceOptionReferences(entry, currentName, nextName)) as T;
|
||||
if (value === null || typeof value !== "object") return value;
|
||||
const entries = Object.entries(value as Record<string, unknown>);
|
||||
if (entries.length === 1 && entries[0]?.[0] === "$option" && entries[0][1] === currentName) {
|
||||
return { $option: nextName } as T;
|
||||
}
|
||||
return Object.fromEntries(
|
||||
entries.map(([key, child]) => [key, replaceOptionReferences(child, currentName, nextName)]),
|
||||
) as T;
|
||||
}
|
||||
|
||||
function replaceTemplateOptionReferences(template: string, currentName: string, nextName: string) {
|
||||
const escaped = escapeRegExp(currentName);
|
||||
return template
|
||||
.replace(new RegExp(`(options\\s*\\[\\s*["'])${escaped}(["']\\s*\\])`, "gu"), `$1${nextName}$2`)
|
||||
.replace(new RegExp(`(options\\.)${escaped}\\b`, "gu"), `$1${nextName}`);
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
}
|
||||
Reference in new issue
Block a user