feat(skins): complete visual component CRUD authoring

This commit is contained in:
illusia committed 2026-10-10 15:53:51 +08:00
1 parent 3fd8e76a98
commit f2e5695bb6
30 files changed
+1858 -511

No files matched your search

@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import test from "node:test";
import { promoteHostEditorToTopLayer } from "./host-editor-top-layer.js";
test("host editors use Popover API top layer when it is available", () => {
const attributes = new Map<string, string>();
let showCount = 0;
const element = {
showPopover() { showCount += 1; },
matches(selector: string) { return selector === ":popover-open" && showCount > 0; },
setAttribute(name: string, value: string) { attributes.set(name, value); },
removeAttribute(name: string) { attributes.delete(name); },
} as unknown as HTMLElement;
promoteHostEditorToTopLayer(element);
promoteHostEditorToTopLayer(element);
assert.equal(attributes.get("popover"), "manual");
assert.equal(showCount, 1, "repeated ref notifications do not reopen an already visible popover");
});
test("host editors keep their ordinary positioning when Popover API is unavailable or fails", () => {
let showCount = 0;
const unsupported = {
setAttribute() { throw new Error("must not add unsupported popover attributes"); },
} as unknown as HTMLElement;
const failingAttributes = new Map<string, string>();
const failing = {
showPopover() { showCount += 1; throw new Error("browser denied popover"); },
setAttribute(name: string, value: string) { failingAttributes.set(name, value); },
removeAttribute(name: string) { failingAttributes.delete(name); },
} as unknown as HTMLElement;
promoteHostEditorToTopLayer(unsupported);
promoteHostEditorToTopLayer(null);
promoteHostEditorToTopLayer(failing);
assert.equal(showCount, 1);
assert.equal(failingAttributes.has("popover"), false, "a failed top-layer promotion leaves the CSS fallback visible");
});
+15
View File
@@ -0,0 +1,15 @@
export function promoteHostEditorToTopLayer(element: HTMLElement | null): void {
const popover = element as (HTMLElement & {
showPopover?: () => void;
matches?: (selectors: string) => boolean;
}) | null;
if (!popover || typeof popover.showPopover !== "function") return;
try {
if (popover.matches?.(":popover-open")) return;
popover.setAttribute("popover", "manual");
popover.showPopover();
} catch {
popover.removeAttribute("popover");
}
}
@@ -350,6 +350,12 @@ test("generated UI rejects executable elements, event handlers, and network/navi
expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { "data-ws-part": "spoofed" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
});
test("generated UI cannot create browser top-layer popovers that cover host controls", () => {
expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { popover: "manual" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertarget: "host-editor" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertargetaction: "show" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
});
test("generated UI enforces component and per-node child limits", () => {
const tooManyComponents = JSON.stringify({
schemaVersion: 4,
@@ -6,7 +6,7 @@ import {
} from "./skin-extension-wasm-ui-loop.js";
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
function uiOutput(count: number): string {
function uiOutput(count: number, handlerId = "increment"): string {
return JSON.stringify({
schemaVersion: 5,
components: [{
@@ -15,7 +15,7 @@ function uiOutput(count: number): string {
page: "voice",
accessibleName: "Local counter",
state: { count },
root: { tag: "button", events: { click: "increment" }, children: [{ text: String(count) }] },
root: { tag: "button", events: { click: handlerId }, children: [{ text: String(count) }] },
}],
});
}
@@ -76,6 +76,30 @@ test("runtime data refresh reruns the guest without fabricating a user event", a
loop.close();
});
test("host-rejected UI output does not replace the callback document", async () => {
const jobs: SkinExtensionUiInput[] = [];
const rejectedOutput = uiOutput(1, "unaccepted");
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun(input) {
jobs.push(input);
return {
result: Promise.resolve({ uiOutput: input.event ? rejectedOutput : uiOutput(0) }),
close: () => undefined,
};
},
onOutput(output) {
if (output === rejectedOutput) throw new Error("Host rejected the generated document.");
},
});
assert.equal(await loop.start(), true);
assert.equal(await loop.dispatch(clickInput(0)), false);
assert.equal(loop.output, uiOutput(0));
assert.equal(await loop.dispatch(clickInput(1, "unaccepted")), false);
assert.equal(jobs.length, 2, "callbacks from a host-rejected document must not be accepted");
loop.close();
});
test("Wasm UI callback queue is bounded and close cancels active and waiting work", async () => {
let rejectActive!: (error: Error) => void;
let held = false;
@@ -74,13 +74,13 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
activeRun = run;
const result = await run.result;
if (closed || activeRun !== run) return false;
lastState = { ...input.state };
if (result.uiOutput !== null) {
const nextDocument = options.parseOutput?.(result.uiOutput) ?? parseSkinExtensionUiOutput(result.uiOutput);
await options.onOutput?.(result.uiOutput, nextDocument, input);
output = result.uiOutput;
document = nextDocument;
await options.onOutput?.(output, nextDocument, input);
}
lastState = { ...input.state };
return true;
} catch (error) {
if (!closed) report(error);
+4
View File
@@ -48,6 +48,7 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con
assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/);
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { d\\69splay: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { position: fixed; inset: 0; z-index: 99999; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.member"] { padding: 30px; transform: scale(1.2); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { font-size: 3rem; line-height: 1; white-space: nowrap; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
@@ -62,6 +63,9 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con
await assert.rejects(importSkinPack(makeSkin(".internal-class { color: red; }")), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.voice-card"].private-component { color: red; }')), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: image-set("https://example.invalid/remote.png" 1x); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l("https://example.invalid/escaped.png"); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l(h\\74 tps\\3a //example.invalid/escaped-scheme.png); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('@font-face { font-family: "Local Font"; src: l\\6f cal("Arial"); } [data-ws-part="home"] { color: teal; }')), (error: unknown) => error instanceof Error && error.message.includes("local() is not allowed"));
});
test("custom skins can override theme appearance without !important or private class selectors", () => {
+10 -342
View File
@@ -1,7 +1,6 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import { unzipSync } from "fflate";
import { compileSkinCss as compileSharedSkinCss, rewriteSkinCssAssets, SkinCssValidationError } from "../../../src/shared/skin-css.js";
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { validateSkinExtensionWasmBytes, validateSkinExtensionWasmImportsAndExports } from "./skin-extension-wasm-policy.js";
@@ -21,43 +20,6 @@ const MAX_CSS_BYTES = 512 * 1024;
const MAX_CONTENT_BYTES = 256 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
const MAX_FONT_BYTES = 4 * 1024 * 1024;
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]);
const LAYOUT_AFFECTING_PROPERTIES = new Set([
"all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size",
"min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing",
"gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x",
"overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility",
"pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate",
"perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name",
"container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font",
"font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap",
"text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim",
"line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift",
"box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing",
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
]);
const ZIP_EOCD = 0x06054b50;
const ZIP_CENTRAL_FILE = 0x02014b50;
@@ -303,17 +265,14 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
const objectUrls: string[] = [];
try {
const root = postcss.parse(css, { from: undefined });
root.walkDecls((declaration) => {
declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => {
const rewritten = rewriteSkinCssAssets(css, (assetPath) => {
const blob = assets[assetPath];
if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING");
const url = URL.createObjectURL(blob);
objectUrls.push(url);
return url;
});
});
return { css: root.toString(), objectUrls };
return { css: rewritten, objectUrls };
} catch (error) {
objectUrls.forEach((url) => URL.revokeObjectURL(url));
throw error;
@@ -561,306 +520,15 @@ function parseContent(bytes: Uint8Array): SkinContent {
}
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"], pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
let root: postcss.Root;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`;
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
const fontFamilyNames = new Map<string, string>();
const hideableRules = new WeakSet<Rule>();
let nodeCount = 0;
root.walk((node) => {
nodeCount += 1;
if (nodeCount > 12000) throw new SkinPackError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY");
});
root.walkAtRules((rule: AtRule) => {
const name = rule.name.toLowerCase();
if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`);
if (name.endsWith("keyframes")) {
const keyframeName = rule.params.trim();
if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers.");
keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`);
rule.params = `${namespace}-${keyframeName}`;
} else if (name === "layer") {
const layers = rule.params.split(",").map((layer) => layer.trim());
if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) {
throw rule.error("Skin CSS must use named @layer values so layer names can be isolated.");
}
rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", ");
} else if (name === "font-face") {
if (/\blocal\s*\(/i.test(rule.toString())) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package.");
const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family");
if (!family) throw rule.error("Each @font-face rule must declare font-family.");
const originalFamily = parseSingleFontFamily(family.value);
const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`;
fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily);
family.value = `"${scopedFamily}"`;
}
});
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
selectors.each((selector) => {
const text = selector.toString().trim();
if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
if (error instanceof SkinPackError) throw error;
throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`);
}
});
const referencedKeyframes = new Set<string>();
const nonOptionalKeyframes = new Set<string>();
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
const optionalTarget = hideableRules.has(rule);
rule.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
if (property !== "animation" && property !== "animation-name") return;
const value = declaration.value;
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
return;
}
for (const name of keyframeNames.keys()) {
if (!referencesCssIdentifier(value, name)) continue;
referencedKeyframes.add(name);
if (!optionalTarget) nonOptionalKeyframes.add(name);
}
});
});
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
.filter((name) => !nonOptionalKeyframes.has(name))
.map((name) => keyframeNames.get(name)!));
root.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
const value = declaration.value.trim();
const owningRule = findOwningRule(declaration);
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.`
: "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase();
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) {
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
const removesVisual = property === "all"
|| (property === "display" && compactValue === "none")
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
if (removesVisual && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(value))
|| (property === "clip-path" && /inset\(\s*50%/i.test(value))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value));
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
const blob = assets[assetPath];
if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
return `wskin-asset:${encodeURIComponent(assetPath)}`;
});
});
return { css: root.toString(), warnings: [...warnings] };
}
function targetsOnlyOptionalVisualParts(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false;
const attribute = item.nodes[0];
if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false;
const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, "");
return OPTIONAL_VISUAL_PARTS.has(part);
});
} catch {
return false;
try { return compileSharedSkinCss(source, id, assets, schemaVersion, pluginId); }
catch (error) {
const cssError = error instanceof SkinCssValidationError
? error
: new SkinCssValidationError(error instanceof Error ? error.message : "The CSS file is invalid.", "SKIN_CSS_INVALID");
throw new SkinPackError(cssError.message, cssError.code);
}
}
function selectorUsesPublicHook(selector: string, allowCustomClasses = false): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
let scoped = false;
let usesPrivateName = false;
item.walk((node) => {
if (node.type === "attribute" && ["data-ws-part", "data-ws-page", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].includes(node.attribute.toLowerCase())) scoped = true;
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true;
});
return scoped && !usesPrivateName;
});
} catch {
return false;
}
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
if (parent.type === "rule") return parent as Rule;
parent = parent.parent;
}
return null;
}
function findKeyframesRule(rule: Rule): AtRule | null {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule;
parent = parent.parent;
}
return null;
}
function referencesCssIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
}
function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
const parsed = valueParser(value);
const resolvePackageAsset = (rawValue: string): string => {
const raw = rawValue.trim();
if (!raw || raw.startsWith("#")) throw new SkinPackError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE");
const isInternalMarker = raw.startsWith("wskin-asset:");
if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinPackError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE");
let path: string;
try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); }
catch { throw new SkinPackError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); }
return resolve(path);
};
const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => {
for (const node of nodes) {
if (node.type === "function" && node.value.toLowerCase() === "url") {
const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim();
node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }];
node.before = "";
node.after = "";
continue;
}
if (node.type === "function" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-webkit-image-set")) {
for (const child of node.nodes) {
if (child.type === "string") child.value = resolvePackageAsset(child.value);
else if (child.type === "function") visit([child]);
}
continue;
}
if (node.type === "function") visit(node.nodes, inImageSet);
else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value);
}
};
visit(parsed.nodes);
return parsed.toString();
}
function parseSingleFontFamily(value: string): string {
const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment");
if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) {
throw new SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY");
}
return parsed[0].value.trim();
}
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
const parsed = valueParser(value);
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const keyframe = keyframes.get(node.value);
if (keyframe) node.value = keyframe;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
}
return parsed.toString();
}
function normalizeAssetPath(raw: string): string {
let path = raw.split(/[?#]/, 1)[0];
try { path = decodeURIComponent(path); } catch { throw new SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); }
if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH");
const segments: string[] = [];
for (const segment of path.split("/")) {
if (!segment || segment === ".") continue;
if (segment === "..") {
if (!segments.length) throw new SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH");
segments.pop();
} else {
segments.push(segment);
}
}
if (!segments.length) throw new SkinPackError("An asset URL must point to a package file.", "SKIN_ASSET_PATH");
return segments.join("/");
}
function hasKeyframesAncestor(rule: Rule): boolean {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true;
parent = parent.parent;
}
return false;
}
function assetMimeType(path: string): string | null {
const extension = path.split(".").at(-1)?.toLowerCase();
switch (extension) {
@@ -58,3 +58,33 @@ test("a missing plugin asset releases a cached URL instead of returning stale ar
URL.revokeObjectURL = originalRevoke;
}
});
test("plugin asset URLs are released when their final component reference is removed", () => {
const originalCreate = URL.createObjectURL;
const originalRevoke = URL.revokeObjectURL;
const created: string[] = [];
const revoked: string[] = [];
URL.createObjectURL = () => {
const url = `blob:skin-retain-${created.length + 1}`;
created.push(url);
return url;
};
URL.revokeObjectURL = (url) => { revoked.push(url); };
try {
const cache = createSkinPluginAssetUrlCache();
cache.resolve("assets/used.png", { "assets/used.png": new Blob(["used"]) });
cache.resolve("assets/removed.png", { "assets/removed.png": new Blob(["removed"]) });
cache.retain(["assets/used.png"]);
assert.deepEqual(revoked, ["blob:skin-retain-2"]);
assert.equal(cache.size, 1);
cache.retain([]);
assert.deepEqual(revoked, ["blob:skin-retain-2", "blob:skin-retain-1"]);
assert.equal(cache.size, 0);
} finally {
URL.createObjectURL = originalCreate;
URL.revokeObjectURL = originalRevoke;
}
});
@@ -26,6 +26,10 @@ export function createSkinPluginAssetUrlCache() {
clear(): void {
for (const path of urls.keys()) release(path);
},
retain(paths: Iterable<string>): void {
const retained = new Set(paths);
for (const path of urls.keys()) if (!retained.has(path)) release(path);
},
get size(): number { return urls.size; },
};
}
+36 -6
View File
@@ -13,7 +13,7 @@ import {
removeSkinPluginNode,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
@@ -101,7 +101,7 @@ test("component order is editable and stays within the selected skin document",
test("duplicating a nested component node gives copied layout parts unique stable IDs", () => {
const source = document();
source.components[0].root.children![0] = {
tag: "div", part: "message", children: [{ tag: "span", part: "author", text: "Author" }],
tag: "div", part: "message", children: [{ tag: "span", part: "author", children: [{ text: "Author" }] }],
};
const copy = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(copy.part, "message-copy");
@@ -109,6 +109,24 @@ test("duplicating a nested component node gives copied layout parts unique stabl
assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i);
});
test("repeated node duplication skips existing layout part IDs", () => {
const source = document();
source.components[0].root.children = [
{ tag: "div", part: "message", children: [{ tag: "span", part: "author" }] },
{ tag: "div", part: "message-copy", children: [{ tag: "span", part: "author-copy" }] },
{ tag: "div", part: "message-copy-2", children: [{ tag: "span", part: "author-copy-2" }] },
];
const first = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(first.part, "message-copy-3");
assert.equal(first.children?.[0].part, "author-copy-3");
const withFirstCopy = addSkinPluginNodeSibling(source, "voice-panel", [0], first);
const second = duplicateSkinPluginNode(withFirstCopy, "voice-panel", [0]);
assert.equal(second.part, "message-copy-4");
assert.equal(second.children?.[0].part, "author-copy-4");
});
test("component editor rejects unsafe markup and invalid permission/action combinations", () => {
assert.throws(() => addSkinPluginNode(document(), "voice-panel", [], { tag: "script" }), /unsupported HTML element/i);
assert.throws(() => replaceSkinPluginNode(document(), "voice-panel", [0], {
@@ -124,11 +142,23 @@ test("component editor rejects unsafe markup and invalid permission/action combi
});
test("older package trees upgrade to editable schema v3 without losing their component", () => {
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
for (const schemaVersion of [1, 2]) {
const legacy = { ...document(), schemaVersion } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
}
const normalizedV1 = parseSkinPluginDocument({ ...document(), schemaVersion: 1 });
assert.equal(normalizedV1.components[0].mode, "widget", "the package parser materializes the schema-v1 default mode");
assert.equal(editableSkinPluginDocument(normalizedV1).schemaVersion, 3,
"revalidating a normalized legacy package must safely strip the parser-generated default before migration");
assert.throws(() => parseSkinPluginDocument({
...document(), schemaVersion: 1,
components: [{ ...document().components[0], mode: "surface" }],
}), /Page surfaces require components schema version 2/i);
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const legacyWithWidget = structuredClone(legacy);
legacyWithWidget.components[0].permissions = [];
legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] };
@@ -45,3 +45,51 @@ test("Wasm worker governor rejects queued work after the bounded wait", async ()
assert.equal(governor.pendingRuns, 0);
release();
});
test("Wasm worker governor stays bounded and drains a saturated burst in FIFO order", async () => {
const maxConcurrentRuns = 2;
const maxPendingRuns = 64;
const burstSize = 2_000;
const governor = createSkinRuntimePluginWasmGovernor({
maxConcurrentRuns,
maxPendingRuns,
queueTimeoutMs: 10_000,
});
const started: number[] = [];
let active = 0;
let peakActive = 0;
const acquisitions = Array.from({ length: burstSize }, (_, index) => governor.acquire(new AbortController().signal)
.then((release) => {
active += 1;
peakActive = Math.max(peakActive, active);
started.push(index);
return {
index,
release: () => {
active -= 1;
release();
},
};
}, (error: unknown) => ({ index, error })));
assert.equal(governor.activeRuns, maxConcurrentRuns);
assert.equal(governor.pendingRuns, maxPendingRuns);
const overflow = await Promise.all(acquisitions.slice(maxConcurrentRuns + maxPendingRuns));
assert.equal(overflow.length, burstSize - maxConcurrentRuns - maxPendingRuns);
assert.ok(overflow.every((item) => "error" in item
&& item.error instanceof SkinRuntimePluginWasmGovernorError
&& item.error.code === "SKIN_EXTENSION_WASM_QUEUE_FULL"));
for (let index = 0; index < maxConcurrentRuns + maxPendingRuns; index += maxConcurrentRuns) {
const batch = await Promise.all(acquisitions.slice(index, index + maxConcurrentRuns));
assert.ok(batch.every((item) => "release" in item));
batch.forEach((item) => {
if ("release" in item) item.release();
});
}
assert.deepEqual(started, Array.from({ length: maxConcurrentRuns + maxPendingRuns }, (_, index) => index));
assert.equal(peakActive, maxConcurrentRuns);
assert.equal(governor.activeRuns, 0);
assert.equal(governor.pendingRuns, 0);
});
@@ -198,3 +198,43 @@ test("approved Wasm entries run as disposable workers with bounded interpreter o
else Reflect.deleteProperty(globalThis, "window");
}
});
test("a worker that exceeds the execution deadline is terminated and releases its handle", async () => {
const { files, approval } = await approvedFiles();
const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
let terminated = 0;
class HangingWorker {
onmessage: ((event: MessageEvent<unknown>) => void) | null = null;
onmessageerror: (() => void) | null = null;
onerror: (() => void) | null = null;
postMessage(): void {
queueMicrotask(() => this.onmessage?.({ data: { type: "running" } } as MessageEvent<unknown>));
}
terminate(): void { terminated += 1; }
}
Object.defineProperty(globalThis, "Worker", { configurable: true, value: HangingWorker });
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
try {
const handle = await createSkinRuntimePluginWasmSandbox({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin,
approval,
files,
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
});
await handle.ready;
await assert.rejects(handle.result, (error: unknown) =>
error instanceof Error && "code" in error && error.code === "SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT");
await handle.stopped;
assert.equal(handle.closeReason, "execution-timeout");
assert.equal(handle.closed, true);
assert.equal(terminated, 1, "the host must terminate the worker when its execution deadline expires");
} finally {
if (previousWorker) Object.defineProperty(globalThis, "Worker", previousWorker);
else Reflect.deleteProperty(globalThis, "Worker");
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
@@ -4,6 +4,8 @@ import test from "node:test";
import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmLargeUiOutputProbe,
createSkinExtensionWasmOversizedUiOutputProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmUiInputProbe,
createSkinExtensionWasmUiOutputProbe,
@@ -88,6 +90,12 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
"the interpreter must accept payloads larger than the previous 16 KiB cap");
assert.equal(run(createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true)).error, 12,
"the interpreter must reject more than one UI payload per execution");
const largeUiOutput = `{"text":"${"x".repeat(240 * 1024)}"}`;
const largeUiResult = run(createSkinExtensionWasmLargeUiOutputProbe(240 * 1024));
assert.equal(largeUiResult.error, 0, "the interpreter must accept a large payload that remains under the output limit");
assert.equal(largeUiResult.uiOutput, largeUiOutput);
assert.equal(run(createSkinExtensionWasmOversizedUiOutputProbe()).error, 12,
"the interpreter must reject UI output beyond its 256 KiB cap before copying it");
const memory = runtime.memory;
const currentPages = memory.buffer.byteLength / (64 * 1024);