feat(skins): add component authoring workflow

This commit is contained in:
illusia committed 2026-10-10 15:53:51 +08:00
1 parent 96c29394f3
commit 0c4cc344ef
25 files changed
+2013 -58

No files matched your search

+15 -3
View File
@@ -1,7 +1,7 @@
import {
SKIN_PLUGIN_PERMISSIONS,
SKIN_PLUGIN_HOST_WIDGETS,
SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS,
missingSkinPluginWidgetPermission,
parseSkinPluginRuntimeAction,
SKIN_PLUGIN_NODE_LIMIT,
SKIN_PLUGIN_TREE_DEPTH_LIMIT,
@@ -52,6 +52,12 @@ function assertLocalUiNode(node: SkinPluginNode): void {
node.children?.forEach(assertLocalUiNode);
}
function rejectExtensionHostWidgets(node: unknown): void {
if (!isRecord(node)) return;
if (node.widget !== undefined) fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "Extension UI output cannot embed privileged host widgets.");
if (Array.isArray(node.children)) node.children.forEach(rejectExtensionHostWidgets);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
@@ -95,8 +101,8 @@ function generatedNode(
}
if (page !== "voice") fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "The screen-share host widget is available only on the voice page.");
const widget = input.widget as SkinPluginHostWidget;
const requiredPermission = SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[widget];
if (requiredPermission && !permissions.includes(requiredPermission)) {
const requiredPermission = missingSkinPluginWidgetPermission(widget, permissions);
if (requiredPermission) {
fail("SKIN_EXTENSION_UI_PERMISSION_MISSING", `The ${widget} widget requires ${requiredPermission}.`);
}
onlyKeys(input, ["widget", "part", "className"], "A generated host widget node");
@@ -275,6 +281,12 @@ export function parseSkinExtensionUiOutput(
return document;
}
if (input.schemaVersion === 3 && Array.isArray(input.components)) {
for (const rawComponent of input.components) {
if (isRecord(rawComponent)) rejectExtensionHostWidgets(rawComponent.root);
}
}
let document: SkinPluginDocument;
try { document = parseSkinPluginDocument(input); }
catch { fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Extension UI output does not match the safe component schema."); }
+228
View File
@@ -0,0 +1,228 @@
import {
SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS,
parseSkinPluginDocument,
type SkinPluginComponent,
type SkinPluginDocument,
type SkinPluginNode,
} from "./skin-plugin.js";
/** Normalize an older declarative package before editing while preserving its validated data. */
export function editableSkinPluginDocument(input: unknown): SkinPluginDocument {
const parsed = parseSkinPluginDocument(input);
if (parsed.schemaVersion === 3) return parsed;
const components = parsed.components.map((component) => {
const permissions = new Set(component.permissions);
const visit = (node: SkinPluginNode) => {
if (node.widget) SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[node.widget]?.forEach((permission) => permissions.add(permission));
node.children?.forEach(visit);
};
visit(component.root);
return { ...component, permissions: [...permissions] };
});
return parseSkinPluginDocument({ schemaVersion: 3, components });
}
export function assertSkinPluginAuthoringDocument(input: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const visit = (node: SkinPluginNode) => {
const reserved = Object.keys(node.attributes ?? {}).find((key) => key.startsWith("data-ws-"));
if (reserved) throw new Error("The " + reserved + " attribute is owned by WebSpeak and cannot be authored by a skin.");
node.children?.forEach(visit);
};
document.components.forEach((component) => visit(component.root));
return document;
}
function checked(input: unknown): SkinPluginDocument {
return editableSkinPluginDocument(input);
}
function componentIndex(document: SkinPluginDocument, id: string): number {
const index = document.components.findIndex((component) => component.id === id);
if (index < 0) throw new Error("The skin component no longer exists.");
return index;
}
function parentNode(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
if (!path.length) return component.root;
let current = component.root;
for (const index of path) {
const child = current.children?.[index];
if (!child) throw new Error("The selected node no longer exists.");
current = child;
}
return current;
}
function nodeAt(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
return parentNode(component, path);
}
function assertChildIndex(index: number, length: number): void {
if (!Number.isInteger(index) || index < 0 || index >= length) throw new Error("The selected node no longer exists.");
}
function updateTree(
input: SkinPluginDocument,
componentId: string,
update: (component: SkinPluginComponent) => SkinPluginComponent,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const index = componentIndex(document, componentId);
const components = [...document.components];
components[index] = update(components[index]);
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginComponent(input: SkinPluginDocument, component: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
return checked({ schemaVersion: 3, components: [...document.components, component] });
}
export function replaceSkinPluginComponent(input: SkinPluginDocument, componentId: string, component: unknown): SkinPluginDocument {
return updateTree(input, componentId, () => component as SkinPluginComponent);
}
export function removeSkinPluginComponent(input: SkinPluginDocument, componentId: string): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
componentIndex(document, componentId);
return checked({ schemaVersion: 3, components: document.components.filter((component) => component.id !== componentId) });
}
export function moveSkinPluginComponent(
input: SkinPluginDocument,
componentId: string,
direction: -1 | 1,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const from = componentIndex(document, componentId);
const to = from + direction;
if (to < 0 || to >= document.components.length) return document;
const components = [...document.components];
[components[from], components[to]] = [components[to], components[from]];
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
parentPath: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => {
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const children = [...(parent.children ?? []), node as SkinPluginNode];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function addSkinPluginNodeSibling(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot have siblings.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index + 1, 0, node as SkinPluginNode);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => ({
...component,
root: replaceNodeAtPath(component.root, path, node as SkinPluginNode),
}));
}
export function removeSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be removed; delete the component instead.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index, 1);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function moveSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
direction: -1 | 1,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be reordered.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const children = [...(parent.children ?? [])];
const from = path[path.length - 1];
const to = from + direction;
assertChildIndex(from, children.length);
if (from < 0 || from >= children.length || to < 0 || to >= children.length) return component;
[children[from], children[to]] = [children[to], children[from]];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceNodeAtPath(root: SkinPluginNode, path: readonly number[], replacement: SkinPluginNode): SkinPluginNode {
if (!path.length) return replacement;
const [index, ...rest] = path;
const children = [...(root.children ?? [])];
assertChildIndex(index, children.length);
children[index] = replaceNodeAtPath(children[index], rest, replacement);
return { ...root, children };
}
export function getSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
const document = editableSkinPluginDocument(input);
return nodeAt(document.components[componentIndex(document, componentId)], path);
}
/** Give a duplicated subtree fresh stable layout parts so it cannot alias its source nodes. */
export function duplicateSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
const document = editableSkinPluginDocument(input);
const component = document.components[componentIndex(document, componentId)];
const source = nodeAt(component, path);
const usedParts = new Set<string>();
const exclude = (node: SkinPluginNode, currentPath: readonly number[]): void => {
if (currentPath.length === path.length && currentPath.every((index, position) => index === path[position])) return;
if (node.part) usedParts.add(node.part);
node.children?.forEach((child, index) => exclude(child, [...currentPath, index]));
};
exclude(component.root, []);
const copy = JSON.parse(JSON.stringify(source)) as SkinPluginNode;
const refreshParts = (node: SkinPluginNode): void => {
if (node.part) {
const stem = node.part.slice(0, 54) + "-copy";
let candidate = stem;
let suffix = 2;
while (usedParts.has(candidate)) {
const tail = "-" + suffix++;
candidate = stem.slice(0, 64 - tail.length) + tail;
}
node.part = candidate;
usedParts.add(candidate);
}
node.children?.forEach(refreshParts);
};
refreshParts(copy);
return copy;
}
+63 -2
View File
@@ -144,6 +144,25 @@ test("starting screen share from a skin host widget requires its own permission"
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.screen-share-start");
});
test("schema v3 host audio controls require read and control permissions while v2 remains compatible", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "voice.audio-controls" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control"];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control", "audio.output.control"];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].widget, "voice.audio-controls");
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
legacyDocument.components[0].permissions = [];
assert.equal(parseSkinPluginDocument(legacyDocument).components[0].root.children?.[0].widget, "voice.audio-controls");
});
test("KAAK v3 example splits validated channel and member data by component", async () => {
const source = await readFile(new URL("../../docs/examples/kaak-voice/components.json", import.meta.url), "utf8");
const parsed = parseSkinPluginJson(source);
@@ -229,10 +248,52 @@ test("skin plugins can repeat channel members only under a channel alias and wit
errorCode(() => parseSkinPluginDocument(outsideChannel), "SKIN_PLUGIN_REPEAT_INVALID");
});
test("skin plugin never dispatches host actions from typing or selection changes", () => {
test("skin plugins keep live typing local but can run host actions on committed changes", () => {
const document = validDocument();
document.components[0].root.children![0].events = { change: "join" };
const input = document.components[0].root.children![0];
input.events = { input: "join" };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_EVENT_INVALID");
input.events = { change: "join" };
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].events?.change, "join");
});
test("skin conditions can compare public repeated data with local component state", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].state = { selectedchannel: "" };
document.components[0].root.children![0].when = {
path: "state.selectedchannel",
equals: "{{channel.id}}",
};
const parsed = parseSkinPluginDocument(document);
assert.deepEqual(parsed.components[0].root.children?.[0].when, {
path: "state.selectedchannel",
equals: "{{channel.id}}",
});
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
errorCode(() => parseSkinPluginDocument(legacyDocument), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
document.components[0].root.children![0].when!.equals = "{{channel.address}}";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_BINDING_INVALID");
});
test("schema v3 can render empty states only for permissioned public collections", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions.push("chat.channel.read");
document.components[0].root.children = [{
tag: "p",
when: { path: "chat.messages", empty: true },
children: [{ text: "No messages yet" }],
}];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].when?.empty, true);
document.components[0].permissions.push("session.status.read");
document.components[0].root.children[0].when!.path = "session.status.serverLabel";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_CONDITION_INVALID");
});
test("component schema v3 exposes composable interaction patterns and permission-gated voice actions", () => {
+40 -10
View File
@@ -55,9 +55,23 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
"voice.disconnect-control",
] as const);
export type SkinPluginHostWidget = typeof SKIN_PLUGIN_HOST_WIDGETS[number];
export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostWidget, SkinPluginPermission>> = Object.freeze({
"voice.screen-share-start": "voice.screenShare.control",
const widgetPermissions = (...permissions: SkinPluginPermission[]): readonly SkinPluginPermission[] => Object.freeze(permissions);
export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostWidget, readonly SkinPluginPermission[]>> = Object.freeze({
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
"voice.connection-controls": widgetPermissions("voice.disconnect"),
"voice.disconnect-control": widgetPermissions("voice.disconnect"),
"voice.member-cards": widgetPermissions("session.members.read", "voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-player": widgetPermissions("voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-start": widgetPermissions("voice.screenShare.control"),
"voice.whisper-controls": widgetPermissions("voice.whisper.status.read", "voice.whisper.control"),
});
export function missingSkinPluginWidgetPermission(
widget: SkinPluginHostWidget,
permissions: readonly SkinPluginPermission[],
): SkinPluginPermission | undefined {
return SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[widget]?.find((permission) => !permissions.includes(permission));
}
export type SkinPluginEvent =
| "click" | "dblclick" | "change" | "input" | "submit" | "keydown"
| "keyup" | "contextmenu" | "focus" | "blur" | "pointerdown" | "pointerup"
@@ -84,7 +98,7 @@ export interface SkinPluginNode {
asset?: string;
bindValue?: string;
repeat?: { path: string; as: string };
when?: { path: string; equals?: string | number | boolean };
when?: { path: string; equals?: string | number | boolean; empty?: boolean };
events?: Partial<Record<SkinPluginEvent, string>>;
children?: SkinPluginNode[];
}
@@ -130,7 +144,7 @@ const ELEMENTS = new Set([
const VOID_ELEMENTS = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const ATTRIBUTES = new Set([
"alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "autocomplete", "checked", "class", "colspan", "disabled", "draggable", "fill", "height", "inputmode", "max", "maxlength", "min",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "stroke", "stroke-linecap", "stroke-linejoin",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "step", "stroke", "stroke-linecap", "stroke-linejoin",
"stroke-width", "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2",
]);
const EVENTS = new Set<string>([
@@ -274,7 +288,8 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
if (!isRecord(input)) fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain an object.");
onlyKeys(input, new Set(["schemaVersion", "components"]), "components.json");
if (!SKIN_PLUGIN_SUPPORTED_SCHEMA_VERSIONS.includes(input.schemaVersion as 1 | 2 | 3) || !Array.isArray(input.components)
|| !input.components.length || input.components.length > (input.schemaVersion === 3 ? SKIN_PLUGIN_COMPONENT_LIMIT : 32)) {
|| (input.schemaVersion !== 3 && !input.components.length)
|| input.components.length > (input.schemaVersion === 3 ? SKIN_PLUGIN_COMPONENT_LIMIT : 32)) {
fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json uses an unsupported schema or component count.");
}
const ids = new Set<string>();
@@ -366,8 +381,12 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
if (rawNode.widget !== undefined) {
if (typeof rawNode.widget !== "string" || !HOST_WIDGETS.has(rawNode.widget)) fail("SKIN_PLUGIN_WIDGET_INVALID", "The component requests an unsupported host widget.");
if (page === "demo") fail("SKIN_PLUGIN_WIDGET_INVALID", "Host widgets are available only on the home and voice client pages.");
const requiredPermission = SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[rawNode.widget as SkinPluginHostWidget];
if (requiredPermission && !permissions.includes(requiredPermission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawNode.widget} widget requires ${requiredPermission}.`);
// Preserve existing schema v2 packages; newly authored v3 widgets must declare every
// permission needed by the trusted host UI they embed. Screen-share start was already gated.
const requiredPermission = inputSchemaVersion >= 3 || rawNode.widget === "voice.screen-share-start"
? missingSkinPluginWidgetPermission(rawNode.widget as SkinPluginHostWidget, permissions)
: undefined;
if (requiredPermission) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawNode.widget} widget requires ${requiredPermission}.`);
const widgetOnlyKeys = new Set(["widget", "part", "className", "when"]);
onlyKeys(rawNode, widgetOnlyKeys, "Host widget node");
node.widget = rawNode.widget as SkinPluginHostWidget;
@@ -436,14 +455,25 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
}
if (rawNode.when !== undefined) {
if (!isRecord(rawNode.when)) fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition must be an object.");
onlyKeys(rawNode.when, new Set(["path", "equals"]), "Component condition");
onlyKeys(rawNode.when, new Set(inputSchemaVersion >= 3 ? ["path", "equals", "empty"] : ["path", "equals"]), "Component condition");
const path = boundedText(rawNode.when.path, "condition.path", 120);
for (const permission of bindingPermissions(`{{${path}}}`, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition data requires ${permission}.`);
}
const equals = rawNode.when.equals;
if (equals !== undefined && typeof equals !== "string" && typeof equals !== "number" && typeof equals !== "boolean") fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition comparison must be scalar.");
node.when = { path, ...(equals === undefined ? {} : { equals }) };
const empty = rawNode.when.empty;
if (empty !== undefined && (inputSchemaVersion < 3 || typeof empty !== "boolean" || equals !== undefined)) fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty-collection condition must be a schema v3 boolean and cannot also compare a scalar.");
if (typeof equals === "string") {
if (inputSchemaVersion < 3 && equals.includes("{{")) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Data-bound condition comparisons require schema v3.");
for (const permission of bindingPermissions(equals, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition comparison data requires ${permission}.`);
}
}
if (empty !== undefined && !["chat.messages", "session.channels", "session.members", "favorites.items", "servers.quickList", "screenShare.streams"].includes(path)) {
fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty condition must reference a registered public collection.");
}
node.when = { path, ...(equals === undefined ? {} : { equals }), ...(empty === undefined ? {} : { empty }) };
}
if (rawNode.events !== undefined) {
if (!isRecord(rawNode.events) || Object.keys(rawNode.events).length > (inputSchemaVersion >= 3 ? 18 : 6)) fail("SKIN_PLUGIN_EVENT_INVALID", "Component events must be a small object.");
@@ -451,7 +481,7 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
for (const [event, actionIdValue] of Object.entries(rawNode.events)) {
if (!EVENTS.has(event) || (inputSchemaVersion < 3 && V3_EVENTS.has(event)) || typeof actionIdValue !== "string" || !actions[actionIdValue]) fail("SKIN_PLUGIN_EVENT_INVALID", "Each component event must refer to a declared host action supported by this schema.");
const action = actions[actionIdValue];
if (action.type !== "ui.setState" && (event === "input" || event === "change")) fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed or changed.");
if (action.type !== "ui.setState" && event === "input") fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed; use a committed change or submit event.");
if (action.type !== "ui.setState" && action.type !== "ui.toggleState" && PASSIVE_EVENTS.has(event)) {
fail("SKIN_PLUGIN_EVENT_INVALID", "Voice and host actions require an explicit user activation event.");
}