The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
[OPEND-5052] fix(studio): reliably select local and project fonts
罗高252b1728c3a1
diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex fba9eef4..d8879369 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -230,6 +230,8 @@ flowchart LRLocal asset import through phase-one MCP and internal legacy tools allows at most 500 MB (500000000 bytes) per file, using a shared byte check before and after copying. The OpenMotion workspace host enforces the same decimal threshold before forwarding Studio uploads to the pinned engine, counting each complete multipart request including all files and form overhead; it rejects oversized requests before saving files, including streamed uploads without Content-Length. Existing project media and historical restoration are not re-imports.+The font picker offers detected local fonts, imported project fonts and fonts declared by the current composition, retaining the selected family even when it is unavailable. It does not suggest remote catalogs or uninstalled presets. Installed-font discovery reads actual family/weight metadata from the engine's system font directories; selecting a family copies its nearest upright regular face into project assets. TTC faces are extracted with their original glyph and shaping tables. Imports use the same metadata and collection preparation, then require successful browser decoding before upload and application. Project listings retain font metadata across reopening, and composition fonts are discovered from the preview document rather than Studio chrome. Reads and preparation retain the shared 500 MB cap and no-follow file guard; original imported collections and authored declarations are not rewritten automatically.+| 数据范围 | 当前内容 | 可移交 / 恢复语义 || --- | --- | --- || 原生工程 | HTML/CSS/JS、媒体、字体、Studio manifest | 是继续编辑与渲染的输入;按工程打包,不依赖生成供应商的临时输出 URL |diff --git a/package-lock.json b/package-lock.jsonindex a6dca314..7609c068 100644--- a/package-lock.json+++ b/package-lock.json@@ -32,6 +32,7 @@"acorn": "8.19.0","cn": "0.2.4","dockview-react": "8.3.1",+ "fontkit": "2.0.4","gsap": "3.15.0","hyperframes": "0.9.7","mediabunny": "1.45.3",diff --git a/package.json b/package.jsonindex 6c69b87e..eb472e64 100644--- a/package.json+++ b/package.json@@ -55,6 +55,7 @@"acorn": "8.19.0","cn": "0.2.4","dockview-react": "8.3.1",+ "fontkit": "2.0.4","gsap": "3.15.0","hyperframes": "0.9.7","mediabunny": "1.45.3",diff --git a/shared/studio-fonts.ts b/shared/studio-fonts.tsnew file mode 100644index 00000000..f10a0c2a--- /dev/null+++ b/shared/studio-fonts.ts@@ -0,0 +1,136 @@+import { constants } from 'node:fs';+import { open, stat } from 'node:fs/promises';+import { MAX_ASSET_BYTES } from './asset-limits.ts';++export type FontMetadata = { family: string; weight: string; style: 'normal' | 'italic'; postscriptName: string };+type FontParser = (bytes: Buffer) => any;++export async function readFontFile(filename: string): Promise<Buffer> {+ const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);+ try {+ const info = await file.stat();+ if (!info.isFile() || info.size > MAX_ASSET_BYTES) throw new Error('Font must be a file of at most 500 MB');+ const bytes = Buffer.alloc(info.size);+ for (let offset = 0; offset < bytes.length;) {+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);+ if (!bytesRead) throw new Error('Font changed while reading');+ offset += bytesRead;+ }+ return bytes;+ } finally { await file.close(); }+}++export function fontFaces(bytes: Buffer, parse: FontParser): Array<FontMetadata & { index: number }> {+ if (bytes.length > MAX_ASSET_BYTES) throw new Error('Font exceeds 500 MB');+ const signature = bytes.toString('ascii', 0, 4);+ if (signature === 'ttcf') {+ if (bytes.length < 12) throw new Error('Invalid font collection');+ const count = bytes.readUInt32BE(8);+ if (!count || count > 4096 || 12 + count * 4 > bytes.length) throw new Error('Invalid font collection');+ }+ if ((signature === 'wOFF' || signature === 'wOF2') && (bytes.length < 20 || bytes.readUInt32BE(16) > MAX_ASSET_BYTES)) throw new Error('Invalid compressed font size');+ const parsed = parse(bytes);+ return (parsed.fonts ?? [parsed]).map((font: any, index: number) => {+ const family = font.getName('preferredFamily') || font.familyName;+ if (typeof family !== 'string' || !family.trim() || !font.postscriptName) throw new Error('Font has no family or face name');+ const axis = font.variationAxes?.wght;+ return { family, index, postscriptName: font.postscriptName,+ weight: axis ? `${axis.min} ${axis.max}` : String(font['OS/2']?.usWeightClass || 400),+ style: font.italicAngle || /italic|oblique/i.test(font.subfamilyName ?? '') ? 'italic' : 'normal' };+ });+}++function checksum(bytes: Buffer): number {+ let sum = 0;+ for (let offset = 0; offset < bytes.length; offset += 4) sum = (sum + bytes.readUInt32BE(offset)) >>> 0;+ return sum;+}++/** Preserve every shaping/glyph table while making one TTC face a standalone font. */+export function extractCollectionFace(bytes: Buffer, index: number): Buffer {+ const count = bytes.readUInt32BE(8);+ if (count > 4096 || index < 0 || index >= count || 12 + count * 4 > bytes.length) throw new Error('Invalid font collection');+ const start = bytes.readUInt32BE(12 + index * 4);+ const tables = bytes.readUInt16BE(start + 4);+ if (!tables || tables > 4096 || start + 12 + tables * 16 > bytes.length) throw new Error('Invalid font directory');+ const entries: Array<{ tag: string; offset: number; length: number }> = [];+ for (let i = 0; i < tables; i++) {+ const entry = start + 12 + i * 16;+ const tag = bytes.toString('ascii', entry, entry + 4);+ const offset = bytes.readUInt32BE(entry + 8), length = bytes.readUInt32BE(entry + 12);+ if (offset + length > bytes.length) throw new Error('Invalid font table');+ if (tag !== 'DSIG') entries.push({ tag, offset, length });+ }+ const head = entries.find(entry => entry.tag === 'head');+ if (!head || head.length < 12) throw new Error('Font has no valid head table');+ const size = 12 + entries.length * 16 + entries.reduce((sum, entry) => sum + Math.ceil(entry.length / 4) * 4, 0);+ if (size > MAX_ASSET_BYTES) throw new Error('Font exceeds 500 MB');+ const result = Buffer.alloc(size);+ bytes.copy(result, 0, start, start + 4);+ const power = 2 ** Math.floor(Math.log2(entries.length));+ result.writeUInt16BE(entries.length, 4); result.writeUInt16BE(power * 16, 6);+ result.writeUInt16BE(Math.log2(power), 8); result.writeUInt16BE(entries.length * 16 - power * 16, 10);+ let next = 12 + entries.length * 16, headOffset = 0;+ entries.forEach((entry, i) => {+ const directory = 12 + i * 16, padded = Math.ceil(entry.length / 4) * 4;+ bytes.copy(result, next, entry.offset, entry.offset + entry.length);+ if (entry.tag === 'head') { headOffset = next; result.writeUInt32BE(0, next + 8); }+ result.write(entry.tag, directory, 4, 'ascii');+ result.writeUInt32BE(checksum(result.subarray(next, next + padded)), directory + 4);+ result.writeUInt32BE(next, directory + 8); result.writeUInt32BE(entry.length, directory + 12);+ next += padded;+ });+ result.writeUInt32BE((0xB1B0AFBA - checksum(result)) >>> 0, headOffset + 8);+ return result;+}++function faceScore(face: FontMetadata): number {+ const [min, max = min] = face.weight.split(' ').map(Number);+ return (face.style === 'normal' ? 0 : 10000) + (min <= 400 && max >= 400 ? 0 : Math.min(Math.abs(min - 400), Math.abs(max - 400)));+}++export function prepareFont(bytes: Buffer, parse: FontParser, requestedFamily?: string) {+ const faces = fontFaces(bytes, parse);+ const family = requestedFamily ?? faces.find(face => !face.family.startsWith('.'))?.family;+ const candidates = faces.filter(face => face.family.toLowerCase() === family?.toLowerCase());+ candidates.sort((a, b) => faceScore(a) - faceScore(b));+ const face = candidates[0];+ if (!face) throw new Error('Font family is unavailable');+ const data = bytes.toString('ascii', 0, 4) === 'ttcf' ? extractCollectionFace(bytes, face.index) : bytes;+ const signature = data.toString('ascii', 0, 4);+ const format = signature === 'OTTO' ? 'otf' : signature === 'wOF2' ? 'woff2' : signature === 'wOFF' ? 'woff' : 'ttf';+ const { index: _index, ...metadata } = face;+ return { data, format, ...metadata };+}++export function createFontCatalog(paths: string[], parse: FontParser) {+ const metadata = new Map<string, { identity: string; faces: ReturnType<typeof fontFaces> }>();+ const inspect = async (filename: string) => {+ const info = await stat(filename), identity = `${info.mtimeMs}:${info.size}`;+ if (metadata.get(filename)?.identity !== identity) metadata.set(filename, { identity, faces: fontFaces(await readFontFile(filename), parse) });+ return metadata.get(filename)!.faces;+ };+ let installed: Promise<Map<string, { path: string; score: number }>> | undefined;+ const load = () => installed ??= (async () => {+ const families = new Map<string, { path: string; score: number }>();+ for (const filename of new Set(paths)) {+ try { for (const face of await inspect(filename)) if (!face.family.startsWith('.') && (!families.has(face.family) || faceScore(face) < families.get(face.family)!.score)) families.set(face.family, { path: filename, score: faceScore(face) }); }+ catch { /* Unsupported or inaccessible installed fonts are not selectable. */ }+ }+ return families;+ })();+ return { inspect,+ families: async () => [...(await load()).keys()].sort((a, b) => a.localeCompare(b)),+ file: async (family: string) => {+ const match = [...await load()].find(([name]) => name.toLowerCase() === family.toLowerCase());+ if (!match) return null;+ return prepareFont(await readFontFile(match[1].path), parse, match[0]);+ },+ };+}++export function preparedFontResponse(font: ReturnType<typeof prepareFont>): Response {+ return new Response(new Blob([font.data]), { headers: { 'Content-Type': `font/${font.format}`,+ 'Content-Length': String(font.data.length),+ 'X-Font-Metadata': encodeURIComponent(JSON.stringify({ family: font.family, weight: font.weight, style: font.style, postscriptName: font.postscriptName })) } });+}diff --git a/shared/workspace-studio.ts b/shared/workspace-studio.tsindex 7dbe64c7..f8abb6d9 100644--- a/shared/workspace-studio.ts+++ b/shared/workspace-studio.ts@@ -1,6 +1,7 @@import { createServer } from 'node:http';import { createRequire } from 'node:module';-import { readFile, readdir } from 'node:fs/promises';+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { randomUUID } from 'node:crypto';import path from 'node:path';import { pathToFileURL } from 'node:url';import { WorkspaceStore } from '../workspace.ts';@@ -9,6 +10,8 @@ import { isMain } from './entry.ts';import { withAvailableHistorySteps } from './studio-history-availability.ts';import { MAX_ASSET_BYTES } from './asset-limits.ts';+import { createFontCatalog, prepareFont, preparedFontResponse } from './studio-fonts.ts';+export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: string, initialDirectory: string, port: number) {const require = createRequire(path.join(runtimeRoot, 'package.json'));const cli = path.dirname(require.resolve('hyperframes/package.json'));@@ -22,6 +25,11 @@ export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: sconst { getRequestListener } = await import(pathToFileURL(require.resolve('@hono/node-server')).href);const { Hono } = await import(pathToFileURL(require.resolve('hono')).href);const { bodyLimit } = await import(pathToFileURL(require.resolve('hono/body-limit')).href);+ const coreRoot = path.dirname(require.resolve('@hyperframes/core/package.json'));+ const core = JSON.parse(await readFile(path.join(coreRoot, 'package.json'), 'utf8'));+ const { collectFontFileEntries, fontDirectories } = await import(pathToFileURL(path.join(coreRoot, core.exports['./fonts/system-locator'].import)).href);+ const { create: parseFont } = require('fontkit');+ const fonts = createFontCatalog(fontDirectories().flatMap(directory => collectFontFileEntries(directory).map(entry => entry.path)), parseFont);const historyModule = path.join(path.dirname(require.resolve('@hyperframes/studio-server/package.json')), 'dist/history/index.js');const { DEFAULT_HISTORY_ROOT } = await import(pathToFileURL(historyModule).href);const historyRoot = process.env.HYPERFRAMES_HISTORY_ROOT ?? DEFAULT_HISTORY_ROOT;@@ -40,7 +48,41 @@ export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: sconst host = createStudioServer({ projectDir: scoped.projectDirectory, projectName: id,origin: () => origin, historyRoot });const nativeApp = host.app;- host.app = new Hono().post('/api/projects/:id/upload', bodyLimit({+ host.app = new Hono().get('/api/fonts', async c => c.json({ fonts: await fonts.families() }))+ .get('/api/fonts/file', async c => {+ const family = c.req.query('family');+ if (!family) return c.json({ error: 'family parameter required' }, 400);+ const font = await fonts.file(family);+ return font ? preparedFontResponse(font) : c.json({ error: 'font not found' }, 404);+ }).post('/api/fonts/prepare', bodyLimit({ maxSize: MAX_ASSET_BYTES }), async c => {+ try { return preparedFontResponse(prepareFont(Buffer.from(await c.req.arrayBuffer()), parseFont)); }+ catch { return c.json({ error: 'Unsupported or invalid font file' }, 400); }+ }).post('/api/projects/:id/fonts/import', bodyLimit({ maxSize: 4096 }), async c => {+ const input = await c.req.json().catch(() => null);+ if (!input || typeof input.family !== 'string' || !input.family.trim()) return c.json({ error: 'Font family required' }, 400);+ const font = await fonts.file(input.family);+ if (!font) return c.json({ error: 'Font not found' }, 404);+ const name = font.postscriptName.replace(/[^a-zA-Z0-9_-]/g, '_') + '-' + randomUUID().slice(0, 8);+ const asset = `assets/fonts/${name}.${font.format}`;+ await mkdir(await scoped.safePath('assets/fonts'), { recursive: true });+ await writeFile(await scoped.safePath(asset), font.data, { flag: 'wx' });+ return c.json({ family: font.family, weight: font.weight, style: font.style, path: asset }, 201);+ }).get('/api/projects/:id', async c => {+ const response = await nativeApp.fetch(c.req.raw);+ if (!response.ok) return response;+ const data = await response.json();+ const projectFonts = [];+ for (const file of data.files ?? []) {+ if (!/\.(?:ttf|otf|ttc|woff2?)$/i.test(file)) continue;+ try {+ const faces = await fonts.inspect(await scoped.safePath(file));+ // Existing collections retain their actual first face until explicitly re-imported.+ const { index: _index, ...face } = faces[0];+ projectFonts.push({ ...face, path: file });+ } catch { /* Invalid historical files remain on disk but are not offered as fonts. */ }+ }+ return c.json({ ...data, fonts: projectFonts });+ }).post('/api/projects/:id/upload', bodyLimit({maxSize: MAX_ASSET_BYTES,onError: c => c.json({ error: 'Upload exceeds 500 MB (500000000 bytes)', maxBytes: MAX_ASSET_BYTES }, 413),}), c => nativeApp.fetch(c.req.raw)).all('*', c => nativeApp.fetch(c.req.raw));diff --git a/studio/src/App.tsx b/studio/src/App.tsxindex a37d5def..36e875ab 100644--- a/studio/src/App.tsx+++ b/studio/src/App.tsx@@ -305,6 +305,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: SteditHistory: { recordEdit: editHistory.recordEdit },fileTree: fileManager.fileTree,importedFontAssetsRef: fileManager.importedFontAssetsRef,+ fontAssets: fileManager.fontAssets,projectDir: fileManager.projectDir,projectIdRef: fileManager.projectIdRef,previewIframe,diff --git a/studio/src/components/editor/fontAssets.ts b/studio/src/components/editor/fontAssets.tsindex 5e75c198..ec3b2deb 100644--- a/studio/src/components/editor/fontAssets.ts+++ b/studio/src/components/editor/fontAssets.ts@@ -6,6 +6,8 @@ export interface ImportedFontAsset {style?: "normal" | "italic";}+export type FontImportInput = FileList | File[] | string;+const FONT_EXT_RE = /\.(eot|otf|ttc|ttf|woff2?)$/i;const FONT_STYLE_SUFFIX_RE =/\s+(thin|extralight|extra light|light|regular|roman|medium|semibold|semi bold|bold|extrabold|extra bold|black|italic|oblique|variable)$/i;diff --git a/studio/src/components/editor/fontCatalog.ts b/studio/src/components/editor/fontCatalog.tsindex fd343ab5..7b639c2e 100644--- a/studio/src/components/editor/fontCatalog.ts+++ b/studio/src/components/editor/fontCatalog.ts@@ -1,110 +1,3 @@-export const POPULAR_GOOGLE_FONT_FAMILIES = [- "ABeeZee",- "Abel",- "Abril Fatface",- "Alegreya",- "Alegreya Sans",- "Anton",- "Archivo",- "Archivo Black",- "Arimo",- "Assistant",- "Barlow",- "Barlow Condensed",- "Bebas Neue",- "Bitter",- "Bricolage Grotesque",- "Cabin",- "Cardo",- "Catamaran",- "Caveat",- "Chivo",- "Cormorant Garamond",- "Crimson Text",- "Dancing Script",- "DM Sans",- "DM Serif Display",- "Domine",- "EB Garamond",- "Exo 2",- "Figtree",- "Fira Code",- "Fira Sans",- "Fraunces",- "Fredoka",- "IBM Plex Mono",- "IBM Plex Sans",- "IBM Plex Serif",- "Inconsolata",- "Instrument Sans",- "Instrument Serif",- "Inter",- "JetBrains Mono",- "Josefin Sans",- "Jost",- "Kanit",- "Karla",- "Lato",- "League Gothic",- "Lexend",- "Libre Baskerville",- "Libre Franklin",- "Lora",- "Manrope",- "Merriweather",- "Montserrat",- "Mukta",- "Mulish",- "Newsreader",- "Noto Sans",- "Noto Sans JP",- "Noto Serif",- "Nunito",- "Nunito Sans",- "Open Sans",- "Oswald",- "Outfit",- "Overpass",- "Pacifico",- "Pathway Extreme",- "Permanent Marker",- "Playfair Display",- "Plus Jakarta Sans",- "Poppins",- "Prata",- "PT Sans",- "PT Serif",- "Public Sans",- "Quicksand",- "Raleway",- "Red Hat Display",- "Roboto",- "Roboto Condensed",- "Roboto Mono",- "Roboto Serif",- "Rubik",- "Schibsted Grotesk",- "Signika",- "Source Code Pro",- "Source Sans 3",- "Source Serif 4",- "Space Grotesk",- "Space Mono",- "Spectral",- "Sora",- "Syne",- "Teko",- "Titillium Web",- "Ubuntu",- "Ubuntu Mono",- "Unbounded",- "Urbanist",- "Varela Round",- "Work Sans",- "Young Serif",- "Zilla Slab",-] as const;-export const COMMON_LOCAL_FONT_FAMILIES = ["TT Norms Pro","SF Pro Display",@@ -114,20 +7,3 @@ export const COMMON_LOCAL_FONT_FAMILIES = ["Menlo","Monaco",] as const;--import { resolveAliasDisplayName } from "@hyperframes/core/fonts/aliases";--/**- * Resolves the render-time canonical font for a local font family name.- * Derived from the shared FONT_ALIAS_MAP — no hand-curation needed.- */-export function renderAliasFor(family: string): string | undefined {- const display = resolveAliasDisplayName(family);- if (!display || display.toLowerCase() === family.toLowerCase()) return undefined;- return display;-}--export function googleFontStylesheetUrl(family: string): string {- const encodedFamily = encodeURIComponent(family.trim()).replace(/%20/g, "+");- return `https://fonts.googleapis.com/css2?family=${encodedFamily}:wght@300;400;500;600;700;800;900&display=swap`;-}diff --git a/studio/src/components/editor/fontImport.test.ts b/studio/src/components/editor/fontImport.test.tsnew file mode 100644index 00000000..561e6d52--- /dev/null+++ b/studio/src/components/editor/fontImport.test.ts@@ -0,0 +1,31 @@+// @vitest-environment happy-dom+import { afterEach, expect, it, vi } from "vitest";+import { prepareFontImport } from "./fontImport";++afterEach(() => vi.unstubAllGlobals());++it("rejects invalid files before upload and retains the decoded font metadata", async () => {+ const load = vi.fn(async () => ({}));+ vi.stubGlobal("FontFace", class { load = load; });+ vi.stubGlobal("fetch", vi.fn(async () => new Response("bad font", { status: 400 })));+ await expect(prepareFontImport(new File(["text"], "bad.ttf"))).rejects.toThrow("invalid font");+ expect(load).not.toHaveBeenCalled();++ const metadata = { family: "Arial Black", weight: "900", style: "normal" };+ vi.mocked(fetch).mockResolvedValue(new Response("font bytes", { headers: {+ "Content-Type": "font/ttf", "X-Font-Metadata": encodeURIComponent(JSON.stringify(metadata)),+ } }));+ const prepared = await prepareFontImport(new File(["collection bytes"], "original.ttc"));+ expect(load).toHaveBeenCalledOnce();+ expect(prepared.metadata).toEqual(metadata);+ expect(prepared.file.name).toBe("original.ttf");+ expect(await prepared.file.text()).toBe("font bytes");+});++it("rejects a server-accepted font when browser decoding fails", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("bad bytes", { headers: {+ "X-Font-Metadata": encodeURIComponent(JSON.stringify({ family: "Broken" })),+ } })));+ vi.stubGlobal("FontFace", class { async load() { throw new Error("Browser cannot decode"); } });+ await expect(prepareFontImport(new File(["bad"], "bad.ttf"))).rejects.toThrow("cannot decode");+});diff --git a/studio/src/components/editor/fontImport.ts b/studio/src/components/editor/fontImport.tsnew file mode 100644index 00000000..b9404e82--- /dev/null+++ b/studio/src/components/editor/fontImport.ts@@ -0,0 +1,15 @@+import { studioApiFetch } from "../../utils/studioApiFetch";+import type { ImportedFontAsset } from "./fontAssets";++export async function prepareFontImport(file: File) {+ const response = await studioApiFetch("/api/fonts/prepare", { method: "POST", body: file });+ if (!response.ok) throw new Error("Unsupported or invalid font file");+ const metadata = JSON.parse(decodeURIComponent(response.headers.get("X-Font-Metadata") ?? "")) as Pick<ImportedFontAsset, "family" | "weight" | "style">;+ if (!metadata.family || typeof metadata.family !== "string") throw new Error("Font has no family");+ const bytes = await response.arrayBuffer();+ await new FontFace("Motion font validation", bytes).load();+ const type = response.headers.get("Content-Type") ?? "font/ttf";+ const extension = type.split("/")[1];+ const name = file.name.replace(/\.[^.]+$/, "") + "." + extension;+ return { file: new File([bytes], name, { type }), metadata };+}diff --git a/studio/src/components/editor/propertyPanelFlatTextSection.tsx b/studio/src/components/editor/propertyPanelFlatTextSection.tsxindex 8dcf5477..3b78860d 100644--- a/studio/src/components/editor/propertyPanelFlatTextSection.tsx+++ b/studio/src/components/editor/propertyPanelFlatTextSection.tsx@@ -6,7 +6,7 @@ import { useEffect, useState } from "react";import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext";import { Plus, X } from "../../icons/SystemIcons";import { isTextEditableSelection, type DomEditSelection } from "./domEditing";-import type { ImportedFontAsset } from "./fontAssets";+import type { ImportedFontAsset, FontImportInput } from "./fontAssets";import { normalizeTextMetricValue } from "./propertyPanelHelpers";import { ColorField } from "./propertyPanelColor";import { FontFamilyField } from "./propertyPanelFont";@@ -57,7 +57,7 @@ function FlatTextFieldEditor({field: DomEditSelection["textFields"][number];styles: Record<string, string>;fontAssets: ImportedFontAsset[];- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ onImportFonts?: (files: FontImportInput) => Promise<ImportedFontAsset[]>;onSetText: (value: string, fieldKey?: string) => void;onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;onPreviewTextFieldStyle?: (fieldKey: string, property: string, value: string) => void;diff --git a/studio/src/components/editor/propertyPanelFont.test.tsx b/studio/src/components/editor/propertyPanelFont.test.tsxindex f6e1eb9f..da310104 100644--- a/studio/src/components/editor/propertyPanelFont.test.tsx+++ b/studio/src/components/editor/propertyPanelFont.test.tsx@@ -6,6 +6,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { FontFamilyField } from "./propertyPanelFont";import { sortFontOptions } from "./propertyPanelHelpers";+let previewDocument: Document | null = null;+vi.mock("../../contexts/StudioContext", () => ({ useStudioShellContextOptional: () => ({ previewIframeRef: { current: { contentDocument: previewDocument } } }) }));+vi.mock("./propertyPanelHelpers", async (importOriginal) => {const actual = await importOriginal<typeof import("./propertyPanelHelpers")>();return {@@ -17,13 +20,18 @@ vi.mock("./propertyPanelHelpers", async (importOriginal) => {(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-// The font APIs are stubbed and every family is off the Google lists, so no test reaches the network.+// Font APIs and browser decoding are stubbed; no test reaches the network.beforeEach(() => {+ previewDocument = null;+ vi.stubGlobal("FontFace", class {+ load = vi.fn(async () => this);+ });+ Object.defineProperty(document, "fonts", { configurable: true, value: { add: vi.fn(), [Symbol.iterator]: function* () { yield { family: "Outer UI Font" }; } } });vi.stubGlobal("fetch",vi.fn(async (url: string) => ({ok: true,- json: async () => ({ fonts: url.includes("google") ? ["Roboto Slab"] : ["Arial"] }),+ json: async () => ({ fonts: url.includes("google") ? ["Google Only"] : ["Arial", "Menlo"] }),})),);});@@ -68,7 +76,7 @@ describe("FontFamilyField font list", () => {await act(async () => trigger?.click());await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));expect(sortFontOptions).toHaveBeenCalled();- expect(document.body.textContent).toContain("Roboto Slab");+ expect(document.body.textContent).toContain("Menlo");expect(host.querySelector('[role="combobox"]')).toBeNull();expect(document.body.querySelector('[role="combobox"]')).not.toBeNull();expect(document.head.querySelector('link[href*="fonts.googleapis.com"]')).toBeNull();@@ -118,13 +126,13 @@ describe("FontFamilyField session font lists", () => {window.dispatchEvent(new Event("pointermove"));await act(async () => vi.advanceTimersByTimeAsync(16));}- expect(fetch).toHaveBeenCalledTimes(2);+ expect(fetch).toHaveBeenCalledTimes(1);expect(t.uniqueFontFamilies).not.toHaveBeenCalled();await act(async () => vi.advanceTimersByTimeAsync(500));expect(t.uniqueFontFamilies).toHaveBeenCalledTimes(1);await act(async () => t.toggle());- expect(document.body.textContent).toContain("Roboto Slab");+ expect(document.body.textContent).toContain("Menlo");} finally {stopLoop();t.done();@@ -143,10 +151,95 @@ describe("FontFamilyField session font lists", () => {await act(async () => t.toggle());await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));- expect(fetch).toHaveBeenCalledTimes(4);- expect(document.body.textContent).toContain("Roboto Slab");+ expect(fetch).toHaveBeenCalledTimes(2);+ expect(document.body.textContent).toContain("Menlo");} finally {t.done();}});});++describe("FontFamilyField installed fonts", () => {+ it.each([true, false])("uses the server font file without browser font access (available: %s)", async (available) => {+ vi.resetModules();+ const { FontFamilyField } = await import("./propertyPanelFont");+ const { StudioHostContext } = await import("../../motion/StudioHost");+ const loop = await import("./overlayFrameLoop");+ const family = "Hiragino Sans GB";+ vi.mocked(fetch).mockResolvedValue(new Response(JSON.stringify({ fonts: [family] })));+ const onImportFonts = vi.fn(async () => available ? [{+ family, path: `assets/fonts/${family}.ttf`, url: "/font.ttf",+ }] : []);+ const onCommit = vi.fn();+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ try {+ await act(async () => root.render(+ <StudioHostContext.Provider value={{ mvpEditor: true }}>+ <FontFamilyField flat value="Arial" importedFonts={[]} onImportFonts={onImportFonts} onCommit={onCommit} />+ </StudioHostContext.Provider>,+ ));+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));+ await act(async () => host.querySelector<HTMLButtonElement>("[data-flat-font-trigger]")?.click());+ const option = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-font-option-index]"))+ .find((button) => button.textContent?.includes(family));+ expect(option?.textContent).toContain("Local");+ await act(async () => option?.click());+ expect(onImportFonts).toHaveBeenCalledWith(family);+ if (available) {+ expect(onImportFonts).toHaveBeenCalledOnce();+ expect(onCommit).toHaveBeenCalledWith(`"${family}", ui-sans-serif, system-ui, sans-serif`);+ } else {+ expect(onCommit).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain(`Couldn't import "${family}"`);+ }+ } finally {+ act(() => root.unmount());+ loop.resetOverlayFrameLoopForTests();+ }+ });+});++it("lists actual project declarations, imports and installed fonts without remote suggestions or Studio fonts", async () => {+ vi.resetModules();+ const { FontFamilyField } = await import("./propertyPanelFont");+ previewDocument = document.implementation.createHTMLDocument();+ Object.defineProperty(previewDocument, "fonts", { value: {+ [Symbol.iterator]: function* () { yield { family: '"Project Brand"' }; },+ load: vi.fn(async () => [{ family: "Project Brand" }]),+ } });+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host), commit = vi.fn();+ try {+ await act(async () => root.render(<FontFamilyField flat value="Authored Remote" importedFonts={[{ family: "Imported Brand", path: "brand.ttf", url: "/brand.ttf" }]} onCommit={commit} />));+ await act(async () => new Promise(resolve => setTimeout(resolve, 10)));+ await act(async () => host.querySelector<HTMLButtonElement>("[data-flat-font-trigger]")?.click());+ const text = document.body.textContent;+ for (const family of ["Authored Remote", "Project Brand", "Imported Brand", "Menlo"]) expect(text).toContain(family);+ for (const family of ["Google Only", "Roboto", "system-ui", "Outer UI Font"]) expect(text).not.toContain(family);+ expect(fetch).toHaveBeenCalledTimes(1);+ const option = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-font-option-index]")).find(button => button.textContent?.includes("Project Brand"));+ await act(async () => option?.click());+ expect(commit).toHaveBeenCalledWith('"Project Brand", ui-sans-serif, system-ui, sans-serif');+ expect(document.head.querySelector('link[href*="googleapis"]')).toBeNull();+ } finally { act(() => root.unmount()); }+});++it("keeps the current family when an existing imported font fails to decode", async () => {+ vi.resetModules();+ const { FontFamilyField } = await import("./propertyPanelFont");+ vi.stubGlobal("FontFace", class { load = vi.fn(async () => { throw new Error("Invalid font"); }); });+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host), commit = vi.fn();+ try {+ await act(async () => root.render(<FontFamilyField flat value="Arial" importedFonts={[{ family: "Broken", path: "broken.ttf", url: "/broken.ttf" }]} onCommit={commit} />));+ await act(async () => host.querySelector<HTMLButtonElement>("[data-flat-font-trigger]")?.click());+ const option = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-font-option-index]")).find(button => button.textContent?.includes("Broken"));+ await act(async () => option?.click());+ expect(commit).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain('Couldn\'t load "Broken"');+ } finally { act(() => root.unmount()); }+});diff --git a/studio/src/components/editor/propertyPanelFont.tsx b/studio/src/components/editor/propertyPanelFont.tsxindex d851a006..faa8cbee 100644--- a/studio/src/components/editor/propertyPanelFont.tsx+++ b/studio/src/components/editor/propertyPanelFont.tsx@@ -1,31 +1,22 @@import { SearchInput } from "../ui/SearchInput";-import { useMvpEditor } from "../../motion/StudioHost";import { Popover } from "../ui/Popover";import type { ReactElement } from "react";import { useI18n } from "../../i18n/I18n";import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { type ImportedFontAsset, type FontImportInput } from "./fontAssets";import {- googleFontStylesheetUrl,- POPULAR_GOOGLE_FONT_FAMILIES,- renderAliasFor,-} from "./fontCatalog";-import { fontFamilyFromAssetPath, importedFontFaceCss, type ImportedFontAsset } from "./fontAssets";-import {- DEFAULT_FONT_FAMILIES,FIELD,GENERIC_FONT_FAMILIES,LABEL,- localFontSortScore,- sanitizeFontFilePart,sortFontOptions,uniqueFontFamilies,uniqueFontOptions,type FontOption,- type LocalFontData,} from "./propertyPanelHelpers";import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext";import { runWhenInputIdle } from "./overlayFrameLoop";import { studioApiFetch } from "../../utils/studioApiFetch";+import { useStudioShellContextOptional } from "../../contexts/StudioContext";/* ------------------------------------------------------------------ *//* Font helper functions */@@ -72,9 +63,8 @@ function buildFontFamilyValue(family: string): string {return `${quoteFontFamily(trimmed)}, ui-sans-serif, system-ui, sans-serif`;}-function collectDocumentFontFamilies(): string[] {- if (typeof document === "undefined") return [];- const fontSet = document.fonts;+function collectDocumentFontFamilies(doc?: Document | null): string[] {+ const fontSet = doc?.fonts;if (!fontSet) return [];return Array.from(fontSet, (ff) => ff.family.replace(/^["']|["']$/g, "").trim()).filter(Boolean)@@ -92,49 +82,20 @@ function fontMatchesQuery(family: string, query: string): boolean {return fontSearchKey(family).includes(fontSearchKey(normalizedQuery));}-function loadGoogleFontStylesheet(family: string): void {+async function loadImportedFontStylesheet(asset: ImportedFontAsset): Promise<void> {if (typeof document === "undefined") return;- const trimmed = family.trim();- if (!trimmed) return;- const id = `studio-google-font-${trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;- if (document.getElementById(id)) return;- const preconnect = document.querySelector('link[data-studio-google-font-preconnect="true"]');- if (!preconnect) {- const el = document.createElement("link");- el.setAttribute("data-studio-google-font-preconnect", "true");- el.rel = "preconnect";- el.href = "https://fonts.gstatic.com";- el.crossOrigin = "anonymous";- document.head.appendChild(el);- }- const link = document.createElement("link");- link.id = id;- link.rel = "stylesheet";- link.href = googleFontStylesheetUrl(trimmed);- document.head.appendChild(link);-}--function loadImportedFontStylesheet(asset: ImportedFontAsset): void {- if (typeof document === "undefined") return;- const id = `studio-imported-font-${asset.family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;- if (document.getElementById(id)) return;- const style = document.createElement("style");- style.id = id;- style.textContent = importedFontFaceCss(asset);- document.head.appendChild(style);+ const face = new FontFace(asset.family, `url(${JSON.stringify(asset.url)})`, { weight: asset.weight ?? "normal", style: asset.style ?? "normal" });+ await face.load();+ document.fonts.add(face);}type FontLists = {loaded: boolean;- google: readonly string[];- googleKeys: ReadonlySet<string>;installed: string[];};let fontLists: FontLists = {loaded: false,- google: POPULAR_GOOGLE_FONT_FAMILIES,- googleKeys: new Set(POPULAR_GOOGLE_FONT_FAMILIES.map((f) => f.toLowerCase())),installed: [],};let fontListsRequest: Promise<void> | null = null;@@ -148,23 +109,10 @@ async function fetchFontList(url: string): Promise<string[]> {function loadFontLists(): void {if (fontLists.loaded) return;- fontListsRequest ??= Promise.all([- fetchFontList("/api/fonts"),- fetchFontList("/api/fonts/google"),- ])- .then(([installed, google]) => {- const names = google.concat(POPULAR_GOOGLE_FONT_FAMILIES);- const families: string[] = [];- const googleKeys = new Set<string>();- let next = 0;- runWhenInputIdle((timeLeft) => {- while (next < names.length && timeLeft() > 0) {- const batch = names.slice(next, next + 200);- next += batch.length;- families.push(...uniqueFontFamilies(batch, googleKeys));- }- if (next < names.length) return false;- fontLists = { loaded: true, google: families, googleKeys, installed };+ fontListsRequest ??= fetchFontList("/api/fonts")+ .then((installed) => {+ runWhenInputIdle(() => {+ fontLists = { loaded: true, installed: uniqueFontFamilies(installed) };for (const listener of fontListListeners) listener();return true;});@@ -196,11 +144,12 @@ export function FontFamilyField({disabled?: boolean;flat?: boolean;importedFonts: ImportedFontAsset[];- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ onImportFonts?: (files: FontImportInput) => Promise<ImportedFontAsset[]>;onCommit: (nextValue: string) => void;}) {const { t } = useI18n();- const mvp = useMvpEditor();+ const shell = useStudioShellContextOptional();+ const previewDocument = shell?.previewIframeRef.current?.contentDocument;const track = useTrackDesignInput();const currentFamily = primaryFontFamily(value);const inputRef = useRef<HTMLInputElement | null>(null);@@ -208,80 +157,35 @@ export function FontFamilyField({const [open, setOpen] = useState(false);const [query, setQuery] = useState("");const [activeIndex, setActiveIndex] = useState(-1);- const [localFonts, setLocalFonts] = useState<string[]>([]);- const [localFontData, setLocalFontData] = useState<LocalFontData[]>([]);const lists = useSyncExternalStore(subscribeFontLists, () => fontLists);- const [loadingLocalFonts, setLoadingLocalFonts] = useState(false);const [importingFonts, setImportingFonts] = useState(false);const [fontNotice, setFontNotice] = useState<string | null>(null);- const canQueryLocalFonts =- typeof window !== "undefined" && typeof window.queryLocalFonts === "function";- const showLocalFontsButton = !mvp && canQueryLocalFonts;const commitFontFamily = (nextValue: string) => {if (nextValue !== value) track("select", "Font family");- onCommit(nextValue);+ return onCommit(nextValue);};useEffect(() => {if (open) loadFontLists();}, [open]);- useEffect(() => {- if (lists.googleKeys.has(currentFamily.toLowerCase())) {- loadGoogleFontStylesheet(currentFamily);- }- const imported = importedFonts.find(- (f) => f.family.toLowerCase() === currentFamily.toLowerCase(),- );- if (imported) loadImportedFontStylesheet(imported);- }, [currentFamily, lists, importedFonts]);-- const loadBrowserLocalFonts = async () => {- if (!canQueryLocalFonts || !window.queryLocalFonts) {- setFontNotice("This browser does not expose installed fonts. Import a font file instead.");- return;- }- setLoadingLocalFonts(true);- setFontNotice(null);- try {- const fonts = await window.queryLocalFonts();- const sorted = [...fonts].sort((a, b) => localFontSortScore(a) - localFontSortScore(b));- const families = sorted- .map((f) => f.family)- .filter((name): name is string => Boolean(name))- .map((name) => fontFamilyFromAssetPath(`${name}.ttf`));- setLocalFontData(sorted);- setLocalFonts((cur) => uniqueFontFamilies([...cur, ...families]));- setFontNotice(fonts.length === 0 ? "No browser-local fonts were returned." : null);- } catch (error) {- const name = error instanceof Error ? error.name : "";- setFontNotice(- name === "NotAllowedError"- ? "Local font access was denied. Import a font file instead."- : "Local font access is unavailable. Import a font file instead.",- );- } finally {- setLoadingLocalFonts(false);- }- };-const handleImportFonts = async (files: FileList | File[] | null) => {if (!files?.length || !onImportFonts) return;setImportingFonts(true);setFontNotice(null);try {const imported = await onImportFonts(files);- for (const font of imported) loadImportedFontStylesheet(font);+ for (const font of imported) await loadImportedFontStylesheet(font);const first = imported[0];if (first) {- commitFontFamily(buildFontFamilyValue(first.family));+ await commitFontFamily(buildFontFamilyValue(first.family));setQuery("");setOpen(false);} else {setFontNotice("No supported font files were imported.");}} catch {- setFontNotice("Font import failed. The files were not added. Try again.");+ setFontNotice("This font could not be loaded. The current font was kept.");} finally {setImportingFonts(false);}@@ -297,20 +201,18 @@ export function FontFamilyField({const options = useMemo(() => {if (!open) return [];- const documentFonts = collectDocumentFontFamilies();+ const documentFonts = collectDocumentFontFamilies(previewDocument);return sortFontOptions(uniqueFontOptions([{ family: currentFamily, source: "Current" },...documentFonts.map((f): FontOption => ({ family: f, source: "Document" })),...projectFontAssets,- ...lists.google.map((f): FontOption => ({ family: f, source: "Google" })),- ...[...lists.installed, ...localFonts].map(+ ...lists.installed.map((f): FontOption => ({ family: f, source: "Local" }),),- ...DEFAULT_FONT_FAMILIES.map((f): FontOption => ({ family: f, source: "System" })),]),);- }, [open, currentFamily, lists, localFonts, projectFontAssets]);+ }, [open, currentFamily, lists, previewDocument, projectFontAssets]);const filteredOptions = useMemo(() => {const matches = options.filter((o) => fontMatchesQuery(o.family, query));@@ -323,58 +225,29 @@ export function FontFamilyField({}const result: FontOption[] = [];for (const s of ["Current", "Document", "Imported"]) result.push(...(bySource.get(s) ?? []));- result.push(...(bySource.get("Google") ?? []).slice(0, 100));result.push(...(bySource.get("Local") ?? []).slice(0, 80));- result.push(...(bySource.get("System") ?? []));return result;}, [options, query]);- const importLocalFont = async (family: string): Promise<ImportedFontAsset | null> => {- if (!onImportFonts) return null;- const candidates = localFontData- .filter((f) => fontFamilyFromAssetPath(`${f.family}.ttf`) === family)- .sort((a, b) => localFontSortScore(a) - localFontSortScore(b));- const font = candidates.find((entry) => typeof entry.blob === "function");- if (!font?.blob) return null;- const blob = await font.blob();- const style = sanitizeFontFilePart(font.style ?? "Regular") || "Regular";- const name = sanitizeFontFilePart(`${family} ${style}`) || family;- const file = new File([blob], `${name}.ttf`, { type: blob.type || "font/ttf" });- const imported = await onImportFonts([file]);- return (- imported.find((a) => a.family.toLowerCase() === family.toLowerCase()) ?? imported[0] ?? null- );- };-const importSystemFont = async (family: string): Promise<ImportedFontAsset | null> => {if (!onImportFonts) return null;- const response = await studioApiFetch(`/api/fonts/file?family=${encodeURIComponent(family)}`);- if (!response.ok) return null;- const blob = await response.blob();- const ext = response.headers.get("Content-Disposition")?.match(/\.(\w+)"?$/)?.[1] ?? "ttf";- const file = new File([blob], `${family}.${ext}`, { type: blob.type || "font/ttf" });- const imported = await onImportFonts([file]);+ const imported = await onImportFonts(family);return (imported.find((a) => a.family.toLowerCase() === family.toLowerCase()) ?? imported[0] ?? null);};const commitFamily = async (option: FontOption) => {- const needsImport =- option.source === "Local" ||- (option.source === "System" && !GENERIC_FONT_FAMILIES.has(option.family.toLowerCase()));+ const needsImport = option.source === "Local";if (needsImport) {setImportingFonts(true);setFontNotice(null);try {- const imported =- option.source === "Local"- ? await importLocalFont(option.family)- : await importSystemFont(option.family);+ const imported = await importSystemFont(option.family);if (imported) {- loadImportedFontStylesheet(imported);- commitFontFamily(buildFontFamilyValue(imported.family));+ await loadImportedFontStylesheet(imported);+ await commitFontFamily(buildFontFamilyValue(imported.family));setQuery("");setOpen(false);} else {@@ -382,32 +255,40 @@ export function FontFamilyField({// so surface the failure and keep the current font instead.setFontNotice(`Couldn't import "${option.family}", so the font was not applied.`);}- } catch {+ } catch (error) {+ console.error("Local font could not be applied", error);setFontNotice(`Couldn't import "${option.family}", so the font was not applied.`);} finally {setImportingFonts(false);}return;}- if (option.source === "Google") loadGoogleFontStylesheet(option.family);- const imported = importedFonts.find(- (f) => f.family.toLowerCase() === option.family.toLowerCase(),- );- if (imported) loadImportedFontStylesheet(imported);- commitFontFamily(buildFontFamilyValue(option.family));- setQuery("");- setOpen(false);+ setImportingFonts(true);+ setFontNotice(null);+ try {+ const imported = importedFonts.find((font) => font.family.toLowerCase() === option.family.toLowerCase());+ if (imported) await loadImportedFontStylesheet(imported);+ else if (!GENERIC_FONT_FAMILIES.has(option.family.toLowerCase()) && previewDocument?.fonts) {+ const faces = await previewDocument.fonts.load(`16px ${quoteFontFamily(option.family)}`);+ if (faces.length === 0) throw new Error("Font is unavailable");+ }+ await commitFontFamily(buildFontFamilyValue(option.family));+ setQuery("");+ setOpen(false);+ } catch {+ setFontNotice(`Couldn't load "${option.family}", so the font was not applied.`);+ } finally { setImportingFonts(false); }};const dropdown = open && (<div className="flex max-h-[min(360px,var(--available-height))] min-h-0 flex-col">- <div className={`grid shrink-0 ${showLocalFontsButton ? "grid-cols-[minmax(0,1fr)_auto_auto]" : "grid-cols-[minmax(0,1fr)_auto]"} gap-2 border-b border-neutral-800 p-2`}>+ <div className="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] gap-2 border-b border-neutral-800 p-2"><SearchInputref={inputRef}aria-label={t("Search fonts")}value={query}- disabled={disabled}- placeholder={lists.loaded ? t("Search fonts") : t("Loading Google Fonts...")}+ disabled={disabled || importingFonts}+ placeholder={t("Search fonts")}onChange={(e) => {setQuery(e.target.value);setActiveIndex(-1);@@ -443,16 +324,6 @@ export function FontFamilyField({aria-autocomplete="list"className="min-w-0"/>- {showLocalFontsButton && (- <button- type="button"- disabled={disabled || loadingLocalFonts}- onClick={loadBrowserLocalFonts}- className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 text-[10px] font-medium text-neutral-400 transition-colors hover:border-neutral-600 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-text-off"- >- {loadingLocalFonts ? "..." : t("Local")}- </button>- )}<buttontype="button"disabled={disabled || importingFonts || !onImportFonts}@@ -464,7 +335,7 @@ export function FontFamilyField({<inputref={fontInputRef}type="file"- accept=".ttf,.otf,.ttc,.woff,.woff2,.eot,font/*"+ accept=".ttf,.otf,.ttc,.woff,.woff2,font/*"multiplearia-label={t("Import local font files")}disabled={disabled || importingFonts || !onImportFonts}@@ -489,6 +360,7 @@ export function FontFamilyField({key={`${option.source}-${option.family}`}type="button"data-font-option-index={index}+ disabled={disabled || importingFonts}onClick={() => commitFamily(option)}className={`flex w-full min-w-0 items-center justify-between gap-3 rounded-lg px-2 py-2 text-left text-[11px] transition-colors ${index === activeIndex@@ -502,11 +374,7 @@ export function FontFamilyField({<span title={option.family} className="truncate font-medium" style={{ fontFamily: `"${option.family}"` }}>{option.family}</span>- {renderAliasFor(option.family) && (- <span className="shrink-0 text-[9px] text-neutral-500">- → {renderAliasFor(option.family)}- </span>- )}+</span><span className="shrink-0 text-[9px] uppercase tracking-[0.14em] text-neutral-600">{t(option.source)}@@ -539,7 +407,7 @@ export function FontFamilyField({{renderPicker(<buttontype="button"data-flat-font-trigger="true"- disabled={disabled}+ disabled={disabled || importingFonts}className="flex items-center gap-1.5 disabled:cursor-not-allowed"><span@@ -567,7 +435,7 @@ export function FontFamilyField({<span className={LABEL}>{t("Font family")}</span>{renderPicker(<buttontype="button"- disabled={disabled}+ disabled={disabled || importingFonts}className={`${FIELD} flex h-10 items-center justify-between gap-3 text-left hover:border-neutral-700 disabled:cursor-not-allowed`}><spandiff --git a/studio/src/components/editor/propertyPanelHelpers.ts b/studio/src/components/editor/propertyPanelHelpers.tsindex c91ffcfb..3742a9b4 100644--- a/studio/src/components/editor/propertyPanelHelpers.ts+++ b/studio/src/components/editor/propertyPanelHelpers.ts@@ -79,52 +79,13 @@ export const GENERIC_FONT_FAMILIES = new Set(["fangsong",]);-export const DEFAULT_FONT_FAMILIES = [- ...COMMON_LOCAL_FONT_FAMILIES,- "Inter",- "system-ui",- "sans-serif",- "serif",- "monospace",-];--export interface LocalFontData {- family: string;- fullName?: string;- postscriptName?: string;- style?: string;- blob?: () => Promise<Blob>;-}--export type FontSource = "Current" | "Document" | "Imported" | "Local" | "Google" | "System";+export type FontSource = "Current" | "Document" | "Imported" | "Local";export interface FontOption {family: string;source: FontSource;}-declare global {- interface Window {- queryLocalFonts?: () => Promise<LocalFontData[]>;- }-}--export function sanitizeFontFilePart(value: string): string {- return value- .replace(/[^\w .-]+/g, " ")- .replace(/\s+/g, " ")- .trim();-}--export function localFontSortScore(font: LocalFontData): number {- const style = font.style?.toLowerCase() ?? "";- const fullName = font.fullName?.toLowerCase() ?? "";- if (style === "regular" || fullName.endsWith(" regular")) return 0;- if (style === "normal" || fullName.endsWith(" normal")) return 1;- if (style === "medium" || fullName.endsWith(" medium")) return 2;- return 3;-}-export function uniqueFontFamilies(values: string[], seen = new Set<string>()): string[] {return values.reduce<string[]>((result, value) => {const family = value.trim();@@ -171,8 +132,7 @@ function fontSourceRank(source: FontSource): number {if (source === "Current") return 0;if (source === "Document") return 1;if (source === "Imported") return 2;- if (source === "Google") return 3;- if (source === "Local") return 4;+ if (source === "Local") return 3;return 5;}diff --git a/studio/src/components/editor/propertyPanelInputCoverage.test.tsx b/studio/src/components/editor/propertyPanelInputCoverage.test.tsxindex 51a0026d..8699804e 100644--- a/studio/src/components/editor/propertyPanelInputCoverage.test.tsx+++ b/studio/src/components/editor/propertyPanelInputCoverage.test.tsx@@ -370,13 +370,16 @@ describe.each(["classic", "flat"] as const)("shared %s input telemetry", (ui) =>});});- it("tracks FontFamilyField exactly once for a real selection", () => {+ it("tracks FontFamilyField exactly once for a real selection", async () => {+ vi.stubGlobal("FontFace", class { async load() { return this; } });+ const originalFonts = Object.getOwnPropertyDescriptor(document, "fonts");+ Object.defineProperty(document, "fonts", { configurable: true, value: { add: vi.fn() } });const host = render(section(<FontFamilyFieldflat={ui === "flat"}value="Arial"- importedFonts={[]}+ importedFonts={[{ family: "Fixture Font", path: "fixture.ttf", url: "/fixture.ttf" }]}onCommit={vi.fn()}/>,),@@ -386,10 +389,10 @@ describe.each(["classic", "flat"] as const)("shared %s input telemetry", (ui) =>);act(() => trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })));const option = Array.from(document.body.querySelectorAll<HTMLButtonElement>("button")).find((button) =>- button.textContent?.includes("sans-serif"),+ button.textContent?.includes("Fixture Font"),);- if (!option) throw new Error("expected sans-serif font option");- act(() => option.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ if (!option) throw new Error("expected imported font option");+ await act(async () => option.dispatchEvent(new MouseEvent("click", { bubbles: true })));expect(trackStudioEvent).toHaveBeenCalledTimes(1);expect(trackStudioEvent).toHaveBeenLastCalledWith("design_input", {@@ -398,6 +401,8 @@ describe.each(["classic", "flat"] as const)("shared %s input telemetry", (ui) =>control: "select",name: "font-family",});+ if (originalFonts) Object.defineProperty(document, "fonts", originalFonts);+ else delete (document as unknown as { fonts?: unknown }).fonts;});it("tracks TextAreaField exactly once across scheduled commit and blur", () => {diff --git a/studio/src/components/editor/propertyPanelSections.tsx b/studio/src/components/editor/propertyPanelSections.tsxindex 33e671f3..52a6c42a 100644--- a/studio/src/components/editor/propertyPanelSections.tsx+++ b/studio/src/components/editor/propertyPanelSections.tsx@@ -2,7 +2,7 @@ import { useI18n } from "../../i18n/I18n";import { useEffect, useRef, useState, type ChangeEvent } from "react";import { Plus, Type } from "../../icons/SystemIcons";import { isTextEditableSelection, type DomEditSelection } from "./domEditing";-import type { ImportedFontAsset } from "./fontAssets";+import type { ImportedFontAsset, FontImportInput } from "./fontAssets";import { FIELD, LABEL, normalizeTextMetricValue, RESPONSIVE_GRID } from "./propertyPanelHelpers";import { MetricField, Section, SelectField } from "./propertyPanelPrimitives";import { ColorField } from "./propertyPanelColor";@@ -310,7 +310,7 @@ function TextFieldEditor({field: DomEditSelection["textFields"][number];styles: Record<string, string>;fontAssets: ImportedFontAsset[];- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ onImportFonts?: (files: FontImportInput) => Promise<ImportedFontAsset[]>;showRemove: boolean;onSetText: (value: string, fieldKey?: string) => void;onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;@@ -419,7 +419,7 @@ export function TextSection({element: DomEditSelection;styles: Record<string, string>;fontAssets: ImportedFontAsset[];- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ onImportFonts?: (files: FontImportInput) => Promise<ImportedFontAsset[]>;onSetText: (value: string, fieldKey?: string) => void;onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;onAddTextField: (afterFieldKey?: string) => string | Promise<string | null> | null;diff --git a/studio/src/components/editor/propertyPanelTypes.ts b/studio/src/components/editor/propertyPanelTypes.tsindex 4d680084..25608cb2 100644--- a/studio/src/components/editor/propertyPanelTypes.ts+++ b/studio/src/components/editor/propertyPanelTypes.ts@@ -1,7 +1,7 @@import type { RefObject } from "react";import type { ArcPathSegment, GsapAnimation } from "@hyperframes/parsers/gsap-parser";import type { DomEditSelection } from "./domEditing";-import type { ImportedFontAsset } from "./fontAssets";+import type { ImportedFontAsset, FontImportInput } from "./fontAssets";import type { GsapAnimationEditCallbacks } from "./gsapAnimationCallbacks";import type { CommitDomAttributeBatch } from "../../hooks/domEditCommitTypes";@@ -104,7 +104,7 @@ export interface PropertyPanelProps {onImportAssets?: (files: FileList, dir?: string) => Promise<string[]>;onAddMediaOverlay?: AddMediaOverlayHandler;fontAssets?: ImportedFontAsset[];- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;+ onImportFonts?: (files: FontImportInput) => Promise<ImportedFontAsset[]>;previewIframeRef?: RefObject<HTMLIFrameElement | null>;gsapAnimations?: GsapAnimation[];gsapMultipleTimelines?: boolean;diff --git a/studio/src/hooks/domStyleCommit.ts b/studio/src/hooks/domStyleCommit.tsindex f92dc053..d34d4f0a 100644--- a/studio/src/hooks/domStyleCommit.ts+++ b/studio/src/hooks/domStyleCommit.ts@@ -6,7 +6,7 @@ import {isManualGeometryStyleProperty,normalizeDomEditStyleValue,} from "../utils/studioHelpers";-import { injectPreviewGoogleFont, injectPreviewImportedFont } from "../utils/studioFontHelpers";+import { injectPreviewImportedFont } from "../utils/studioFontHelpers";import {buildDomEditStylePatchOperation,findElementsForSelection,@@ -99,7 +99,6 @@ export async function commitDomStyles(for (const [property, value] of liveStyles) el.style.setProperty(property, value);}if (fontFamily !== undefined && doc) {- injectPreviewGoogleFont(doc, fontFamily);if (importedFont) injectPreviewImportedFont(doc, importedFont);}},diff --git a/studio/src/hooks/useDomEditCommits.test.tsx b/studio/src/hooks/useDomEditCommits.test.tsxindex 9f2b3f4b..922bf8a1 100644--- a/studio/src/hooks/useDomEditCommits.test.tsx+++ b/studio/src/hooks/useDomEditCommits.test.tsx@@ -37,6 +37,7 @@ interface RenderedDomEditCommits {interface RenderDomEditCommitsOptions {importedFontAssets?: ImportedFontAsset[];+ fontAssets?: ImportedFontAsset[];writeProjectFile?: (path: string, content: string, expectedContent?: string) => Promise<void>;onTrySdkPersist?: () => Promise<CutoverResult>;queueDomEditSave?: <T>(save: () => Promise<T>) => Promise<T>;@@ -220,6 +221,7 @@ function renderDomEditCommits(writeProjectFile: options.writeProjectFile ?? (async () => {}),editHistory: { recordEdit },fileTree: [],+ fontAssets: options.fontAssets,importedFontAssetsRef: { current: options.importedFontAssets ?? [] },projectId: "p1",projectIdRef,@@ -1821,3 +1823,21 @@ describe("useDomEditCommits attribute batch commit", () => {}});});++it.each([false, true])("preserves real font metadata and an existing authored face (declared: %s)", async declared => {+ const source = '<!doctype html><html><head></head><body><div data-hf-id="hf-card">Card</div></body></html>';+ const fetchMock = stubPatchFetch({ ok: true, changed: true, matched: true, content: source }, source);+ const { iframe, element } = createPreviewElement();+ if (declared) Object.defineProperty(iframe.contentDocument, "fonts", { configurable: true, value: [{ family: "Arial Black" }] });+ const rendered = renderDomEditCommits(createSelection(element), iframe, {+ fontAssets: [{ family: "Arial Black", path: "fonts/misleading.ttf", url: "/api/projects/p1/preview/fonts/misleading.ttf", weight: "900", style: "normal" }],+ });+ try {+ await act(async () => { await rendered.hook.handleDomStyleCommit("font-family", '"Arial Black"'); });+ const writes = fetchMock.mock.calls.filter(([, init]) => init?.method === "POST" || init?.method === "PUT");+ expect(writes).toHaveLength(1);+ const body = JSON.parse(String(writes[0][1]?.body));+ if (declared) expect(body.fontFaceCss).toBeUndefined();+ else expect(body.fontFaceCss).toContain('font-weight: 900; font-style: normal;');+ } finally { rendered.cleanup(); }+});diff --git a/studio/src/hooks/useDomEditCommits.ts b/studio/src/hooks/useDomEditCommits.tsindex b5c958a2..f295d4e5 100644--- a/studio/src/hooks/useDomEditCommits.ts+++ b/studio/src/hooks/useDomEditCommits.ts@@ -33,6 +33,7 @@ export interface UseDomEditCommitsParams {writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>;editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };fileTree: string[];+ fontAssets?: ImportedFontAsset[];importedFontAssetsRef: React.MutableRefObject<ImportedFontAsset[]>;projectId: string | null;projectIdRef: React.MutableRefObject<string | null>;@@ -81,6 +82,7 @@ export function useDomEditCommits({writeProjectFile,editHistory,fileTree,+ fontAssets = [],importedFontAssetsRef,projectId,projectIdRef,@@ -104,6 +106,11 @@ export function useDomEditCommits({(font) => font.family.toLowerCase() === family.toLowerCase(),);if (imported) return imported;+ // An authored face already owns its source and weight; do not replace it with a filename guess.+ const doc = previewIframeRef.current?.contentDocument;+ if (doc?.fonts && Array.from(doc.fonts).some(face => face.family.replace(/^["']|["']$/g, "").toLowerCase() === family.toLowerCase())) return null;+ const known = fontAssets.find(font => font.family.toLowerCase() === family.toLowerCase());+ if (known) return known;const asset = fileTree.find((path) =>FONT_EXT.test(path) &&@@ -116,7 +123,7 @@ export function useDomEditCommits({url: buildProjectApiPath(projectId, `/preview/${encodeUrlPath(asset)}`),};},- [fileTree, projectId, importedFontAssetsRef],+ [fileTree, fontAssets, projectId, importedFontAssetsRef, previewIframeRef],);const persistDomEditOperations = useDomEditPersist({diff --git a/studio/src/hooks/useDomEditSession.ts b/studio/src/hooks/useDomEditSession.tsindex 97c246cb..cd99bf8f 100644--- a/studio/src/hooks/useDomEditSession.ts+++ b/studio/src/hooks/useDomEditSession.ts@@ -40,6 +40,7 @@ export interface UseDomEditSessionParams extends DomEditTimelineParams {updateEditingFileContent: (path: string, content: string) => void;editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };fileTree: string[];+ fontAssets?: ImportedFontAsset[];importedFontAssetsRef: React.MutableRefObject<ImportedFontAsset[]>;projectDir: string | null;projectIdRef: React.MutableRefObject<string | null>;@@ -85,6 +86,7 @@ export function useDomEditSession({updateEditingFileContent,editHistory,fileTree,+ fontAssets,importedFontAssetsRef,projectDir,projectIdRef,@@ -223,6 +225,7 @@ export function useDomEditSession({writeProjectFile,editHistory,fileTree,+ fontAssets,importedFontAssetsRef,projectId,projectIdRef,diff --git a/studio/src/hooks/useDomEditTextCommits.ts b/studio/src/hooks/useDomEditTextCommits.tsindex 7a0ca3aa..7a699a4c 100644--- a/studio/src/hooks/useDomEditTextCommits.ts+++ b/studio/src/hooks/useDomEditTextCommits.ts@@ -2,7 +2,7 @@ import { trackPreviewFeatureUsed } from "../utils/previewFeatureUsage";import { useCallback, useRef } from "react";import { refreshTimelineRowText } from "./refreshTimelineRowText";import { normalizeDomEditStyleValue } from "../utils/studioHelpers";-import { injectPreviewGoogleFont, injectPreviewImportedFont } from "../utils/studioFontHelpers";+import { injectPreviewImportedFont } from "../utils/studioFontHelpers";import {buildDomEditRichTextPatchOperation,findElementForSelection,@@ -409,7 +409,6 @@ export function useDomEditTextCommits({if (property === "font-family") {const doc = previewIframeRef.current?.contentDocument;if (doc) {- injectPreviewGoogleFont(doc, normalizedValue);if (importedFont) injectPreviewImportedFont(doc, importedFont);}}diff --git a/studio/src/hooks/useFileManager.ts b/studio/src/hooks/useFileManager.tsindex 45435d64..26ba885b 100644--- a/studio/src/hooks/useFileManager.ts+++ b/studio/src/hooks/useFileManager.ts@@ -1,9 +1,9 @@import { useI18n } from "../i18n/I18n";import { importValidationMessage } from "../i18n/importMessages";-import { useState, useCallback, useRef } from "react";+import { useState, useCallback, useRef, useEffect } from "react";import type { EditingFile } from "../utils/studioHelpers";import { FONT_EXT, isMediaFile } from "../utils/mediaTypes";-import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";+import { type ImportedFontAsset, type FontImportInput } from "../components/editor/fontAssets";import { findTagByTarget, type PatchTarget } from "../utils/sourcePatcher";import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";import { serializeStudioFileMutation } from "../utils/studioFileMutationCoordinator";@@ -12,6 +12,7 @@ import { useEditorSave } from "./useEditorSave";import { useProjectFileWriter } from "./useProjectFileWriter";import { studioApiFetch } from "../utils/studioApiFetch";import { encodeUrlPath } from "@hyperframes/parsers";+import { prepareFontImport } from "../components/editor/fontImport";// ── Types ──@@ -70,6 +71,8 @@ export function useFileManager({fontAssets,} = useFileTree({ projectId, projectIdRef });+ useEffect(() => { importedFontAssetsRef.current = []; }, [projectId]);+const updateEditingFileContent = useCallback((path: string, content: string) => {if (editingPathRef.current === path) {setEditingFile({ path, content });@@ -386,20 +389,29 @@ export function useFileManager({);const handleImportFonts = useCallback(- async (files: FileList | File[]): Promise<ImportedFontAsset[]> => {+ async (files: FontImportInput): Promise<ImportedFontAsset[]> => {const pid = projectIdRef.current;if (!pid) return [];- const uploaded = await uploadProjectFiles(- Array.from(files).filter((file) => FONT_EXT.test(file.name)),- "assets/fonts",- );- const imported = uploaded- .filter((asset) => FONT_EXT.test(asset))- .map((asset) => ({- family: fontFamilyFromAssetPath(asset),- path: asset,- url: `/api/projects/${encodeURIComponent(pid)}/preview/${encodeUrlPath(asset)}`,+ let imported: ImportedFontAsset[];+ if (typeof files === "string") {+ const response = await studioApiFetch(`/api/projects/${encodeURIComponent(pid)}/fonts/import`, {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ family: files }),+ });+ if (!response.ok) throw new Error("Installed font import failed");+ const font = await response.json();+ imported = [{ ...font, url: `/api/projects/${encodeURIComponent(pid)}/preview/${encodeUrlPath(font.path)}` }];+ await refreshFileTree();+ } else {+ const prepared: Awaited<ReturnType<typeof prepareFontImport>>[] = [];+ for (const file of Array.from(files).filter((file) => FONT_EXT.test(file.name))) prepared.push(await prepareFontImport(file));+ if (projectIdRef.current !== pid) throw new Error("Active project changed before font import");+ const uploaded = await uploadProjectFiles(prepared.map(font => font.file), "assets/fonts");+ if (uploaded.length !== prepared.length) throw new Error("Font import did not complete");+ imported = uploaded.map((asset, index) => ({ ...prepared[index].metadata,+ path: asset, url: `/api/projects/${encodeURIComponent(pid)}/preview/${encodeUrlPath(asset)}`,}));+ }+ if (projectIdRef.current !== pid) throw new Error("Active project changed before font import");importedFontAssetsRef.current = [...imported,...importedFontAssetsRef.current.filter(@@ -409,7 +421,7 @@ export function useFileManager({];return imported;},- [uploadProjectFiles],+ [uploadProjectFiles, refreshFileTree],);// ── Return ──diff --git a/studio/src/hooks/useFileTree.test.tsx b/studio/src/hooks/useFileTree.test.tsxindex 8e940dd8..6ca17529 100644--- a/studio/src/hooks/useFileTree.test.tsx+++ b/studio/src/hooks/useFileTree.test.tsx@@ -25,20 +25,33 @@ afterEach(() => {interface Handle {compositions: string[];+ fonts: ReturnType<typeof useFileTree>["fontAssets"];refresh: () => Promise<void>;}const Harness = forwardRef<Handle, { projectId: string }>(function Harness({ projectId }, ref) {const projectIdRef = useRef(projectId);projectIdRef.current = projectId;- const { compositions, refreshFileTree } = useFileTree({ projectId, projectIdRef });- useImperativeHandle(ref, () => ({ compositions, refresh: refreshFileTree }), [+ const { compositions, refreshFileTree, fontAssets } = useFileTree({ projectId, projectIdRef });+ useImperativeHandle(ref, () => ({ compositions, fonts: fontAssets, refresh: refreshFileTree }), [compositions,+ fontAssets,refreshFileTree,]);return null;});+it("keeps the server's real family and weight instead of deriving them from the asset filename", async () => {+ const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({+ files: ["assets/fonts/misleading.ttf"], compositions: [],+ fonts: [{ family: "Arial Black", weight: "900", style: "normal", path: "assets/fonts/misleading.ttf" }],+ })));+ try {+ const handle = await renderHarness("project-a");+ expect(handle.current?.fonts).toEqual([{ family: "Arial Black", weight: "900", style: "normal", path: "assets/fonts/misleading.ttf", url: "/api/projects/project-a/preview/assets/fonts/misleading.ttf" }]);+ } finally { fetchSpy.mockRestore(); vi.mocked(captureProjectProvenance).mockClear(); }+});+async function renderHarness(projectId: string): Promise<{ current: Handle | null }> {const handleRef = { current: null as Handle | null };const host = document.createElement("div");diff --git a/studio/src/hooks/useFileTree.ts b/studio/src/hooks/useFileTree.tsindex 3ca70cf8..ec976888 100644--- a/studio/src/hooks/useFileTree.ts+++ b/studio/src/hooks/useFileTree.ts@@ -19,13 +19,14 @@ interface FetchedFileTree {fileTree: string[];compositionPaths: string[];projectDir: string | null;+ fonts?: Array<Omit<ImportedFontAsset, "url">>;}// Stable references so a mismatched projectId doesn't create a new array every render// and defeat useMemo/useCallback deps downstream (e.g. the `assets` memo below).const EMPTY_FILE_LIST: string[] = [];-type TreeListing = { files?: string[]; compositions?: string[] };+type TreeListing = { files?: string[]; compositions?: string[]; fonts?: Array<Omit<ImportedFontAsset, "url">> };async function readTreeListing(projectId: string, signal: AbortSignal): Promise<TreeListing> {const res = await studioApiFetch(buildProjectApiPath(projectId), { signal });@@ -64,7 +65,7 @@ export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) {if (!r.ok) throw new Error(`tree fetch failed: ${r.status}`);return r.json();})- .then((data: { files?: string[]; dir?: string; compositions?: string[] }) => {+ .then((data: TreeListing & { dir?: string }) => {if (cancelled) return;setFetched({projectId,@@ -72,6 +73,7 @@ export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) {fileTree: data.files ?? [],compositionPaths: data.compositions ?? [],projectDir: typeof data.dir === "string" ? data.dir : null,+ fonts: data.fonts,});// Snapshot how this project was made, while the listing is in hand and// the app is still alive. A crash later has no other way to learn it.@@ -119,6 +121,7 @@ export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) {// A response that omits `compositions` must not wipe out a// known-good list — only replace it when the field is present.compositionPaths: data.compositions ?? prev.compositionPaths,+ fonts: data.fonts ?? prev.fonts,}: prev,);@@ -133,14 +136,14 @@ export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) {const fontAssets = useMemo<ImportedFontAsset[]>(() =>- (projectId ? assets : [])+ current?.fonts?.map(font => ({ ...font, url: buildProjectApiPath(projectId!, `/preview/${encodeUrlPath(font.path)}`) })) ?? (projectId ? assets : []).filter((asset) => FONT_EXT.test(asset)).map((asset) => ({family: fontFamilyFromAssetPath(asset),path: asset,url: projectId ? buildProjectApiPath(projectId, `/preview/${encodeUrlPath(asset)}`) : "",})),- [assets, projectId],+ [assets, projectId, current?.fonts],);return {diff --git a/studio/src/utils/studioFontHelpers.ts b/studio/src/utils/studioFontHelpers.tsindex 22b84cd8..03a272d0 100644--- a/studio/src/utils/studioFontHelpers.ts+++ b/studio/src/utils/studioFontHelpers.ts@@ -1,32 +1,6 @@-import { googleFontStylesheetUrl } from "../components/editor/fontCatalog";import { importedFontFaceCss, type ImportedFontAsset } from "../components/editor/fontAssets";import { toRelativeProjectAssetPath } from "./studioHelpers";-const GENERIC_FONT_FAMILIES = new Set([- "inherit",- "initial",- "revert",- "revert-layer",- "serif",- "sans-serif",- "monospace",- "cursive",- "fantasy",- "system-ui",- "ui-sans-serif",- "ui-serif",- "ui-monospace",- "ui-rounded",- "emoji",- "math",- "fangsong",-]);--function primaryFontFamilyFromCss(value: string): string {- const first = value.split(",")[0] ?? "";- return first.trim().replace(/^["']|["']$/g, "");-}-export function primaryFontFamilyValue(value: string): string {return (value@@ -37,20 +11,6 @@ export function primaryFontFamilyValue(value: string): string {);}-export function injectPreviewGoogleFont(doc: Document, fontFamilyValue: string): void {- const family = primaryFontFamilyFromCss(fontFamilyValue);- if (!family || GENERIC_FONT_FAMILIES.has(family.toLowerCase())) return;-- const id = `studio-preview-google-font-${family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;- if (doc.getElementById(id)) return;-- const link = doc.createElement("link");- link.id = id;- link.rel = "stylesheet";- link.href = googleFontStylesheetUrl(family);- doc.head.appendChild(link);-}-export function injectPreviewImportedFont(doc: Document, asset: ImportedFontAsset): void {const id = `studio-imported-font-${asset.path.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;if (doc.getElementById(id)) return;diff --git a/studio/tests/e2e/local-fonts.mjs b/studio/tests/e2e/local-fonts.mjsnew file mode 100644index 00000000..477dbc01--- /dev/null+++ b/studio/tests/e2e/local-fonts.mjs@@ -0,0 +1,212 @@+// Run inside browser-lock.sh; uses its web/API ports and an isolated project.+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { mkdir, mkdtemp, readFile, writeFile, readdir } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawn, execFileSync } from 'node:child_process';+import puppeteer from 'puppeteer-core';+import { create } from 'fontkit';+import { WorkspaceStore } from '../../../workspace.ts';+import { handler } from '../../../server.ts';+import { startWorkspaceStudio } from '../../../shared/workspace-studio.ts';+import { resolveChromeExecutable } from './chrome-executable.mjs';++assert.ok(process.env.D4_LANE, 'Acquire the shared browser lane first');+const root = fileURLToPath(new URL('../../../', import.meta.url));+const output = process.env.EVIDENCE_DIR || await mkdtemp(path.join(tmpdir(), 'motion-font-e2e-'));+await mkdir(output, { recursive: true });+const store = new WorkspaceStore(await mkdtemp(path.join(output, 'workspace-')));+await store.initialize(root);+const assets = path.join(store.projectDirectory, 'assets/fonts');+await mkdir(assets, { recursive: true });+const ownedFonts = path.join(root, 'library/skills/motion-design-remix/assets/wireframe-portal-title/assets/fonts');+await writeFile(path.join(assets, 'material.ttf'), await readFile(path.join(ownedFonts, 'Geist-Regular.ttf')));+const entry = path.join(store.projectDirectory, 'index.html');+await writeFile(entry, `<!doctype html><html><head><script src="assets/gsap.min.js"></script><style>+@font-face{font-family:'Project Brand';src:url('assets/fonts/material.ttf')}+body{margin:0}#main{position:relative;width:640px;height:360px;background:#eee}+#title{position:absolute;left:40px;top:100px;font:32px system-ui;color:#222}+#material{position:absolute;left:40px;top:250px;font:24px 'Project Brand';color:#222}+</style></head><body><div id="main" data-composition-id="main" data-start="0" data-duration="1" data-width="640" data-height="360" data-fps="12">+<h1 id="title" class="clip" data-start="0" data-duration="1" data-track-index="0">Font test ABC 新标题</h1><p id="material">Material font sample</p>+</div><script>window.__timelines={main:gsap.timeline({paused:true})};</script></body></html>`);+const native = await startWorkspaceStudio(root, store.directory, store.projectDirectory, Number(process.env.D4_LANE_API_PORT));+const studio = { url: native.origin, alive: () => true, projectDirectory: store.projectDirectory };+const server = createServer((req, res) => void handler(req, res, store, { studio, runtimeRoot: root, nativeRoot: root, ffmpeg: true, ensureStudio: async () => studio }));+await new Promise(resolve => server.listen(Number(process.env.PLAYWRIGHT_WEB_PORT), '127.0.0.1', resolve));+const origin = `http://127.0.0.1:${server.address().port}`;+const results = { head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(), output, projectDirectory: store.projectDirectory, fonts: [], screenshots: [] };+let browser;+try {+ const families = (await (await fetch(`${origin}/api/fonts`)).json()).fonts;+ for (const family of ['Arial', 'Avenir Next', 'Songti SC', 'Hiragino Sans GB'].filter(family => families.includes(family))) {+ const response = await fetch(`${origin}/api/fonts/file?family=${encodeURIComponent(family)}`);+ assert.equal(response.status, 200);+ const metadata = JSON.parse(decodeURIComponent(response.headers.get('X-Font-Metadata')));+ const decoded = create(Buffer.from(await response.arrayBuffer()));+ assert.equal(metadata.postscriptName, decoded.postscriptName);+ assert.equal(metadata.family, family);+ assert.equal(metadata.style, 'normal');+ if (family === 'Arial') assert.equal(metadata.postscriptName, 'ArialMT');+ if (family === 'Avenir Next') assert.equal(metadata.postscriptName, 'AvenirNext-Regular');+ if (family === 'Songti SC') assert.equal(metadata.postscriptName, 'STSongti-SC-Regular');+ results.fonts.push(metadata);+ }+ if (!results.fonts.length) {+ const response = await fetch(`${origin}/api/fonts/file?family=${encodeURIComponent(families[0])}`);+ results.fonts.push(JSON.parse(decodeURIComponent(response.headers.get('X-Font-Metadata'))));+ }+ browser = await puppeteer.launch({ executablePath: resolveChromeExecutable(), headless: true });+ const page = await browser.newPage();+ page.on('console', message => { if (message.type() === 'error') console.log('Browser:', message.text()); });+ page.on('response', async response => { if (response.status() >= 400 && /\/api\//.test(response.url())) console.log('HTTP failure:', response.status(), response.url(), (await response.text().catch(() => '')).slice(0, 500)); });+ await page.setViewport({ width: 1440, height: 1000 });+ const client = await page.createCDPSession();+ await client.send('DOM.enable'); await client.send('CSS.enable');+ const capture = async name => {+ await page.evaluate(() => Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {}))));+ await page.screenshot({ path: path.join(output, name) }); results.screenshots.push(name);+ };+ const remoteFontRequests = [];+ page.on('request', request => { if (/fonts\.(googleapis|gstatic)\.com/.test(request.url())) remoteFontRequests.push(request.url()); });+ const url = `${origin}/?project=${store.projectId}#project/${store.projectId}`;+ const preview = () => page.evaluateHandle(() => document.querySelector('hyperframes-player').shadowRoot.querySelector('iframe').contentDocument);+ const selectTitle = async () => {+ await page.waitForFunction(() => !!document.querySelector('hyperframes-player')?.shadowRoot?.querySelector('iframe')?.contentDocument?.querySelector('#title'));+ await page.evaluate(() => Array.from(document.querySelectorAll('.hf-dock-side-rail')).find(rail => rail.getBoundingClientRect().left > innerWidth / 2)?.querySelector('.hf-dock-side-rail-items button')?.click());+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));+ // A saved project can replace its initial preview while fonts finish loading.+ for (let attempt = 0; attempt < 3; attempt++) {+ const at = await page.evaluate(async () => {+ const frame = document.querySelector('hyperframes-player').shadowRoot.querySelector('iframe');+ await frame.contentDocument.fonts.ready;+ const box = frame.getBoundingClientRect(), scale = box.width / frame.contentWindow.innerWidth;+ const rect = frame.contentDocument.querySelector('#title').getBoundingClientRect();+ return { x: box.left + (rect.left + rect.width / 2) * scale, y: box.top + (rect.top + rect.height / 2) * scale };+ });+ await page.mouse.click(at.x, at.y);+ if (await page.waitForSelector('[data-flat-font-trigger]', { timeout: 1500 }).catch(() => null)) return;+ }+ throw new Error('The loaded title could not be selected');+ };+ const choose = async family => {+ console.log('Choosing font:', family);+ await page.waitForSelector('[data-flat-font-trigger]:not(:disabled)');+ await page.click('[data-flat-font-trigger]');+ await page.locator('input[role="combobox"]').fill(family);+ await page.waitForFunction(family => Array.from(document.querySelectorAll('[data-font-option-index]')).some(el => el.querySelector('span[title]')?.title === family), {}, family);+ const item = await page.evaluateHandle(family => Array.from(document.querySelectorAll('[data-font-option-index]')).find(el => el.querySelector('span[title]')?.title === family), family);+ await item.asElement().click();+ };+ const applied = async family => {+ console.log('Waiting for applied font:', family);+ await page.waitForFunction(family => document.querySelector('[data-flat-font-trigger]')?.textContent.includes(family), {}, family);+ await page.waitForSelector('[data-flat-font-trigger]:not(:disabled)');+ await page.waitForFunction(() => !document.querySelector('input[role="combobox"]'));+ await (await preview()).evaluate(async doc => {+ const title = doc.querySelector('#title'), style = doc.defaultView.getComputedStyle(title);+ await doc.fonts.load(`${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, title.textContent);+ });+ await page.waitForFunction(() => !/Saving|正在保存/.test(document.body.innerText));+ await page.waitForFunction(async ({ family, id }) => {+ const data = await (await fetch(`/api/projects/${id}/files/index.html`)).json();+ return new DOMParser().parseFromString(data.content, 'text/html').querySelector('#title')?.style.fontFamily.includes(family);+ }, {}, { family, id: store.projectId });+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));+ };+ await page.goto(url, { waitUntil: 'domcontentloaded' });+ await selectTitle();+ for (const font of results.fonts) {+ await choose(font.family); await applied(font.family);+ await page.waitForFunction(family => document.querySelector('hyperframes-player').shadowRoot.querySelector('iframe').contentDocument.querySelector('#title').style.fontFamily.includes(family), {}, font.family);+ const source = await readFile(entry, 'utf8');+ assert.ok(source.includes('data-hf-studio-fonts="true"'));+ assert.ok(source.includes(font.family));+ const { root: dom } = await client.send('DOM.getDocument', { depth: -1, pierce: true });+ const findTitle = node => node.attributes?.some((value, index) => value === 'id' && node.attributes[index + 1] === 'title') ? node : [...node.children ?? [], ...node.shadowRoots ?? [], ...node.contentDocument ? [node.contentDocument] : []].map(findTitle).find(Boolean);+ const title = findTitle(dom);+ assert.ok(title, 'CDP sees the rendered title');+ const rendered = (await client.send('CSS.getPlatformFontsForNode', { nodeId: title.nodeId })).fonts;+ assert.ok(rendered.some(face => face.postScriptName === font.postscriptName && face.isCustomFont && face.glyphCount > 0), JSON.stringify(rendered));+ font.rendered = rendered;+ }+ await capture('local-font.png');+ const before = await readFile(entry, 'utf8');+ console.log('Reopening local font');+ await page.reload({ waitUntil: 'domcontentloaded' }); await selectTitle();+ await applied(results.fonts.at(-1).family);+ assert.equal(await readFile(entry, 'utf8'), before);+ results.reopen = true;++ const current = results.fonts.at(-1).family;+ console.log('Rejecting invalid import');+ await page.click('[data-flat-font-trigger]');+ let input = await page.$('input[type="file"][accept*=".ttf"]');+ const bad = path.join(output, 'Broken.ttf'); await writeFile(bad, 'not a font');+ await input.uploadFile(bad);+ await page.waitForFunction(() => document.body.innerText.includes('current font was kept'));+ assert.ok(await page.$eval('[data-flat-font-trigger]', (el, current) => el.textContent.includes(current), current));+ assert.equal((await readdir(assets)).some(file => file.includes('Broken')), false);+ await capture('invalid-font.png');+ results.invalidRejectedBeforeUpload = true;+ await page.keyboard.press('Escape');++ const projectFonts = (await (await fetch(`${origin}/api/projects/${store.projectId}`)).json()).fonts;+ const largeFont = projectFonts.find(font => font.family === 'Songti SC');+ if (largeFont) {+ console.log('Importing a large CJK font file');+ await page.click('[data-flat-font-trigger]');+ input = await page.$('input[type="file"][accept*=".ttf"]');+ await input.uploadFile(path.join(store.projectDirectory, largeFont.path));+ await applied(largeFont.family);+ results.largeCjkFileImport = true;+ }++ await page.click('[data-flat-font-trigger]'); input = await page.$('input[type="file"][accept*=".ttf"]');+ console.log('Importing a valid font');+ await input.uploadFile(path.join(ownedFonts, 'Geist-Bold.ttf')); await applied('Geist');+ const importedSource = await readFile(entry, 'utf8');+ assert.match(importedSource, /font-weight: 700/);+ await page.reload({ waitUntil: 'domcontentloaded' }); await selectTitle(); await applied('Geist');+ const listing = await (await fetch(`${origin}/api/projects/${store.projectId}`)).json();+ assert.ok(listing.fonts.some(font => font.family === 'Geist' && font.weight === '700'));+ results.importedMetadataSurvivesReopen = true;++ await choose('Project Brand'); await applied('Project Brand');+ assert.ok((await readFile(entry, 'utf8')).includes('Project Brand'));+ await capture('material-font.png');+ await page.click('[data-flat-font-trigger]');+ const remote = ['Pacifico', 'Roboto Slab', 'ABeeZee'].find(family => !families.includes(family));+ if (remote) {+ await page.locator('input[role="combobox"]').fill(remote);+ assert.equal(await page.$$eval('[data-font-option-index]', elements => elements.length), 0);+ }+ await page.keyboard.press('Escape');+ assert.deepEqual(remoteFontRequests, []);+ results.noRemoteSuggestionsOrRequests = true;+ await choose(results.fonts.at(-1).family); await applied(results.fonts.at(-1).family);+ await writeFile(path.join(output, 'saved-index.html'), await readFile(entry));+ await writeFile(path.join(output, 'browser-result.json'), JSON.stringify(results, null, 2));+ console.log(JSON.stringify(results));++ if (process.env.FONT_E2E_RENDER === '1') {+ const render = await new Promise(resolve => {+ const child = spawn(process.execPath, [path.join(root, 'node_modules/hyperframes/bin/hyperframes.mjs'), 'render', store.projectDirectory, '--output', path.join(output, 'font-test.mp4'), '--workers', '1', '--quality', 'draft', '--experimental-fast-capture=false', '--json'], { cwd: root, env: process.env });+ let stdout = '', stderr = '';+ child.stdout.on('data', data => { stdout += data; }); child.stderr.on('data', data => { stderr += data; });+ child.on('close', code => resolve({ code, stdout, stderr }));+ });+ await writeFile(path.join(output, 'render.log'), render.stdout + render.stderr);+ assert.equal(render.code, 0, render.stderr);+ results.rendered = true;+ await writeFile(path.join(output, 'browser-result.json'), JSON.stringify(results, null, 2));+ }+} catch (error) {+ const page = (await browser?.pages())?.at(-1);+ if (page) { await page.screenshot({ path: path.join(output, 'failure.png') }); await writeFile(path.join(output, 'failure-text.txt'), await page.evaluate(() => document.body.innerText)); }+ throw error;+} finally {+ await browser?.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await native.close();+}diff --git a/tests/studio-fonts.test.ts b/tests/studio-fonts.test.tsnew file mode 100644index 00000000..217a0747--- /dev/null+++ b/tests/studio-fonts.test.ts@@ -0,0 +1,68 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile, mkdtemp, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { create } from 'fontkit';+import { createFontCatalog, extractCollectionFace, fontFaces, prepareFont } from '../shared/studio-fonts.ts';++const fontRoot = new URL('../library/skills/motion-design-remix/assets/wireframe-portal-title/assets/fonts/', import.meta.url);+const regular = await readFile(new URL('Geist-Regular.ttf', fontRoot));+const bold = await readFile(new URL('Geist-Bold.ttf', fontRoot));++function collection(...fonts: Buffer[]) {+ let offset = 12 + fonts.length * 4;+ const result = Buffer.alloc(offset + fonts.reduce((size, font) => size + Math.ceil(font.length / 4) * 4, 0));+ result.write('ttcf'); result.writeUInt32BE(0x00010000, 4); result.writeUInt32BE(fonts.length, 8);+ fonts.forEach((font, index) => {+ result.writeUInt32BE(offset, 12 + index * 4); font.copy(result, offset);+ for (let i = 0; i < font.readUInt16BE(4); i++) {+ const entry = offset + 12 + i * 16;+ result.writeUInt32BE(result.readUInt32BE(entry + 8) + offset, entry + 8);+ }+ offset += Math.ceil(font.length / 4) * 4;+ });+ return result;+}++test('a collection selects its regular face and preserves every table, glyph and identity', () => {+ const bytes = collection(bold, regular);+ const faces = fontFaces(bytes, create);+ assert.deepEqual(faces.map(face => face.weight), ['700', '400']);+ const prepared = prepareFont(bytes, create, faces[0].family);+ const result = create(prepared.data), original = create(regular);+ assert.equal(prepared.weight, '400');+ assert.equal(result.postscriptName, original.postscriptName);+ assert.equal(result.numGlyphs, original.numGlyphs);+ assert.deepEqual(result.characterSet, original.characterSet);+ assert.deepEqual(Object.keys(result.directory.tables), Object.keys(original.directory.tables));+ let checksum = 0;+ for (let i = 0; i < prepared.data.length; i += 4) checksum = (checksum + prepared.data.readUInt32BE(i)) >>> 0;+ assert.equal(checksum, 0xB1B0AFBA);+});++test('a misleading filename cannot change the family or force a bold face', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motion-font-catalog-'));+ try {+ const misleading = path.join(root, 'Arial Black.ttf'), normal = path.join(root, 'other.ttf');+ await writeFile(misleading, bold); await writeFile(normal, regular);+ const family = fontFaces(regular, create)[0].family;+ const catalog = createFontCatalog([misleading, normal, misleading], create);+ assert.deepEqual(await catalog.families(), [family]);+ assert.equal((await catalog.file(family))?.postscriptName, create(regular).postscriptName);+ assert.equal(await catalog.file('Arial'), null);+ assert.equal(await catalog.file('../../package.json'), null);+ } finally { await rm(root, { recursive: true, force: true }); }+});++test('malformed collections and unsupported bytes fail before extraction or import', () => {+ assert.throws(() => prepareFont(Buffer.from('not a font'), create));+ const bad = collection(bold, regular);+ bad.writeUInt32BE(0xffffffff, 12);+ assert.throws(() => extractCollectionFace(bad, 0));+ assert.throws(() => extractCollectionFace(collection(bold), 1));+ const table = collection(regular);+ const start = table.readUInt32BE(12);+ table.writeUInt32BE(0xffffffff, start + 12 + 12);+ assert.throws(() => extractCollectionFace(table, 0));+});diff --git a/tests/workspace-studio.test.ts b/tests/workspace-studio.test.tsindex c5f190db..8ca1a634 100644--- a/tests/workspace-studio.test.ts+++ b/tests/workspace-studio.test.ts@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { mkdtemp, mkdir, writeFile, copyFile, readdir, rm } from 'node:fs/promises';+import { mkdtemp, mkdir, writeFile, copyFile, readdir, rm, open, symlink } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';import { pathToFileURL } from 'node:url';@@ -8,6 +8,25 @@ import { startWorkspaceStudio } from '../shared/workspace-studio.ts';import { request } from 'node:http';import { fixture } from './fixtures.ts';import { pluginRoot } from '../hyperframes.ts';+import { readFontFile } from '../shared/studio-fonts.ts';+import { create } from 'fontkit';++test('system fonts above 5 MiB remain readable with the asset limit and no-follow guard', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motion-system-font-'));+ const font = { path: path.join(root, 'CJK.ttc'), format: 'ttc' };+ const bytes = Buffer.alloc(6 * 1024 * 1024, 0x42);+ try {+ await writeFile(font.path, bytes);+ assert.deepEqual(await readFontFile(font.path), bytes);+ const link = path.join(root, 'link.ttc');+ await symlink(font.path, link);+ await assert.rejects(readFontFile(link));+ await assert.rejects(readFontFile(root));+ const file = await open(font.path, 'r+');+ try { await file.truncate(500_000_001); } finally { await file.close(); }+ await assert.rejects(readFontFile(font.path), /500 MB/);+ } finally { await rm(root, { recursive: true, force: true }); }+});test('Studio rejects decimal uploads above 500 MB before saving and still accepts normal uploads', () => fixture(async store => {const studio = await startWorkspaceStudio(pluginRoot, store.directory, store.projectDirectory, 0);@@ -15,6 +34,8 @@ test('Studio rejects decimal uploads above 500 MB before saving and still acceptconst assets = path.join(store.projectDirectory, 'assets');const before = await readdir(assets);try {+ assert.equal((await fetch(studio.origin + '/api/fonts/file')).status, 400);+ assert.equal((await fetch(studio.origin + '/api/fonts/file?family=../../package.json')).status, 404);for (const size of [500_000_001, 500_500_000, 524_288_000]) {const response = await new Promise<{ status: number; body: string }>((resolve, reject) => {const req = request(url, { method: 'POST', headers: { Origin: studio.origin, 'Content-Length': size, Connection: 'close' } }, res => {@@ -49,6 +70,27 @@ test('the shipped history availability module loads without plugin-local node_mo} finally { await rm(root, { recursive: true, force: true }); }});+test('installed font import copies an actual face into only the requested project', () => fixture(async store => {+ const studio = await startWorkspaceStudio(pluginRoot, store.directory, store.projectDirectory, 0);+ const url = `${studio.origin}/api/projects/${store.projectId}/fonts/import`;+ const post = body => fetch(url, { method: 'POST', headers: { Origin: studio.origin, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ try {+ assert.equal((await post({ path: '/etc/passwd' })).status, 400);+ assert.equal((await post({ family: '../../package.json' })).status, 404);+ assert.equal((await fetch(url, { method: 'POST', body: JSON.stringify({ family: 'Arial' }) })).status, 403);+ const { fonts } = await (await fetch(studio.origin + '/api/fonts')).json();+ assert.ok(fonts.length > 0, 'The runtime test requires the CI system fonts');+ const response = await post({ family: fonts[0] });+ assert.equal(response.status, 201);+ const font = await response.json();+ assert.ok(font.path.startsWith('assets/fonts/'));+ const decoded = create(await readFontFile(await store.safePath(font.path)));+ assert.equal(decoded.getName('preferredFamily') || decoded.familyName, font.family);+ const listing = await (await fetch(`${studio.origin}/api/projects/${store.projectId}`)).json();+ assert.ok(listing.fonts.some(entry => entry.path === font.path && entry.family === font.family && entry.weight === font.weight));+ } finally { await studio.close(); }+}));+test('workspace host refuses unsupported, missing, ambiguous and incompatible native factories before serving', async () => {const root = await mkdtemp(path.join(tmpdir(), 'motion-host-contract-'));const cli = path.join(root, 'node_modules/hyperframes');