@hyperframes/core

类型定义、HTML 生成、运行时与 Linter — 所有其他包的基础依赖。

"@hyperframes/core"

core 包提供了基础类型、HTML 解析/生成、运行时和合成 Linter,所有其他 Hyperframes 包都构建于此之上。如果你正在开发工具、编写自定义集成或扩展 Hyperframes 本身,就需要使用这个包。

npm install @hyperframes/core

何时使用

💡 Tip

大多数用户不需要直接安装 @hyperframes/core CLIproducerstudio 包内部都依赖 core。只有在执行以下操作时才需要直接使用它。

在以下场景使用 @hyperframes/core

  • 通过编程方式检查合成(CI 流水线、编辑器插件)
  • 将 HTML 合成解析为结构化 TypeScript 对象
  • 从数据生成合成 HTML(例如从 API 或 AI Agent)
  • 在自定义工具中使用 Hyperframes 类型系统
  • 在自定义播放器中嵌入 Hyperframes 运行时

如果需要以下功能,请使用其他包:

  • 在浏览器中预览合成 — 使用 CLInpx hyperframes preview)或 studio
  • 将合渲染为 MP4 — 使用 CLInpx hyperframes render)或 producer
  • 从无头浏览器捕获帧 — 使用 engine

包导出

core 包有四个入口点:

导入路径描述
@hyperframes/core类型、解析器、生成器、适配器、运行时工具
@hyperframes/core/lint合成 Linter
@hyperframes/core/compiler时序编译器、HTML 编译器、打包器、静态守卫
@hyperframes/core/runtime预构建的 IIFE 运行时,用于浏览器注入

类型

core 类型系统定义了合成、时间轴元素和变量的模型:

import type {
TimelineElement,
TimelineMediaElement,
TimelineTextElement,
TimelineCompositionElement,
TimelineElementType,       // "video" | "image" | "text" | "audio" | "composition"
CompositionSpec,
CompositionVariable,
CanvasResolution,          // "landscape" | "portrait" | "landscape-4k" | "portrait-4k" | "square" | "square-4k"
Orientation,               // "16:9" | "9:16"
FrameAdapter,
FrameAdapterContext,
} from '@hyperframes/core';

// 类型守卫
import {
isTextElement,
isMediaElement,
isCompositionElement,
isStringVariable,
isNumberVariable,
isColorVariable,
isBooleanVariable,
isEnumVariable,
} from '@hyperframes/core';

// 常量
import {
CANVAS_DIMENSIONS,        // { landscape: { width, height }, portrait: { width, height } }
TIMELINE_COLORS,
DEFAULT_DURATIONS,
} from '@hyperframes/core';

变量类型

合成可以暴露类型化的变量,用于动态内容:

import type {
CompositionVariableType,   // "string" | "number" | "color" | "boolean" | "enum"
StringVariable,
NumberVariable,
ColorVariable,
BooleanVariable,
EnumVariable,
} from '@hyperframes/core';

关键帧类型

import type {
Keyframe,
KeyframeProperties,
ElementKeyframes,
StageZoom,
StageZoomKeyframe,
} from '@hyperframes/core';

import { getDefaultStageZoom } from '@hyperframes/core';

HTML 解析与生成

在 HTML 和结构化数据之间进行双向转换:

import { parseHtml, generateHyperframesHtml } from '@hyperframes/core';
import type { ParsedHtml, CompositionMetadata } from '@hyperframes/core';

// 将 HTML 解析为结构化数据
const parsed: ParsedHtml = parseHtml(htmlString);
// parsed.elements, parsed.gsapScript, parsed.styles, parsed.resolution, parsed.keyframes

// 提取合成元数据
import { extractCompositionMetadata } from '@hyperframes/core';
const meta: CompositionMetadata = extractCompositionMetadata(htmlString);
// meta.id, meta.duration, meta.width, meta.height, meta.variables
//
// 变量元数据声明在文档根元素上,例如:
// <html
//   data-composition-id="card"
//   data-composition-duration="3"
//   data-composition-variables='[{"id":"title","label":"Title","type":"string","default":"Hello"}]'
// >

// 在合成内部读取解析后的变量(声明的默认值 +
// CLI 覆盖 + 每个实例的宿主 data-variable-values):
import { getVariables } from '@hyperframes/core';
const { title } = getVariables<{ title: string }>();

// 验证 CLI / 宿主覆盖是否符合声明的 schema:
import { validateVariables, formatVariableValidationIssue } from '@hyperframes/core';
const issues = validateVariables({ title: 'Hello', count: 'three' }, meta.variables);
for (const issue of issues) {
console.warn(formatVariableValidationIssue(issue));
}

// 从结构化数据生成 HTML
const html = generateHyperframesHtml(elements, {
animations,
styles,
resolution: 'landscape',
compositionId: 'my-video',
});

修改 HTML

import {
updateElementInHtml,
addElementToHtml,
removeElementFromHtml,
validateCompositionHtml,
} from '@hyperframes/core';

// 更新元素属性
const updatedHtml = updateElementInHtml(html, 'el-1', { start: 5 });

// 添加新元素
const newHtml = addElementToHtml(html, newElement);

// 移除元素
const cleanHtml = removeElementFromHtml(html, 'el-1');

// 验证 HTML 结构
const result = validateCompositionHtml(html);
// result.valid, result.errors

GSAP 脚本解析

import {
parseGsapScript,
serializeGsapAnimations,
updateAnimationInScript,
addAnimationToScript,
removeAnimationFromScript,
getAnimationsForElement,
validateCompositionGsap,
keyframesToGsapAnimations,
gsapAnimationsToKeyframes,
SUPPORTED_PROPS,            // 可动画属性
SUPPORTED_EASES,            // 可用的缓动函数
} from '@hyperframes/core';
import type { GsapAnimation, GsapMethod, ParsedGsap } from '@hyperframes/core';

// 将 GSAP 脚本解析为结构化动画
const parsed: ParsedGsap = parseGsapScript(scriptContent);
// parsed.animations, parsed.timelineVar, parsed.preamble, parsed.postamble

// 序列化回脚本
const script = serializeGsapAnimations(parsed.animations);

HTML 生成

import {
generateHyperframesHtml,
generateGsapTimelineScript,
generateHyperframesStyles,
} from '@hyperframes/core';

// 生成完整的 HTML 合成
const html = generateHyperframesHtml(elements, options);

// 仅生成 GSAP 脚本
const script = generateGsapTimelineScript(animations, options);

// 生成 CSS 样式
const { coreCss, customCss, googleFontsLink } = generateHyperframesStyles(
elements, 'landscape', customStyles
);

模板工具

import {
generateBaseHtml,
getStageStyles,
GSAP_CDN,
BASE_STYLES,
ELEMENT_BASE_STYLES,
MEDIA_STYLES,
TEXT_STYLES,
ZOOM_CONTAINER_STYLES,
} from '@hyperframes/core';

// 为指定分辨率生成基础 HTML 结构
const baseHtml = generateBaseHtml('landscape');
const styles = getStageStyles('portrait');

Linter

合成 Linter 会检查可能导致渲染失败或异常行为的结构问题。你可以通过 CLI 使用 npx hyperframes lint 运行,或通过编程方式调用:

import { lintHyperframeHtml, lintMediaUrls } from '@hyperframes/core/lint';
import type {
HyperframeLintResult,
HyperframeLintFinding,
HyperframeLintSeverity,     // "error" | "warning"
HyperframeLinterOptions,
} from '@hyperframes/core/lint';

const result: HyperframeLintResult = lintHyperframeHtml(html, { filePath: 'index.html' });
// result.ok, result.errorCount, result.warningCount, result.findings

for (const finding of result.findings) {
console.log(finding.severity, finding.code, finding.message);
// finding.file, finding.selector, finding.elementId, finding.fixHint, finding.snippet
}

// 附加的媒体 URL 验证
const mediaFindings = lintMediaUrls(result.findings);

检测到的问题包括:

  • 缺少时间轴注册(window.__timelines
  • 未静音的视频元素(导致自动播放失败)
  • 定时可见元素缺少 class="clip"
  • 已弃用的属性名称
  • 缺少合成尺寸(data-widthdata-height
  • data-start 引用了不存在的 clip ID
关于 Linter 可检测的所有问题及其修复方法,请参阅 [常见错误](/guides/common-mistakes) 和 [故障排查](/guides/troubleshooting)。

编译器

编译器子包处理时序解析、HTML 编译和打包:

// 时序编译器(浏览器安全 — 无 Node.js 依赖)
import {
compileTimingAttrs,
injectDurations,
extractResolvedMedia,
clampDurations,
} from '@hyperframes/core/compiler';
import type {
UnresolvedElement,
ResolvedDuration,
ResolvedMediaElement,
CompilationResult,
} from '@hyperframes/core/compiler';

// 从 HTML 编译时序属性
const compiled: CompilationResult = compileTimingAttrs(html);

// 将解析后的时长注入回 HTML
const updatedHtml = injectDurations(html, compiled.durations);

// 提取解析后的媒体元素
const media: ResolvedMediaElement[] = extractResolvedMedia(html);
// HTML 编译器(Node.js — 需要媒体探测)
import { compileHtml } from '@hyperframes/core/compiler';
import type { MediaDurationProber } from '@hyperframes/core/compiler';

const prober: MediaDurationProber = async (src) => getDuration(src);
const compiledHtml = await compileHtml(html, prober);
// HTML 打包器(Node.js — 打包为单个文件)
import { bundleToSingleHtml } from '@hyperframes/core/compiler';
import type { BundleOptions } from '@hyperframes/core/compiler';

const bundled = await bundleToSingleHtml({ entryPath: './index.html', inline: true });
// 静态守卫 — 验证 HTML 约定
import { validateHyperframeHtmlContract } from '@hyperframes/core/compiler';
import type {
HyperframeStaticGuardResult,
HyperframeStaticFailureReason,
} from '@hyperframes/core/compiler';

const guard: HyperframeStaticGuardResult = validateHyperframeHtmlContract(html);
// guard.ok, guard.failures[]
// 失败原因:"missing_composition_id" | "missing_composition_dimensions"
//   | "missing_timeline_registry" | "invalid_script_syntax"
//   | "invalid_static_hyperframe_contract"

运行时

Hyperframes 运行时在浏览器中管理播放、跳转和 clip 生命周期。core 包提供了构建和加载运行时的工具:

import {
loadHyperframeRuntimeSource,
buildHyperframesRuntimeScript,
HYPERFRAME_RUNTIME_ARTIFACTS,
HYPERFRAME_RUNTIME_CONTRACT,
HYPERFRAME_RUNTIME_GLOBALS,
HYPERFRAME_BRIDGE_SOURCES,
HYPERFRAME_CONTROL_ACTIONS,
} from '@hyperframes/core';
import type {
HyperframeControlAction,
HyperframesRuntimeBuildOptions,
} from '@hyperframes/core';

// 加载预构建的运行时 IIFE
const runtimeSource = loadHyperframeRuntimeSource();

// 构建自定义运行时脚本
const script = buildHyperframesRuntimeScript(options);

预构建的运行时 IIFE 可以直接导入:

import runtime from '@hyperframes/core/runtime';

Frame 适配器

core 包定义了 Frame 适配器 接口,并提供了内置的 GSAP 适配器:

import { createGSAPFrameAdapter } from '@hyperframes/core';
import type {
FrameAdapter,
FrameAdapterContext,
GSAPTimelineLike,
CreateGSAPFrameAdapterOptions,
} from '@hyperframes/core';

// 创建 GSAP Frame 适配器
const adapter: FrameAdapter = createGSAPFrameAdapter({
id: 'my-composition',
fps: 30,
imeline: gsapTimeline,
});

// 适配器生命周期
await adapter.init?.(context);
const durationFrames = adapter.getDurationFrames();
await adapter.seekFrame(42);
await adapter.destroy?.();

媒体工具

import {
MEDIA_VISUAL_STYLE_PROPERTIES,
copyMediaVisualStyles,
quantizeTimeToFrame,
} from '@hyperframes/core';
import type { MediaVisualStyleProperty } from '@hyperframes/core';

// 将时间值量化到最近的帧边界
const frameTime = quantizeTimeToFrame(5.033, 30); // → 5.033... 吸附到帧

// 在媒体元素之间复制视觉样式
copyMediaVisualStyles(fromElement, toElement);

Picker API

用于编辑器 UI 中的元素选择:

import type {
HyperframePickerApi,
HyperframePickerBoundingBox,
HyperframePickerElementInfo,
} from '@hyperframes/core';

相关包

  • CLI 创建、预览、检查和渲染合成的最简单方式。
  • Engine 使用 core 类型和运行时的底层帧捕获管道。
  • Producer 构建在 core 和 engine 之上的完整渲染管道。
  • Studio 嵌入 core 运行时进行预览的可视化合成编辑器。