scaling-swarms / backend /src /shared /embed-contract.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(mcp): chart and publish tools, structured errors, JSON 404s
2525af6
Raw History Blame Contribute Delete
4.71 kB
/**
* Static checks of an embed fragment against the embed contract
* (backend/embed-kit/contract.md), shared by the Embed Studio and the MCP
* embed tools. Errors mean the fragment cannot work in the article; warnings
* are contract rules a renderer cannot verify cheaply. The browser checker
* (src/embed-check) covers what only rendering shows.
*/
export const MAX_EMBED_SIZE = 512_000;
export const EMBED_NAME_RE = /^[a-z0-9][a-z0-9-]{0,59}\.html$/;
export interface ContractReport {
errors: string[];
warnings: string[];
/** Root class found on the first element, if any. */
rootClass: string | null;
}
/**
* Slugify an arbitrary filename hint into a safe kebab-case slug.
* Keeps ASCII letters/digits/dashes, collapses whitespace, lowercases.
*/
export function slugify(raw: string): string {
const base = raw
.toLowerCase()
.replace(/\.html?$/i, "")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 55);
return base || "chart";
}
/**
* Given a slug, find a unique .html filename. If the desired name is free,
* return it; otherwise append `-2`, `-3`, ...
*/
export function ensureUniqueFilename(
slug: string,
taken: (name: string) => boolean,
currentSrc: string,
): string {
const base = `${slug}.html`;
if (base === currentSrc) return base;
if (!taken(base)) return base;
let i = 2;
while (taken(`${slug}-${i}.html`)) i++;
return `${slug}-${i}.html`;
}
const CONFIG_BLOCK_RE = /<script\b[^>]*\bdata-embed-config\b[^>]*>([\s\S]*?)<\/script>/i;
const HARDCODED_COLOR = /(?:fill|stroke|color|background)["']?\s*[:=,]\s*["']?#[0-9a-f]{3,8}\b/i;
export function validateEmbedHtml(html: string, opts: { banner?: boolean } = {}): ContractReport {
const errors: string[] = [];
const warnings: string[] = [];
const trimmed = html.trim();
if (!trimmed) return { errors: ["html is empty"], warnings, rootClass: null };
if (trimmed.length > MAX_EMBED_SIZE) {
errors.push(`html is ${trimmed.length} characters, the limit is ${MAX_EMBED_SIZE}: aggregate or downsample the data`);
}
if (/<\s*(html|head|body)\b/i.test(trimmed) || /<!doctype/i.test(trimmed)) {
errors.push("send a fragment (root <div> + <style> + <script>), not a full HTML document");
}
const first = /^<([a-z][\w-]*)\b([^>]*)>/i.exec(trimmed);
let rootClass: string | null = null;
if (!first) {
errors.push("the fragment must start with its root element, e.g. <div class=\"d3-my-chart\"></div>");
} else {
const cls = /\bclass\s*=\s*["']([^"']+)["']/i.exec(first[2]);
rootClass = cls ? cls[1].trim().split(/\s+/)[0] : null;
if (first[1].toLowerCase() !== "div") warnings.push(`the root is a <${first[1]}>; the contract expects a <div>`);
if (!rootClass) errors.push("the root element needs a unique, descriptive class (d3- prefix)");
if (/\bid\s*=/.test(first[2])) warnings.push("no id on the root element: two copies of the chart would clash");
}
const mounts = [...trimmed.matchAll(/Embed\.mount\(\s*['"`]([^'"`]+)['"`]/g)].map((m) => m[1]);
if (!mounts.length) {
errors.push("the script must call Embed.mount('<root class>', setup) at top level");
} else if (rootClass && !mounts.includes(rootClass)) {
errors.push(`Embed.mount('${mounts[0]}') does not match the root class "${rootClass}"`);
}
if (/DOMContentLoaded|window\.onload/.test(trimmed)) {
warnings.push("do not wait for DOMContentLoaded: call Embed.mount at top level");
}
if (/<script\b[^>]*\bsrc\s*=\s*["'][^"']*d3[^"']*["']/i.test(trimmed)) {
warnings.push("D3 is loaded by the runtime: remove the D3 <script src>");
}
if (/\bfetch\(|d3\.(csv|json|tsv)\(/.test(trimmed)) {
warnings.push("the iframe cannot fetch files: inline the data in the script");
}
if (HARDCODED_COLOR.test(trimmed) && !/ctx\.colors\(/.test(trimmed)) {
warnings.push("hardcoded colors break one of the two themes: use CSS variables or ctx.colors()");
}
if (!opts.banner && !/\.describe\(/.test(trimmed)) {
warnings.push("no ctx.describe(): screen readers get nothing");
}
const block = CONFIG_BLOCK_RE.exec(trimmed);
if (block) {
try {
const parsed = JSON.parse(block[1]);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
errors.push("the data-embed-config block must be a JSON object of settings");
}
} catch (err) {
errors.push(`the data-embed-config block is not valid JSON: ${(err as Error).message}`);
}
} else if (!opts.banner) {
warnings.push("no data-embed-config block: authors cannot tweak the chart without the AI");
}
return { errors, warnings, rootClass };
}