mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-24 16:06:34 +00:00
fix(core): preserve held scene dependencies and root timing
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hyperframes",
|
||||
"description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"author": {
|
||||
"name": "HeyGen",
|
||||
"email": "hyperframes@heygen.com",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hyperframes",
|
||||
"description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"author": {
|
||||
"name": "HeyGen",
|
||||
"email": "hyperframes@heygen.com",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "hyperframes",
|
||||
"displayName": "HyperFrames by HeyGen",
|
||||
"description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"author": {
|
||||
"name": "HeyGen",
|
||||
"email": "hyperframes@heygen.com"
|
||||
|
||||
@@ -8,6 +8,88 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio
|
||||
|
||||
{/* New release entries are prepended by `bun run changelog:draft <version> --write`. */}
|
||||
|
||||
<Update
|
||||
label="HyperFrames v0.8.169"
|
||||
description="Released - 2026-10-17"
|
||||
tags={["Release", "CLI", "Gcp Cloud Run", "Studio"]}
|
||||
>
|
||||
Rendering from inside an agent's macOS sandbox now works, because Chrome starts as one process instead of several that the sandbox blocks.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **CLI:** Chrome starts inside an agent's macOS sandbox as one process over a pipe ([5e7ba0be944](https://github.com/heygen-com/hyperframes/commit/5e7ba0be944b076d514fc082c25a0b7e35eeb42f), [#5781](https://github.com/heygen-com/hyperframes/pull/5781)).
|
||||
- **Gcp Cloud Run:** The BeginFrame contract image resolves the engine's core import ([b18b3e958aa](https://github.com/heygen-com/hyperframes/commit/b18b3e958aa199529fa5fa06728e81b97d520021), [#5785](https://github.com/heygen-com/hyperframes/pull/5785)).
|
||||
|
||||
## Internal
|
||||
|
||||
- **Studio:** The edit accuracy bench starts one server when node is a Volta shim ([c7151399769](https://github.com/heygen-com/hyperframes/commit/c71513997694f6f56e230d768b6f5c9ed7a73fab), [#5779](https://github.com/heygen-com/hyperframes/pull/5779)).
|
||||
|
||||
[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.168...v0.8.169).
|
||||
</Update>
|
||||
|
||||
<Update
|
||||
label="HyperFrames v0.8.168"
|
||||
description="Released - 2026-10-17"
|
||||
tags={["Release", "Core", "Engine", "Producer"]}
|
||||
>
|
||||
Scrubbing back across a scene in the preview now shows its content instead of an empty frame. Cloud renders size their chunks to the worker limit and assemble in one pass, so long videos finish faster.
|
||||
|
||||
## Features
|
||||
|
||||
- **Producer:** Distributed renders accept 25 fps ([cc9e1bb33a4](https://github.com/heygen-com/hyperframes/commit/cc9e1bb33a430b878af6dcb257ce5c9a70f9f180), [#5423](https://github.com/heygen-com/hyperframes/pull/5423)).
|
||||
- **Producer:** Render at 720p and 480p from a larger composition ([09c0307c3fd](https://github.com/heygen-com/hyperframes/commit/09c0307c3fd0318a7ea77e6b41df4e5d30a1902b), [#5724](https://github.com/heygen-com/hyperframes/pull/5724)).
|
||||
|
||||
## Fixes
|
||||
|
||||
- **Core:** Scrubbing back across a scene no longer leaves its content hidden ([4cf0e3a0e59](https://github.com/heygen-com/hyperframes/commit/4cf0e3a0e599c73a9a96efcee8f62099323a08cf), [#5766](https://github.com/heygen-com/hyperframes/pull/5766)).
|
||||
- **Engine:** Local renders lay out width-only videos like the browser ([fc41fa277a5](https://github.com/heygen-com/hyperframes/commit/fc41fa277a5649eb4879b524192dd6bee39d7465), [#5771](https://github.com/heygen-com/hyperframes/pull/5771)).
|
||||
- **CLI:** A browser a sandbox refuses says to rerun the command with escalation ([fa936691562](https://github.com/heygen-com/hyperframes/commit/fa9366915620ea9baa1d03b0eb44caaca013dc21), [#5734](https://github.com/heygen-com/hyperframes/pull/5734)).
|
||||
- **CLI:** Check's dense overlap pass takes at most 240 samples, at clip windows first ([caea3863b07](https://github.com/heygen-com/hyperframes/commit/caea3863b075f5f79d1c77dd084d05ea05aa0529), [#5764](https://github.com/heygen-com/hyperframes/pull/5764)).
|
||||
- **Lint:** Stop flagging dir on \<html\>; a render test now guards RTL export ([e6ce7337962](https://github.com/heygen-com/hyperframes/commit/e6ce73379620fb2abf73e0ab681e85fd7f938725), [#5744](https://github.com/heygen-com/hyperframes/pull/5744)).
|
||||
- **Skills:** Regenerate manifest after HyperFrames guidance update ([40c64255e8c](https://github.com/heygen-com/hyperframes/commit/40c64255e8c0a3d11a0d6e8229b7a88877c84401), [#5747](https://github.com/heygen-com/hyperframes/pull/5747)).
|
||||
- **CLI:** Honour HYPERFRAMES_SKIP_SKILLS in skills update and bare skills ([6dba67a0c3a](https://github.com/heygen-com/hyperframes/commit/6dba67a0c3a0a51247ab85bbc245f1cf3effa0dc), [#5743](https://github.com/heygen-com/hyperframes/pull/5743)).
|
||||
- **CLI:** Timeline lists clips nested in a timed element and lint flags ones that never show ([eab6ca15b1a](https://github.com/heygen-com/hyperframes/commit/eab6ca15b1af7ec7bca0bbeb4cd0330e677467a5), [#5732](https://github.com/heygen-com/hyperframes/pull/5732)).
|
||||
- **Engine:** A WebGPU block mounted as a sub-composition gets WebGPU like a root one ([4e6ee6d2300](https://github.com/heygen-com/hyperframes/commit/4e6ee6d2300290b638042ec88ef5afb7a0c27408), [#5735](https://github.com/heygen-com/hyperframes/pull/5735)).
|
||||
- **Core:** A composition mounted twice keeps each mount's own timeline ([c38e9f350b4](https://github.com/heygen-com/hyperframes/commit/c38e9f350b4dbe6b09a6a35d5db0d437b9464220), [#5729](https://github.com/heygen-com/hyperframes/pull/5729)).
|
||||
|
||||
## Performance
|
||||
|
||||
- **Producer:** Assemble in one pass and keep its disk use under one output copy ([a498cf2032c](https://github.com/heygen-com/hyperframes/commit/a498cf2032c6b22492dedb475ad6196a8d6c6797), [#5768](https://github.com/heygen-com/hyperframes/pull/5768)).
|
||||
- **Producer:** Size distributed chunks to the worker limit and concurrency ([c69fd2c6eca](https://github.com/heygen-com/hyperframes/commit/c69fd2c6ecadedff88cdc09d37854a658bffb733), [#5765](https://github.com/heygen-com/hyperframes/pull/5765)).
|
||||
|
||||
## Internal
|
||||
|
||||
- **Core:** One owner for the distributed fps set ([d5162beb50a](https://github.com/heygen-com/hyperframes/commit/d5162beb50a402a69423df106647347bd0f8763e), [#5756](https://github.com/heygen-com/hyperframes/pull/5756)).
|
||||
|
||||
[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.167...v0.8.168).
|
||||
</Update>
|
||||
|
||||
<Update
|
||||
label="HyperFrames v0.8.167"
|
||||
description="Released - 2026-10-16"
|
||||
tags={["Release", "Core", "CLI", "Lint"]}
|
||||
>
|
||||
Long projects preview more smoothly: the preview's work now follows what is playing, not the total clip count. Bundling a project also stops freezing the app that runs it.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **Core:** Bundling a project no longer blocks the host's thread on esbuild ([b1cf6e3c517](https://github.com/heygen-com/hyperframes/commit/b1cf6e3c517e227d1dca1b212e7637c19e502a64), [#5714](https://github.com/heygen-com/hyperframes/pull/5714)).
|
||||
- **CLI:** Page loads stop timing out while a busy machine's Chrome warms up ([41486b9725a](https://github.com/heygen-com/hyperframes/commit/41486b9725ab2aae4f457d75dcd625931d103bb3), [#5705](https://github.com/heygen-com/hyperframes/pull/5705)).
|
||||
|
||||
## Performance
|
||||
|
||||
- **Core:** Hold a clip at 0 inside a later scene until it is due ([13ea8349597](https://github.com/heygen-com/hyperframes/commit/13ea8349597bbcb874402d1771aea65766fd7ffc), [#5716](https://github.com/heygen-com/hyperframes/pull/5716)).
|
||||
- **Core:** A preview's composition scripts give the page a turn every 50 ms, not one long task ([12d8df37f4d](https://github.com/heygen-com/hyperframes/commit/12d8df37f4db8ccf019da32c97cc1352f8db9652), [#5713](https://github.com/heygen-com/hyperframes/pull/5713)).
|
||||
- **Lint:** Strip stylesheet comments once per canvas zoom scan ([0bff8342c38](https://github.com/heygen-com/hyperframes/commit/0bff8342c389c1841d3b8d858168700f13627e48), [#5712](https://github.com/heygen-com/hyperframes/pull/5712)).
|
||||
- **Core:** Preview runtime scales with what plays, not with the film's clip count ([d05bc4215d5](https://github.com/heygen-com/hyperframes/commit/d05bc4215d5757da86956217f4a8a4b2ab11b1fd), [#5674](https://github.com/heygen-com/hyperframes/pull/5674)).
|
||||
|
||||
## Internal
|
||||
|
||||
- **CLI:** Caption image test checks the close itself, not a reusable file number ([eace3d28b6c](https://github.com/heygen-com/hyperframes/commit/eace3d28b6cb721ec1f9a96d7d2ea76bf215551a), [#5707](https://github.com/heygen-com/hyperframes/pull/5707)).
|
||||
|
||||
[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.166...v0.8.167).
|
||||
</Update>
|
||||
|
||||
<Update
|
||||
label="HyperFrames v0.8.166"
|
||||
description="Released - 2026-10-16"
|
||||
|
||||
@@ -52,13 +52,13 @@ Most adopters' render config maps directly:
|
||||
|
||||
| Concept | HyperFrames equivalent | Where it lives |
|
||||
| ------------------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `fps` | `--fps=30` (CLI) or `config.fps` (SDK) | 24, 30, 60 only — non-integer NTSC rationals are an in-process-only feature. |
|
||||
| `fps` | `--fps=30` (CLI) or `config.fps` (SDK) | 24, 25, 30, 60 only — non-integer NTSC rationals are an in-process-only feature. |
|
||||
| `width` / `height` | `--width` / `--height` flags, or `config.width` / `config.height` | Even integers ≤ 7680 (yuv420p parity). |
|
||||
| `codec: 'h264' / 'h265'` | `--codec=h264` or `--codec=h265` (mp4 only) | h265 uses libx265 with closed-GOP keyint params so chunked concat-copy round-trips losslessly. |
|
||||
| Output format | `--format=mp4 / mov / webm / png-sequence` | webm uses libvpx-vp9 + closed-GOP concat-copy. Distributed mode still refuses HDR mp4 at plan time. |
|
||||
| Quality preset | `--quality=draft / standard / high` | Maps onto ffmpeg encoder presets. |
|
||||
| Chunk size in frames | `--chunk-size=240` (default 240) | ~8s at 30 fps; sized to fit Lambda's 15-min cap with headroom. |
|
||||
| Max parallel chunks | `--max-parallel-chunks=16` (default 16) | Caps the Map state's fan-out. |
|
||||
| Chunk size in frames | `--chunk-size=240` (default: auto) | By default each chunk is sized to finish inside the Lambda timeout with headroom; a render that cannot fails at plan time with `CHUNK_EXCEEDS_WORKER_TIMEOUT`. |
|
||||
| Max parallel chunks | `--max-parallel-chunks=16` (default: auto) | By default one wave across the deploy's `--concurrency` (16 if unknown), widened when a chunk would outrun the Lambda timeout. |
|
||||
| Per-chunk frame ceiling | `--target-chunk-frames=N` (optional) | Caps frames per chunk so one chunk can't run past Lambda's 15-min cap on a long video: the planner adds chunks (up to `--max-parallel-chunks`) to keep each at or below `N`, and short videos still collapse to fewer chunks. A ceiling, not a fixed size; ignored when `--chunk-size` is set. |
|
||||
| Bitrate / CRF | `config.bitrate` or `config.crf` in the SDK | Mutually exclusive; the current Lambda CLI does not expose these two fields. |
|
||||
|
||||
|
||||
@@ -1648,6 +1648,10 @@ adds it. `check` and `update` both accept `--json`, plus `--dir` and `--source`
|
||||
to point removed-detection at a different skills directory or source — those two
|
||||
scope the prune, not the install.
|
||||
|
||||
Set `HYPERFRAMES_SKIP_SKILLS=1` when something else manages the skills (CI, tests,
|
||||
or an install pinned to one commit). `skills update` and bare `skills` then exit 0
|
||||
with a one-line notice and leave the installed skills unchanged.
|
||||
|
||||
The CLI installs from the current HyperFrames GitHub source and links the global
|
||||
bundles into whichever compatible agents it finds. After scaffolding, `init`
|
||||
also refreshes the core set plus any HyperFrames skills you already have.
|
||||
@@ -1933,13 +1937,13 @@ And these drive `render` and `render-batch`:
|
||||
| ----------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `--width`, `--height` | required | Render dimensions in pixels |
|
||||
| `--site-id` | content hash | Reuse an uploaded site instead of uploading again |
|
||||
| `--fps` | `30` | `24`, `30`, or `60` |
|
||||
| `--fps` | `30` | `24`, `25`, `30`, or `60` |
|
||||
| `--format` | `mp4` | `mp4`, `mov`, `webm`, or `png-sequence` |
|
||||
| `--codec` | `h264` | `h264` or `h265`, MP4 only |
|
||||
| `--quality` | `standard` | `draft`, `standard`, or `high` |
|
||||
| `--output-resolution` | — | Supersample via Chrome `deviceScaleFactor` to a preset (`1080p`, `4k`, `uhd`, `hd`, `landscape-4k`, …) without changing layout |
|
||||
| `--chunk-size` | `240` | Frames per chunk |
|
||||
| `--max-parallel-chunks` | `16` | Concurrent chunks per render |
|
||||
| `--chunk-size` | auto | Frames per chunk. By default each chunk is sized to finish inside the Lambda timeout |
|
||||
| `--max-parallel-chunks` | auto | Chunks per render. By default one wave across the deploy's `--concurrency` (16 if unknown), widened when a chunk would outrun the Lambda timeout |
|
||||
| `--target-chunk-frames` | — | Ceiling on frames per chunk. The planner adds chunks — up to `--max-parallel-chunks` — to stay under it, and short videos still collapse to fewer. Ignored when `--chunk-size` is set. |
|
||||
| `--variables` | — | JSON object reaching every chunk worker as `window.__hfVariables` |
|
||||
| `--variables-file` | — | Read those from a JSON file |
|
||||
|
||||
@@ -20,7 +20,8 @@ Severities:
|
||||
|
||||
Source: `packages/lint/src/rules/structure.ts`.
|
||||
|
||||
The four codes marked **Warning or error** are warnings when the CLI lints a project, and errors when Studio lints the file it is editing.
|
||||
The five codes marked **Warning or error** are warnings when the CLI lints a project, and errors when Studio
|
||||
lints the file it is editing.
|
||||
|
||||
### `nested_structure_needs_subcomposition`
|
||||
|
||||
@@ -52,6 +53,15 @@ The four codes marked **Warning or error** are warnings when the CLI lints a pro
|
||||
|
||||
**Fix:** Extend the root `data-duration`, or make the clip end at or before it.
|
||||
|
||||
### `nested_clip_never_visible`
|
||||
|
||||
**Warning or error.** A timed clip sits inside another timed element, and its time window never overlaps that
|
||||
element's, so it never appears. A nested clip's `data-start` counts from the composition's start, not from the
|
||||
element around it. Runs in sub-composition files too.
|
||||
|
||||
**Fix:** Give the clip a `data-start` inside its parent's window, in composition time, or move it out of the
|
||||
parent.
|
||||
|
||||
## Composition contract
|
||||
|
||||
Source: `packages/lint/src/rules/composition.ts`.
|
||||
@@ -98,12 +108,6 @@ Source: `packages/lint/src/rules/composition.ts`.
|
||||
|
||||
**Fix:** Keep `data-composition-id` on exactly one element: the composition root. Remove it from metadata or duplicate hosts.
|
||||
|
||||
### `html_dir_attribute_breaks_render`
|
||||
|
||||
**Error.** `<html dir="rtl">` or `<html dir="auto">` renders correctly in preview and snapshot but produces a fully blank or black video from render — a confirmed, silent failure. `dir="ltr"` is not flagged.
|
||||
|
||||
**Fix:** Remove `dir` from `<html>`, keep `lang`, and scope the direction to individual text-containing elements instead — `direction: rtl` in CSS, or `dir="auto"` on the element.
|
||||
|
||||
### `invalid_parent_traversal_in_asset_path`
|
||||
|
||||
**Error.** Asset paths use `../` to traverse above the project root; render and preview clamp or misresolve them.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "hyperframes",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames."
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hyperframes/aws-lambda",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -164,7 +164,7 @@ interface PlanLambdaResultBase {
|
||||
PlanHash: string;
|
||||
ChunkCount: number;
|
||||
TotalFrames: number;
|
||||
Fps: 24 | 30 | 60;
|
||||
Fps: SerializableDistributedRenderConfig["fps"];
|
||||
Width: number;
|
||||
Height: number;
|
||||
Format: DistributedFormat;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* the glue's contract.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -247,6 +247,43 @@ describe("handler dispatch", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("plans against the function's own timeout unless the config pins one", async () => {
|
||||
const seen: Array<number | undefined> = [];
|
||||
for (const pinned of [undefined, 300]) {
|
||||
const tmpRoot = makeTmpRoot();
|
||||
const s3 = new FakeS3Client();
|
||||
s3.objects.set("s3://bucket/project.tar.gz", await makeMinimalProjectTar());
|
||||
await handler(
|
||||
{
|
||||
Action: "plan",
|
||||
PlanProtocol: "v1",
|
||||
ProjectS3Uri: "s3://bucket/project.tar.gz",
|
||||
PlanOutputS3Prefix: "s3://bucket/renders/timeout/",
|
||||
Config: { fps: 30, width: 640, height: 360, format: "mp4", workerTimeoutSeconds: pinned },
|
||||
},
|
||||
{
|
||||
s3: s3 as unknown as import("@aws-sdk/client-s3").S3Client,
|
||||
primitives: {
|
||||
plan: mock(async (_dir: string, config: { workerTimeoutSeconds?: number }) => {
|
||||
seen.push(config.workerTimeoutSeconds);
|
||||
throw new Error("stop after config");
|
||||
}) as unknown as typeof import("@hyperframes/producer/distributed").plan,
|
||||
renderChunk: mock(async () => {
|
||||
throw new Error("unused");
|
||||
}) as unknown as typeof import("@hyperframes/producer/distributed").renderChunk,
|
||||
assemble: mock(async () => {
|
||||
throw new Error("unused");
|
||||
}) as unknown as typeof import("@hyperframes/producer/distributed").assemble,
|
||||
},
|
||||
tmpRoot,
|
||||
skipChromeResolution: true,
|
||||
getRemainingTimeInMillis: () => 899_987,
|
||||
},
|
||||
).catch(() => undefined);
|
||||
}
|
||||
expect(seen).toEqual([900, 300]);
|
||||
});
|
||||
|
||||
it("normalizes producer workflow codes to Step Functions error names", async () => {
|
||||
for (const code of [
|
||||
"PLAN_TOO_LARGE",
|
||||
@@ -257,6 +294,8 @@ describe("handler dispatch", () => {
|
||||
"VIDEO_SOURCE_UNRENDERABLE",
|
||||
"VIDEO_EXTRACTION_FAILED",
|
||||
"INVALID_VIDEO_METADATA",
|
||||
"FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED",
|
||||
"CHUNK_EXCEEDS_WORKER_TIMEOUT",
|
||||
] as const) {
|
||||
const tmpRoot = makeTmpRoot();
|
||||
const s3 = new FakeS3Client();
|
||||
@@ -619,6 +658,10 @@ describe("handler dispatch", () => {
|
||||
skipChromeResolution: true,
|
||||
};
|
||||
|
||||
const logged: string[] = [];
|
||||
const logSpy = spyOn(console, "log").mockImplementation((line: string) => {
|
||||
logged.push(line);
|
||||
});
|
||||
const planned = await handler(
|
||||
{
|
||||
Action: "plan",
|
||||
@@ -627,7 +670,12 @@ describe("handler dispatch", () => {
|
||||
Config: { fps: 30, width: 640, height: 360, format: "mp4" },
|
||||
},
|
||||
deps,
|
||||
);
|
||||
).finally(() => logSpy.mockRestore());
|
||||
const stageLines = logged
|
||||
.filter((line) => line.includes('"plan_stage"'))
|
||||
.map((line) => JSON.parse(line) as { stage?: string; ms?: unknown });
|
||||
expect(stageLines.map((line) => line.stage)).toEqual(["download", "untar"]);
|
||||
expect(stageLines.every((line) => typeof line.ms === "number")).toBe(true);
|
||||
expect(planned).toMatchObject({
|
||||
PlanProtocol: "v2",
|
||||
PlanV2ManifestS3Uri: "s3://bucket/renders/v2/v2/manifest.json",
|
||||
|
||||
@@ -91,6 +91,11 @@ export interface HandlerDeps {
|
||||
tmpRoot?: string;
|
||||
/** Skip Chrome resolution (used by handler dispatch tests that mock renderChunk). */
|
||||
skipChromeResolution?: boolean;
|
||||
/**
|
||||
* The Lambda runtime's `Context` arrives as this second argument and supplies it. Plan
|
||||
* and chunk share one function, so its remaining time at plan start is the chunk limit.
|
||||
*/
|
||||
getRemainingTimeInMillis?: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,7 +167,9 @@ function normalizeTerminalErrorName(error: unknown): void {
|
||||
candidate.code === "NOT_MEDIA_PAYLOAD" ||
|
||||
candidate.code === "VIDEO_SOURCE_UNRENDERABLE" ||
|
||||
candidate.code === "VIDEO_EXTRACTION_FAILED" ||
|
||||
candidate.code === "INVALID_VIDEO_METADATA"
|
||||
candidate.code === "INVALID_VIDEO_METADATA" ||
|
||||
candidate.code === "FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED" ||
|
||||
candidate.code === "CHUNK_EXCEEDS_WORKER_TIMEOUT"
|
||||
) {
|
||||
candidate.name = candidate.code;
|
||||
}
|
||||
@@ -316,6 +323,14 @@ function primeRuntimeEnv(): void {
|
||||
|
||||
// ── Plan ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function planConfig(event: PlanEvent, deps?: HandlerDeps): DistributedRenderConfig {
|
||||
const remainingMs = deps?.getRemainingTimeInMillis?.();
|
||||
if (event.Config.workerTimeoutSeconds !== undefined || remainingMs === undefined) {
|
||||
return { ...event.Config };
|
||||
}
|
||||
return { ...event.Config, workerTimeoutSeconds: Math.ceil(remainingMs / 1000) };
|
||||
}
|
||||
|
||||
// The v1 handler owns one transactional download, plan, archive, upload, and cleanup lifecycle.
|
||||
// fallow-ignore-next-line complexity
|
||||
async function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanLambdaResult> {
|
||||
@@ -323,6 +338,7 @@ async function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanLam
|
||||
return handlePlanV2(event, deps);
|
||||
}
|
||||
const started = Date.now();
|
||||
const config = planConfig(event, deps);
|
||||
const s3 = deps?.s3 ?? getS3Client();
|
||||
const primitive = deps?.primitives?.plan ?? plan;
|
||||
|
||||
@@ -349,9 +365,6 @@ async function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanLam
|
||||
await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);
|
||||
await untarDirectory(projectArchive, projectDir);
|
||||
|
||||
const config: DistributedRenderConfig = {
|
||||
...event.Config,
|
||||
};
|
||||
const result: PlanResult = await primitive(projectDir, config, planDir);
|
||||
|
||||
// Upload the planDir as a single tarball. Step Functions cannot pass
|
||||
@@ -403,6 +416,7 @@ async function handlePlanV2(
|
||||
deps?: HandlerDeps,
|
||||
): Promise<Extract<PlanLambdaResult, { PlanProtocol: "v2" }>> {
|
||||
const started = Date.now();
|
||||
const config = planConfig(event, deps);
|
||||
const s3 = deps?.s3 ?? getS3Client();
|
||||
const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher;
|
||||
if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {
|
||||
@@ -413,14 +427,18 @@ async function handlePlanV2(
|
||||
const projectArchive = join(work, "project.tar.gz");
|
||||
const projectDir = join(work, "project");
|
||||
try {
|
||||
let stageStarted = Date.now();
|
||||
await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);
|
||||
logEvent({ event: "plan_stage", stage: "download", ms: Date.now() - stageStarted });
|
||||
stageStarted = Date.now();
|
||||
await untarDirectory(projectArchive, projectDir);
|
||||
logEvent({ event: "plan_stage", stage: "untar", ms: Date.now() - stageStarted });
|
||||
const publisher = new S3PlanV2ArtifactPublisher({
|
||||
s3,
|
||||
planOutputS3Prefix: event.PlanOutputS3Prefix,
|
||||
temporaryRoot: work,
|
||||
});
|
||||
const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, {
|
||||
const manifest: PlanV2Manifest = await primitive(projectDir, config, publisher, {
|
||||
stagingParentDir: work,
|
||||
});
|
||||
|
||||
@@ -663,7 +681,9 @@ async function handleAssembleV2(
|
||||
// `downloadAndMaterializePlanV2` materializes atomically. Audio is
|
||||
// assembler-only and lives at the familiar v1-compatible location.
|
||||
const audioPath = resolvePlanAudioPath(planDir);
|
||||
const chunksStarted = Date.now();
|
||||
const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format);
|
||||
const chunksMs = Date.now() - chunksStarted;
|
||||
const finalOutput =
|
||||
event.Format === "png-sequence"
|
||||
? join(work, "output-frames")
|
||||
@@ -671,6 +691,7 @@ async function handleAssembleV2(
|
||||
const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, {
|
||||
cfr: event.Cfr === true,
|
||||
});
|
||||
const uploadStarted = Date.now();
|
||||
if (event.Format === "png-sequence") {
|
||||
const tarball = `${finalOutput}.tar.gz`;
|
||||
await tarDirectory(finalOutput, tarball);
|
||||
@@ -678,6 +699,13 @@ async function handleAssembleV2(
|
||||
} else {
|
||||
await uploadFileToS3(s3, finalOutput, event.OutputS3Uri);
|
||||
}
|
||||
logEvent({
|
||||
event: "assemble_stages",
|
||||
planMs: chunksStarted - started,
|
||||
chunksMs,
|
||||
assembleMs: result.durationMs,
|
||||
uploadMs: Date.now() - uploadStarted,
|
||||
});
|
||||
return {
|
||||
Action: "assemble",
|
||||
OutputS3Uri: event.OutputS3Uri,
|
||||
|
||||
@@ -19,12 +19,14 @@ interface PutOperation {
|
||||
class FakeS3 {
|
||||
readonly objects = new Map<string, StoredObject>();
|
||||
readonly puts: PutOperation[] = [];
|
||||
sends = 0;
|
||||
|
||||
asClient(): import("@aws-sdk/client-s3").S3Client {
|
||||
return this as unknown as import("@aws-sdk/client-s3").S3Client;
|
||||
}
|
||||
|
||||
async send(command: unknown): Promise<unknown> {
|
||||
this.sends += 1;
|
||||
// AWS command inputs are the runtime boundary exercised by this fake.
|
||||
const value = command as unknown as {
|
||||
readonly constructor: { readonly name: string };
|
||||
@@ -139,6 +141,22 @@ describe("S3PlanV2ArtifactPublisher", () => {
|
||||
expect(s3.objects.get(manifestUri)?.bytes.toString("utf8")).toBe(manifest);
|
||||
});
|
||||
|
||||
it("sends nothing for a digest it already published", async () => {
|
||||
const source = makeSource("hello");
|
||||
const s3 = new FakeS3();
|
||||
const publisher = new S3PlanV2ArtifactPublisher({
|
||||
s3: s3.asClient(),
|
||||
planOutputS3Prefix: "s3://bucket/render",
|
||||
temporaryRoot: source.root,
|
||||
});
|
||||
const blob = { sourcePath: source.path, sha256: source.digest, sizeBytes: source.sizeBytes };
|
||||
|
||||
await publisher.putBlob(blob);
|
||||
const sendsAfterFirst = s3.sends;
|
||||
await publisher.putBlob(blob);
|
||||
expect(s3.sends).toBe(sendsAfterFirst);
|
||||
});
|
||||
|
||||
it("refuses to expose a manifest that references an unpublished digest", async () => {
|
||||
const source = makeSource("hello");
|
||||
const s3 = new FakeS3();
|
||||
|
||||
@@ -83,6 +83,7 @@ export class S3PlanV2ArtifactPublisher implements PlanV2ArtifactPublisher {
|
||||
async putBlob(blob: Readonly<PlanV2PublishBlob>): Promise<void> {
|
||||
this.#assertOpen("publish a blob");
|
||||
const digest = assertSha256(blob.sha256, "S3 published blob sha256");
|
||||
if (this.#publishedDigests.has(digest)) return;
|
||||
const sourceSize = statSync(blob.sourcePath).size;
|
||||
if (sourceSize !== blob.sizeBytes) {
|
||||
throw new PlanV2IntegrityError(
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -116,6 +117,19 @@ describe("content-addressed v2 artifacts", () => {
|
||||
expect(s3.putCount).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves verifying the local bytes to the S3 checksum instead of hashing them again", async () => {
|
||||
const source = join(scratchRoot, "artifact-changed.bin");
|
||||
writeFileSync(source, "bytes that changed");
|
||||
const digest = createHash("sha256").update("bytes as hashed").digest("hex");
|
||||
const uri = `s3://bucket/v2/artifacts/sha256/${digest.slice(0, 2)}/${digest}`;
|
||||
const s3 = new ContentAddressedFakeS3();
|
||||
|
||||
await expect(
|
||||
uploadContentAddressedFileToS3(s3.asClient(), source, uri, digest),
|
||||
).rejects.toMatchObject({ name: "BadDigest" });
|
||||
expect(s3.objects.has(uri)).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses to overwrite an immutable key with conflicting metadata", async () => {
|
||||
const source = join(scratchRoot, "artifact-conflict.bin");
|
||||
writeFileSync(source, "expected bytes");
|
||||
@@ -199,6 +213,7 @@ class ContentAddressedFakeS3 {
|
||||
Key: string;
|
||||
Body?: NodeJS.ReadableStream;
|
||||
Metadata?: Record<string, string>;
|
||||
ChecksumSHA256?: string;
|
||||
};
|
||||
};
|
||||
const uri = `s3://${value.input.Bucket}/${value.input.Key}`;
|
||||
@@ -238,6 +253,12 @@ class ContentAddressedFakeS3 {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of value.input.Body ?? []) chunks.push(Buffer.from(chunk));
|
||||
const bytes = Buffer.concat(chunks);
|
||||
const checksum = createHash("sha256").update(bytes).digest("base64");
|
||||
if (value.input.ChecksumSHA256 !== undefined && value.input.ChecksumSHA256 !== checksum) {
|
||||
const error = new Error("checksum mismatch");
|
||||
error.name = "BadDigest";
|
||||
throw error;
|
||||
}
|
||||
this.objects.set(uri, {
|
||||
bytes,
|
||||
sha256: value.input.Metadata?.sha256 ?? "",
|
||||
|
||||
@@ -131,11 +131,9 @@ export async function uploadFileToS3(
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload one content-addressed plan-v2 artifact exactly once.
|
||||
*
|
||||
* Existing objects are reused only when their immutable digest metadata and
|
||||
* byte length agree. A conflicting object is never overwritten: doing so
|
||||
* could change a plan already being consumed by another chunk invocation.
|
||||
* Upload one content-addressed plan-v2 artifact exactly once; S3 verifies the bytes against
|
||||
* `ChecksumSHA256`. An existing object is reused only when its digest metadata and length agree,
|
||||
* and a conflicting one is never overwritten, since a chunk may already be reading that plan.
|
||||
*/
|
||||
export async function uploadContentAddressedFileToS3(
|
||||
client: S3Client,
|
||||
@@ -148,15 +146,6 @@ export async function uploadContentAddressedFileToS3(
|
||||
if (!existsSync(localPath)) {
|
||||
throw new Error(`[s3Transport] upload source missing: ${localPath}`);
|
||||
}
|
||||
const actualSha256 = await sha256File(localPath);
|
||||
if (actualSha256 !== expectedSha256) {
|
||||
const error = new Error(
|
||||
`[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`,
|
||||
);
|
||||
error.name = "PLAN_ARTIFACT_DIGEST_MISMATCH";
|
||||
throw error;
|
||||
}
|
||||
|
||||
const { bucket, key } = parseS3Uri(uri);
|
||||
const size = statSync(localPath).size;
|
||||
const existing = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256);
|
||||
|
||||
@@ -173,7 +173,7 @@ describe("renderToLambda", () => {
|
||||
projectDir,
|
||||
bucketName: "test-bucket",
|
||||
stateMachineArn: "arn:aws:states:us-east-1:1234:stateMachine:hf",
|
||||
config: { ...baseConfig, fps: 25 as 24 | 30 | 60 },
|
||||
config: { ...baseConfig, fps: 50 as never },
|
||||
sfn: asSFNClient(sfn),
|
||||
s3: asS3Client(s3),
|
||||
});
|
||||
|
||||
@@ -20,6 +20,11 @@ describe("validateDistributedRenderConfig", () => {
|
||||
expect(validateDistributedRenderConfig(VALID)).toBe(VALID);
|
||||
});
|
||||
|
||||
it("accepts 25 fps", () => {
|
||||
const cfg: SerializableDistributedRenderConfig = { ...VALID, fps: 25 };
|
||||
expect(validateDistributedRenderConfig(cfg)).toBe(cfg);
|
||||
});
|
||||
|
||||
it("accepts optional fields when valid", () => {
|
||||
const cfg: SerializableDistributedRenderConfig = {
|
||||
...VALID,
|
||||
@@ -39,7 +44,7 @@ describe("validateDistributedRenderConfig", () => {
|
||||
["null config", null as unknown as SerializableDistributedRenderConfig, "config"],
|
||||
[
|
||||
"wrong fps",
|
||||
{ ...VALID, fps: 25 as 24 | 30 | 60 } satisfies SerializableDistributedRenderConfig,
|
||||
{ ...VALID, fps: 50 as never } satisfies SerializableDistributedRenderConfig,
|
||||
"config.fps",
|
||||
],
|
||||
[
|
||||
@@ -116,6 +121,16 @@ describe("validateDistributedRenderConfig", () => {
|
||||
{ ...VALID, maxParallelChunks: 0 } satisfies SerializableDistributedRenderConfig,
|
||||
"config.maxParallelChunks",
|
||||
],
|
||||
[
|
||||
"workerTimeoutSeconds 0",
|
||||
{ ...VALID, workerTimeoutSeconds: 0 } satisfies SerializableDistributedRenderConfig,
|
||||
"config.workerTimeoutSeconds",
|
||||
],
|
||||
[
|
||||
"fractional workerConcurrency",
|
||||
{ ...VALID, workerConcurrency: 1.5 } satisfies SerializableDistributedRenderConfig,
|
||||
"config.workerConcurrency",
|
||||
],
|
||||
[
|
||||
"unknown runtimeCap",
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hyperframes/cli",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"description": "HyperFrames CLI — create, preview, and render HTML video compositions",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
||||
@@ -20,6 +20,7 @@ function row(
|
||||
host: null,
|
||||
hostRow: null,
|
||||
children: [],
|
||||
parentRow: null,
|
||||
trackIndex: 0,
|
||||
src: "audio/a.wav",
|
||||
sourceFile: null,
|
||||
|
||||
@@ -7,6 +7,13 @@ import {
|
||||
import { normalizeErrorMessage } from "../utils/errorMessage.js";
|
||||
import { requestCliExit } from "../utils/commandResult.js";
|
||||
import { processIsAlive } from "../utils/processTree.js";
|
||||
import {
|
||||
inAgentSandbox,
|
||||
isOneProcessOverPipe,
|
||||
machServiceDenied,
|
||||
oneProcessOverPipe,
|
||||
sandboxDeniedRemediation,
|
||||
} from "./sandboxDenied.js";
|
||||
|
||||
export class BrowserCleanupError extends AggregateError {}
|
||||
|
||||
@@ -55,9 +62,7 @@ export async function resolveManagedGpuMode(
|
||||
context.signal?.throwIfAborted();
|
||||
const browser = await launchManagedBrowser(puppeteer, {
|
||||
...options,
|
||||
...(context.noListen
|
||||
? { pipe: true, args: [...(options.args ?? []), "--single-process"] }
|
||||
: {}),
|
||||
...(context.noListen ? oneProcessOverPipe(options) : {}),
|
||||
signal: context.signal,
|
||||
});
|
||||
try {
|
||||
@@ -75,6 +80,29 @@ export async function resolveManagedGpuMode(
|
||||
export async function launchManagedBrowser(
|
||||
puppeteer: PuppeteerNode,
|
||||
options: LaunchOptions,
|
||||
): Promise<Browser> {
|
||||
const sandboxed = isOneProcessOverPipe(options) || inAgentSandbox();
|
||||
try {
|
||||
return await launchOwnedBrowser(puppeteer, sandboxed ? oneProcessOverPipe(options) : options);
|
||||
} catch (error) {
|
||||
const unnamedSeatbelt = !sandboxed && machServiceDenied(normalizeErrorMessage(error));
|
||||
if (!unnamedSeatbelt) throw withRemediation(error);
|
||||
return launchOwnedBrowser(puppeteer, oneProcessOverPipe(options)).catch(
|
||||
(retryError: unknown) => {
|
||||
throw withRemediation(retryError);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function withRemediation(error: unknown): unknown {
|
||||
const remediation = sandboxDeniedRemediation(normalizeErrorMessage(error));
|
||||
return remediation ? new Error(remediation, { cause: error }) : error;
|
||||
}
|
||||
|
||||
async function launchOwnedBrowser(
|
||||
puppeteer: PuppeteerNode,
|
||||
options: LaunchOptions,
|
||||
): Promise<Browser> {
|
||||
if (shutdown) throw new Error("The CLI is stopping; no browser can start.");
|
||||
ownSignals();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { Browser, LaunchOptions, PuppeteerNode } from "puppeteer-core";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { launchManagedBrowser } from "./launch.js";
|
||||
|
||||
const SEATBELT_LAUNCH_FAILURE = [
|
||||
"Failed to launch the browser process: Code: null",
|
||||
"",
|
||||
"stderr:",
|
||||
"[1016/170315.389548:FATAL:base/apple/mach_port_rendezvous_mac.cc:159] Check failed: kr == KERN_SUCCESS. bootstrap_check_in org.chromium.Chromium.MachPortRendezvousServer.26166: Permission denied (1100)",
|
||||
].join("\n");
|
||||
|
||||
const failingPuppeteer = (message: string) =>
|
||||
({ launch: async (_: LaunchOptions) => Promise.reject(new Error(message)) }) as PuppeteerNode;
|
||||
|
||||
describe("a browser launch a sandbox refuses", () => {
|
||||
it("tells the caller to rerun with escalation instead of showing Chrome's crash", async () => {
|
||||
await expect(
|
||||
launchManagedBrowser(failingPuppeteer(SEATBELT_LAUNCH_FAILURE), {}),
|
||||
).rejects.toMatchObject({
|
||||
message:
|
||||
"The browser can't start inside this sandbox: macOS refused Chrome's mach service (bootstrap_check_in: Permission denied).\nRerun this command with escalation, outside the sandbox.",
|
||||
cause: { message: SEATBELT_LAUNCH_FAILURE },
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves any other launch failure as it was", async () => {
|
||||
const other = "Failed to launch the browser process: Code: 1";
|
||||
await expect(launchManagedBrowser(failingPuppeteer(other), {})).rejects.toThrow(other);
|
||||
});
|
||||
});
|
||||
|
||||
const fakeBrowser = () => ({ process: () => new EventEmitter() }) as unknown as Browser;
|
||||
|
||||
function recordingPuppeteer(failures: string[]) {
|
||||
const launches: LaunchOptions[] = [];
|
||||
const puppeteer = {
|
||||
launch: async (options: LaunchOptions) => {
|
||||
launches.push(options);
|
||||
const failure = failures.shift();
|
||||
if (failure) throw new Error(failure);
|
||||
return fakeBrowser();
|
||||
},
|
||||
} as unknown as PuppeteerNode;
|
||||
return { puppeteer, launches };
|
||||
}
|
||||
|
||||
describe("a browser inside an agent's macOS seatbelt", () => {
|
||||
const platform = process.platform;
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
Object.defineProperty(process, "platform", { value: platform });
|
||||
});
|
||||
|
||||
it("starts as one process over a pipe when Codex names its seatbelt", async () => {
|
||||
vi.stubEnv("CODEX_SANDBOX", "seatbelt");
|
||||
Object.defineProperty(process, "platform", { value: "darwin" });
|
||||
const { puppeteer, launches } = recordingPuppeteer([]);
|
||||
await launchManagedBrowser(puppeteer, { args: ["--headless"] });
|
||||
expect(launches).toHaveLength(1);
|
||||
expect(launches[0]).toMatchObject({ pipe: true, args: ["--headless", "--single-process"] });
|
||||
});
|
||||
|
||||
it("relaunches as one process over a pipe when an unnamed sandbox refuses the mach service", async () => {
|
||||
vi.stubEnv("CODEX_SANDBOX", "");
|
||||
const { puppeteer, launches } = recordingPuppeteer([SEATBELT_LAUNCH_FAILURE]);
|
||||
await expect(launchManagedBrowser(puppeteer, { args: ["--headless"] })).resolves.toBeDefined();
|
||||
expect(launches.map((options) => options.pipe ?? false)).toEqual([false, true]);
|
||||
expect(launches[1]!.args).toEqual(["--headless", "--single-process"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { LaunchOptions } from "puppeteer-core";
|
||||
|
||||
const MACH_SERVICE_DENIED = /bootstrap_check_in\b[^\n]*Permission denied/;
|
||||
const SINGLE_PROCESS = "--single-process";
|
||||
|
||||
export function machServiceDenied(errorMessage: string): boolean {
|
||||
return MACH_SERVICE_DENIED.test(errorMessage);
|
||||
}
|
||||
|
||||
/** Codex runs agent commands in a macOS seatbelt, which names itself in the environment. */
|
||||
export function inAgentSandbox(env = process.env, platform = process.platform): boolean {
|
||||
return platform === "darwin" && env.CODEX_SANDBOX === "seatbelt";
|
||||
}
|
||||
|
||||
/** The one launch a seatbelt allows: no child process can register its mach port and nothing may listen. */
|
||||
export function oneProcessOverPipe(options: LaunchOptions): LaunchOptions {
|
||||
const args = options.args ?? [];
|
||||
return {
|
||||
...options,
|
||||
pipe: true,
|
||||
args: args.includes(SINGLE_PROCESS) ? args : [...args, SINGLE_PROCESS],
|
||||
};
|
||||
}
|
||||
|
||||
export function isOneProcessOverPipe(options: LaunchOptions): boolean {
|
||||
return options.pipe === true && (options.args ?? []).includes(SINGLE_PROCESS);
|
||||
}
|
||||
|
||||
/** A process sandbox (an agent's macOS seatbelt) refused Chrome its mach service, so no browser starts here. */
|
||||
export function sandboxDeniedRemediation(errorMessage: string): string | undefined {
|
||||
if (!machServiceDenied(errorMessage)) return undefined;
|
||||
return [
|
||||
"The browser can't start inside this sandbox: macOS refused Chrome's mach service (bootstrap_check_in: Permission denied).",
|
||||
"Rerun this command with escalation, outside the sandbox.",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -27,7 +27,7 @@ function fakeSeekPage() {
|
||||
const evaluate = vi.fn(
|
||||
async (
|
||||
_pageFunction: Parameters<CompositionSeekPage["evaluate"]>[0],
|
||||
_value?: number,
|
||||
_value?: Parameters<CompositionSeekPage["evaluate"]>[1],
|
||||
_fallbackToBridgeAndTimelines?: boolean,
|
||||
): Promise<unknown> => undefined,
|
||||
);
|
||||
@@ -108,7 +108,7 @@ describe("seekCompositionTimeline", () => {
|
||||
expect(waitForFunction).not.toHaveBeenCalled();
|
||||
expect(evaluate).toHaveBeenCalledTimes(4);
|
||||
expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false, false);
|
||||
expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function));
|
||||
expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true });
|
||||
expect(evaluate.mock.calls[2]?.[0]).toContain("window.setTimeout(finish, 100)");
|
||||
// Post-seek font settle: a seek can reveal glyphs whose unicode-range
|
||||
// subsets only start loading after the next layout (CJK snapshot reports).
|
||||
@@ -230,7 +230,7 @@ describe("seekCompositionTimeline", () => {
|
||||
|
||||
expect(evaluate).toHaveBeenCalledTimes(4);
|
||||
expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 4, true, false);
|
||||
expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function));
|
||||
expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true });
|
||||
expect(evaluate).toHaveBeenNthCalledWith(3, expect.any(Function));
|
||||
expect(evaluate).toHaveBeenNthCalledWith(4, expect.any(Function), 500);
|
||||
});
|
||||
@@ -471,6 +471,26 @@ describe("installPageFunctionGuard", () => {
|
||||
});
|
||||
|
||||
describe("DENSE_GEOMETRY_SEEK_OPTIONS", () => {
|
||||
// A 79 s project of 1080p H.264 clips: each of the 600 dense seeks waited ~185 ms for a video frame it never reads,
|
||||
// so `check` ran past its deadline. Frame sources and hf-seek work can move the DOM, so those still hold it.
|
||||
it("skips only the seek barrier's video-frame holds, while the audit seek waits for all", async () => {
|
||||
const barrierCalls = async (options: Parameters<typeof seekCompositionTimeline>[2]) => {
|
||||
const { page, evaluate } = fakeSeekPage();
|
||||
const barrier = vi.fn(async (_options?: { videoFrames?: boolean }) => {});
|
||||
vi.stubGlobal("window", { __hfWaitForSeekCompletion: barrier });
|
||||
evaluate.mockImplementation(async (pageFunction, value) =>
|
||||
typeof pageFunction === "function" && typeof value === "object"
|
||||
? Reflect.apply(pageFunction, undefined, [value])
|
||||
: undefined,
|
||||
);
|
||||
await seekCompositionTimeline(page, 3, options);
|
||||
return barrier.mock.calls;
|
||||
};
|
||||
|
||||
expect(await barrierCalls(DENSE_GEOMETRY_SEEK_OPTIONS)).toEqual([[{ videoFrames: false }]]);
|
||||
expect(await barrierCalls(AUDIT_SEEK_OPTIONS)).toEqual([[{ videoFrames: true }]]);
|
||||
});
|
||||
|
||||
it("is genuinely geometry-only — no post-seek settle waits at the 600-sample cap", () => {
|
||||
// Dense pass must not inherit AUDIT's post-seek waits — geometry is valid synchronously after setTime, and waits multiply by sample count.
|
||||
expect(DENSE_GEOMETRY_SEEK_OPTIONS.animationFrameSettle).toBe("none");
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
launchManagedBrowser,
|
||||
resolveManagedGpuMode,
|
||||
} from "../browser/launch.js";
|
||||
import { oneProcessOverPipe } from "../browser/sandboxDenied.js";
|
||||
import { spawn } from "node:child_process";
|
||||
import type { Browser, Page } from "puppeteer-core";
|
||||
import type { InProcessRequest, InProcessResponse } from "../utils/staticProjectServer.js";
|
||||
@@ -40,6 +41,7 @@ export const DENSE_GEOMETRY_SEEK_OPTIONS = {
|
||||
animationFrameSettle: "none",
|
||||
waitForFontsMs: 0,
|
||||
settleMs: 0,
|
||||
waitForVideoFrames: false,
|
||||
} as const;
|
||||
|
||||
export interface SeekCompositionTimelineOptions {
|
||||
@@ -49,18 +51,22 @@ export interface SeekCompositionTimelineOptions {
|
||||
animationFrameSettle?: "race" | "double" | "none";
|
||||
waitForFontsMs?: number;
|
||||
settleMs?: number;
|
||||
waitForVideoFrames?: boolean;
|
||||
}
|
||||
|
||||
type SeekBarrierOptions = { videoFrames: boolean };
|
||||
|
||||
type CompositionPageFunction =
|
||||
| string
|
||||
| (() => unknown)
|
||||
| ((value: number) => unknown)
|
||||
| ((barrier: SeekBarrierOptions) => unknown)
|
||||
| ((value: number, fallbackToBridgeAndTimelines: boolean, exactTime: boolean) => unknown);
|
||||
|
||||
export interface CompositionEvaluationPage {
|
||||
evaluate(
|
||||
pageFunction: CompositionPageFunction,
|
||||
value?: number,
|
||||
value?: number | SeekBarrierOptions,
|
||||
fallbackToBridgeAndTimelines?: boolean,
|
||||
exactTime?: boolean,
|
||||
): Promise<unknown>;
|
||||
@@ -225,7 +231,7 @@ export async function openSettledCompositionPage(
|
||||
headless: true,
|
||||
signal: options.signal,
|
||||
executablePath,
|
||||
...(answer ? { pipe: true, args: [...args, "--single-process"] } : { args }),
|
||||
...(answer ? oneProcessOverPipe({ args }) : { args }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -341,12 +347,15 @@ export async function seekCompositionTimeline(
|
||||
options.exactTime === true,
|
||||
);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const waitForCompletion = Reflect.get(window, "__hfWaitForSeekCompletion");
|
||||
if (typeof waitForCompletion === "function") {
|
||||
await Reflect.apply(waitForCompletion, window, []);
|
||||
}
|
||||
});
|
||||
await page.evaluate(
|
||||
async (barrier: SeekBarrierOptions) => {
|
||||
const waitForCompletion = Reflect.get(window, "__hfWaitForSeekCompletion");
|
||||
if (typeof waitForCompletion === "function") {
|
||||
await Reflect.apply(waitForCompletion, window, [barrier]);
|
||||
}
|
||||
},
|
||||
{ videoFrames: options.waitForVideoFrames !== false },
|
||||
);
|
||||
|
||||
const animationFrameSettle = options.animationFrameSettle ?? "race";
|
||||
if (animationFrameSettle === "race") {
|
||||
|
||||
@@ -163,6 +163,7 @@ function fakeDriver(overrides: Partial<CheckAuditDriver> = {}): CheckAuditDriver
|
||||
getDuration: vi.fn(async () => 9),
|
||||
hasNoTimelineDeclaration: vi.fn(async () => false),
|
||||
getTransitionBoundaries: vi.fn(async () => []),
|
||||
getClipEdges: vi.fn(async () => []),
|
||||
getCanvas: vi.fn(async () => ({ width: 1920, height: 1080 })),
|
||||
findAmbiguousSelectors: vi.fn(async (_selectors: string[]) => []),
|
||||
seek: vi.fn(async (_time: number) => undefined),
|
||||
@@ -2312,6 +2313,58 @@ describe("dense motion-overlap re-sampling", () => {
|
||||
expect(driver.collectOverlap).toHaveBeenCalled();
|
||||
expect(report.layout.findings.some((f) => f.code === "content_overlap")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a long film's dense pass to a fixed number of seeks", async () => {
|
||||
const clipEdges = Array.from({ length: 433 }, (_, i) => [i * 1.2, i * 1.2 + 1.1]).flat();
|
||||
const driver = fakeDriver({
|
||||
getDuration: vi.fn(async () => 540),
|
||||
getClipEdges: async () => clipEdges,
|
||||
});
|
||||
await runScenario(driver);
|
||||
expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(240);
|
||||
});
|
||||
|
||||
it("still promotes an overlap held on a long film", async () => {
|
||||
const held = (time: number): boolean => time >= 200 && time <= 260;
|
||||
const driver = fakeDriver({
|
||||
getDuration: vi.fn(async () => 540),
|
||||
collectLayout: vi.fn(async (_time: number) => []),
|
||||
collectOverlap: vi.fn(async (time: number) =>
|
||||
held(time) ? [layoutIssue("warning", { time, code: "content_overlap" })] : [],
|
||||
),
|
||||
});
|
||||
const { report } = await runScenario(driver);
|
||||
expect(report.layout.findings).toContainEqual(
|
||||
expect.objectContaining({ code: "content_overlap", severity: "error" }),
|
||||
);
|
||||
expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(240);
|
||||
});
|
||||
|
||||
it("spends one hold probe on an overlap that stays the whole film", async () => {
|
||||
const driver = fakeDriver({
|
||||
getDuration: vi.fn(async () => 540),
|
||||
collectLayout: vi.fn(async (_time: number) => []),
|
||||
collectOverlap: vi.fn(async (time: number) => [
|
||||
layoutIssue("warning", { time, code: "content_overlap" }),
|
||||
]),
|
||||
});
|
||||
await runScenario(driver);
|
||||
expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(181);
|
||||
});
|
||||
|
||||
it("samples a short clip the uniform grid steps over", async () => {
|
||||
const inShortClip = (time: number): boolean => time > 101 && time < 101.8;
|
||||
const driver = fakeDriver({
|
||||
getDuration: vi.fn(async () => 540),
|
||||
getClipEdges: async () => [101, 101.8],
|
||||
collectLayout: vi.fn(async (_time: number) => []),
|
||||
collectOverlap: vi.fn(async (time: number) =>
|
||||
inShortClip(time) ? [layoutIssue("warning", { time, code: "content_overlap" })] : [],
|
||||
),
|
||||
});
|
||||
const { report } = await runScenario(driver);
|
||||
expect(report.layout.findings.some((f) => f.code === "content_overlap")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scoped check", () => {
|
||||
|
||||
@@ -55,11 +55,12 @@ export interface CheckCommandDependencies {
|
||||
const DEFAULT_COMMAND_DEPENDENCIES: CheckCommandDependencies = {
|
||||
resolveProject,
|
||||
async runPipeline(project, options) {
|
||||
const capture = await captureArtifactRevision(project.dir).catch(warnNotRecorded);
|
||||
const capturing = captureArtifactRevision(project.dir).catch(warnNotRecorded);
|
||||
const report = await runCheckPipeline(project, options);
|
||||
const images = (files: readonly string[]) => files.map((file) => resolve(project.dir, file));
|
||||
reportArtifacts("check", "frame", images(report.snapshots.files));
|
||||
reportArtifacts("check", "finding", images(report.snapshots.findingFiles));
|
||||
const capture = await capturing;
|
||||
if (!capture) return report;
|
||||
try {
|
||||
return { ...report, saved: await saveCheckReport(project, options, report, capture) };
|
||||
|
||||
@@ -71,7 +71,7 @@ it("only warns when the report cannot be recorded; the exit status is the check'
|
||||
}
|
||||
});
|
||||
|
||||
it("still reports the check when another process holds history", async () => {
|
||||
it("still reports the check when another process holds history, without waiting for it", async () => {
|
||||
const project = mkdtempSync(join(tmpdir(), "hf-check-history-held-"));
|
||||
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
@@ -80,7 +80,8 @@ it("still reports the check when another process holds history", async () => {
|
||||
"<html><body>Missing composition metadata</body></html>",
|
||||
);
|
||||
const previousWait = historyDeps.ownerWaitMs;
|
||||
historyDeps.ownerWaitMs = 0;
|
||||
// A wait for the holder outlasts the test: recording the report must not take it.
|
||||
historyDeps.ownerWaitMs = 60_000;
|
||||
const held = await openProjectHistory({
|
||||
projectDir: project,
|
||||
historyRoot: historyDeps.historyRoot,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCommand } from "citty";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import check from "./check.js";
|
||||
import { consumeCommandResult } from "../utils/commandResult.js";
|
||||
import type { CheckReport } from "../utils/checkPipeline.js";
|
||||
|
||||
// The history capture answers only once the check has started: a check that waits for it never runs.
|
||||
const gate = vi.hoisted(() => {
|
||||
let open = () => {};
|
||||
const opened = new Promise<void>((resolve) => (open = resolve));
|
||||
return { opened, open: () => open() };
|
||||
});
|
||||
|
||||
vi.mock("../utils/artifactCapture.js", () => ({
|
||||
captureArtifactRevision: async () => {
|
||||
await gate.opened;
|
||||
return undefined;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils/checkPipeline.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../utils/checkPipeline.js")>();
|
||||
return {
|
||||
...actual,
|
||||
runCheckPipeline: (...args: Parameters<typeof actual.runCheckPipeline>) => {
|
||||
gate.open();
|
||||
return actual.runCheckPipeline(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
it("runs the check while its history capture is still under way", async () => {
|
||||
const project = mkdtempSync(join(tmpdir(), "hf-check-capture-"));
|
||||
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
writeFileSync(
|
||||
join(project, "index.html"),
|
||||
"<html><body>Missing composition metadata</body></html>",
|
||||
);
|
||||
try {
|
||||
await runCommand(check, { rawArgs: [project, "--json"] });
|
||||
const output = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as CheckReport;
|
||||
expect(output.browserSkipped).toBe(true);
|
||||
expect(output).not.toHaveProperty("saved");
|
||||
} finally {
|
||||
log.mockRestore();
|
||||
consumeCommandResult();
|
||||
rmSync(project, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -29,7 +29,9 @@ import {
|
||||
validateVariablesAgainstProject,
|
||||
} from "../utils/variables.js";
|
||||
import { normalizeErrorMessage } from "../utils/errorMessage.js";
|
||||
import { readAllowedCompositionFpsFromDir } from "../utils/compositionFps.js";
|
||||
import { defaultCloudFps } from "../utils/compositionFps.js";
|
||||
import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core";
|
||||
import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js";
|
||||
|
||||
export const examples: Example[] = [
|
||||
["Deploy the Cloud Run render stack", "hyperframes cloudrun deploy --project my-gcp-project"],
|
||||
@@ -100,20 +102,11 @@ function loadCloudRunAdapter(): Promise<CloudRunAdapter> {
|
||||
}
|
||||
|
||||
export function isMissingCloudRunAdapterError(error: unknown): boolean {
|
||||
return (
|
||||
(error as NodeJS.ErrnoException)?.code === "ERR_MODULE_NOT_FOUND" &&
|
||||
normalizeErrorMessage(error).includes("@hyperframes/gcp-cloud-run")
|
||||
);
|
||||
return isMissingPackageError(error, "@hyperframes/gcp-cloud-run");
|
||||
}
|
||||
|
||||
export function missingCloudRunAdapterMessage(subcommand: string): string {
|
||||
return (
|
||||
`${c.error("@hyperframes/gcp-cloud-run is not installed.")} The ${c.accent(`hyperframes cloudrun ${subcommand}`)} command needs it at runtime.\n` +
|
||||
`Install it alongside the CLI:\n` +
|
||||
` ${c.accent("npm install -g @hyperframes/gcp-cloud-run")}\n` +
|
||||
`Or, for an opt-in project setup:\n` +
|
||||
` ${c.accent("npm install @hyperframes/gcp-cloud-run")}`
|
||||
);
|
||||
return missingPackageMessage("@hyperframes/gcp-cloud-run", `hyperframes cloudrun ${subcommand}`);
|
||||
}
|
||||
|
||||
export default defineCommand({
|
||||
@@ -167,7 +160,7 @@ export default defineCommand({
|
||||
"site-id": { type: "string", description: "Explicit site id (overrides content hash)" },
|
||||
width: { type: "string", description: "Render width in pixels" },
|
||||
height: { type: "string", description: "Render height in pixels" },
|
||||
fps: { type: "string", description: "Render fps (24 | 30 | 60)" },
|
||||
fps: { type: "string", description: `Render fps (${DISTRIBUTED_FPS.join(" | ")})` },
|
||||
format: { type: "string", description: "mp4 | mov | png-sequence | webm (default: mp4)" },
|
||||
codec: { type: "string", description: "h264 | h265 (mp4 only)" },
|
||||
quality: { type: "string", description: "draft | standard | high" },
|
||||
@@ -529,11 +522,12 @@ function resolveCloudRunFps(
|
||||
args: Record<string, unknown>,
|
||||
projectDir: string,
|
||||
command: "render" | "render-batch",
|
||||
): 24 | 30 | 60 {
|
||||
const fps =
|
||||
parseIntFlag(args.fps) ?? readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ?? 30;
|
||||
if (fps === 24 || fps === 30 || fps === 60) return fps;
|
||||
console.error(`[cloudrun ${command}] --fps must be 24, 30, or 60; got ${fps}.`);
|
||||
): DistributedFps {
|
||||
const fps = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir);
|
||||
if (isDistributedFps(fps)) return fps;
|
||||
console.error(
|
||||
`[cloudrun ${command}] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fps}.`,
|
||||
);
|
||||
failCommand();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,11 +11,12 @@ import { failCommand } from "../utils/commandResult.js";
|
||||
|
||||
import { defineCommand } from "citty";
|
||||
import type { DistributedFormat } from "@hyperframes/aws-lambda/sdk";
|
||||
import { type CanvasResolution } from "@hyperframes/core";
|
||||
import { type CanvasResolution, DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
|
||||
import { parseOutputResolutionFlag } from "../utils/parseOutputResolution.js";
|
||||
import type { Example } from "./_examples.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { readAllowedCompositionFpsFromDir } from "../utils/compositionFps.js";
|
||||
import { defaultCloudFps } from "../utils/compositionFps.js";
|
||||
import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js";
|
||||
|
||||
export const examples: Example[] = [
|
||||
["Deploy the Lambda render stack to AWS", "hyperframes lambda deploy"],
|
||||
@@ -126,12 +127,20 @@ export default defineCommand({
|
||||
description:
|
||||
"Output resolution preset that engages Chrome deviceScaleFactor supersampling. Accepts canonical names (landscape, landscape-4k, portrait, portrait-4k, square, square-4k) and aliases (1080p, 4k, uhd, hd). When set, the composition's authored data-width/data-height is supersampled to the target preset without changing the layout.",
|
||||
},
|
||||
fps: { type: "string", description: "Render fps (24 | 30 | 60)" },
|
||||
fps: { type: "string", description: `Render fps (${DISTRIBUTED_FPS.join(" | ")})` },
|
||||
format: { type: "string", description: "mp4 | mov | png-sequence | webm (default: mp4)" },
|
||||
codec: { type: "string", description: "h264 | h265 (mp4 only)" },
|
||||
quality: { type: "string", description: "draft | standard | high" },
|
||||
"chunk-size": { type: "string", description: "Frames per chunk (default: 240)" },
|
||||
"max-parallel-chunks": { type: "string", description: "Max concurrent chunks (default: 16)" },
|
||||
"chunk-size": {
|
||||
type: "string",
|
||||
description:
|
||||
"Frames per chunk (default: sized so each chunk fits the Lambda timeout, one wave across --concurrency)",
|
||||
},
|
||||
"max-parallel-chunks": {
|
||||
type: "string",
|
||||
description:
|
||||
"Max chunks per render (default: one wave across the deploy's --concurrency, widened to fit the Lambda timeout)",
|
||||
},
|
||||
"target-chunk-frames": {
|
||||
type: "string",
|
||||
description:
|
||||
@@ -231,13 +240,9 @@ export default defineCommand({
|
||||
try {
|
||||
await import("@hyperframes/aws-lambda/sdk");
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ERR_MODULE_NOT_FOUND") {
|
||||
if (isMissingPackageError(err, "@hyperframes/aws-lambda")) {
|
||||
console.error(
|
||||
`${c.error("@hyperframes/aws-lambda is not installed.")} The ${c.accent(`hyperframes lambda ${subcommand}`)} command needs it at runtime.\n` +
|
||||
`Install it alongside the CLI:\n` +
|
||||
` ${c.accent("npm install -g @hyperframes/aws-lambda")}\n` +
|
||||
`Or, for an opt-in dev setup:\n` +
|
||||
` ${c.accent("npm install @hyperframes/aws-lambda")}`,
|
||||
missingPackageMessage("@hyperframes/aws-lambda", `hyperframes lambda ${subcommand}`),
|
||||
);
|
||||
failCommand();
|
||||
}
|
||||
@@ -296,12 +301,11 @@ export default defineCommand({
|
||||
console.error("[lambda render] --width and --height are required.");
|
||||
failCommand();
|
||||
}
|
||||
const fpsRaw =
|
||||
parseIntFlag(args.fps) ??
|
||||
readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ??
|
||||
30;
|
||||
if (fpsRaw !== 24 && fpsRaw !== 30 && fpsRaw !== 60) {
|
||||
console.error(`[lambda render] --fps must be 24, 30, or 60; got ${fpsRaw}.`);
|
||||
const fpsRaw = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir);
|
||||
if (!isDistributedFps(fpsRaw)) {
|
||||
console.error(
|
||||
`[lambda render] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fpsRaw}.`,
|
||||
);
|
||||
failCommand();
|
||||
}
|
||||
const { runRender } = await import("./lambda/render.js");
|
||||
@@ -353,12 +357,11 @@ export default defineCommand({
|
||||
console.error("[lambda render-batch] --width and --height are required.");
|
||||
failCommand();
|
||||
}
|
||||
const fpsRaw =
|
||||
parseIntFlag(args.fps) ??
|
||||
readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ??
|
||||
30;
|
||||
if (fpsRaw !== 24 && fpsRaw !== 30 && fpsRaw !== 60) {
|
||||
console.error(`[lambda render-batch] --fps must be 24, 30, or 60; got ${fpsRaw}.`);
|
||||
const fpsRaw = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir);
|
||||
if (!isDistributedFps(fpsRaw)) {
|
||||
console.error(
|
||||
`[lambda render-batch] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fpsRaw}.`,
|
||||
);
|
||||
failCommand();
|
||||
}
|
||||
const { runRenderBatch } = await import("./lambda/render-batch.js");
|
||||
|
||||
@@ -86,6 +86,7 @@ export async function runDeploy(args: Partial<DeployArgs> = {}): Promise<void> {
|
||||
stateMachineArn: outputs.stateMachineArn,
|
||||
functionName: outputs.functionName,
|
||||
lambdaMemoryMb: resolved.lambdaMemoryMb,
|
||||
reservedConcurrency: resolved.reservedConcurrency,
|
||||
deployedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
|
||||
@@ -167,4 +167,8 @@ describe("buildLambdaBatchRenderConfig — aspect-agnostic wire threading", () =
|
||||
expect(config.outputResolution).toBe("portrait-4k");
|
||||
expect(config.outputResolutionAspectAgnostic).toBeUndefined();
|
||||
});
|
||||
|
||||
it("hands the deploy's reserved concurrency to the planner", () => {
|
||||
expect(buildLambdaBatchRenderConfig(baseArgs, 64).workerConcurrency).toBe(64);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,7 +29,7 @@ import type {
|
||||
SerializableDistributedRenderConfig,
|
||||
SiteHandle,
|
||||
} from "@hyperframes/aws-lambda/sdk";
|
||||
import type { CanvasResolution } from "@hyperframes/core";
|
||||
import type { CanvasResolution, DistributedFps } from "@hyperframes/core";
|
||||
import { c } from "../../ui/colors.js";
|
||||
import { errorBox } from "../../ui/format.js";
|
||||
import {
|
||||
@@ -61,7 +61,7 @@ export interface RenderBatchArgs {
|
||||
*/
|
||||
siteId?: string;
|
||||
/** Composition config — fps/width/height/format required, rest optional. */
|
||||
fps: 24 | 30 | 60;
|
||||
fps: DistributedFps;
|
||||
width: number;
|
||||
height: number;
|
||||
/** See {@link RenderArgs.outputResolution}. */
|
||||
@@ -217,7 +217,10 @@ export async function runRenderBatch(args: RenderBatchArgs): Promise<void> {
|
||||
failCommand();
|
||||
}
|
||||
|
||||
const config: SerializableDistributedRenderConfig = buildLambdaBatchRenderConfig(args);
|
||||
const config: SerializableDistributedRenderConfig = buildLambdaBatchRenderConfig(
|
||||
args,
|
||||
stack.reservedConcurrency,
|
||||
);
|
||||
|
||||
// Deploy the site once and reuse it across every entry. --site-id and
|
||||
// --dry-run both skip the deploy via a synthesised handle.
|
||||
@@ -354,6 +357,7 @@ function makePlaceholderSiteHandle(siteId: string, bucketName: string): SiteHand
|
||||
*/
|
||||
export function buildLambdaBatchRenderConfig(
|
||||
args: RenderBatchArgs,
|
||||
workerConcurrency?: number,
|
||||
): SerializableDistributedRenderConfig {
|
||||
const config: SerializableDistributedRenderConfig = {
|
||||
fps: args.fps,
|
||||
@@ -366,6 +370,7 @@ export function buildLambdaBatchRenderConfig(
|
||||
chunkSize: args.chunkSize,
|
||||
maxParallelChunks: args.maxParallelChunks,
|
||||
targetChunkFrames: args.targetChunkFrames,
|
||||
workerConcurrency,
|
||||
runtimeCap: "lambda",
|
||||
};
|
||||
if (args.outputResolutionAspectAgnostic) {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import lambdaCommand from "../lambda.js";
|
||||
import { buildLambdaRenderConfig, type RenderArgs } from "./render.js";
|
||||
|
||||
const BASE_ARGS: RenderArgs = {
|
||||
@@ -55,3 +56,18 @@ describe("buildLambdaRenderConfig — aspect-agnostic wire threading", () => {
|
||||
expect(config.variables).toEqual({ alice: "hello" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("lambda render chunk sizing", () => {
|
||||
it("hands the deploy's reserved concurrency to the planner", () => {
|
||||
expect(buildLambdaRenderConfig(BASE_ARGS, undefined, 64).workerConcurrency).toBe(64);
|
||||
expect(buildLambdaRenderConfig(BASE_ARGS, undefined).workerConcurrency).toBeUndefined();
|
||||
});
|
||||
|
||||
it("help no longer claims --chunk-size defaults to 240", () => {
|
||||
const chunkSizeArg = lambdaCommand.args
|
||||
? Reflect.get(lambdaCommand.args, "chunk-size")
|
||||
: undefined;
|
||||
expect(chunkSizeArg?.description).not.toContain("240");
|
||||
expect(chunkSizeArg?.description).toContain("timeout");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
DistributedFormat,
|
||||
SerializableDistributedRenderConfig,
|
||||
} from "@hyperframes/aws-lambda/sdk";
|
||||
import type { CanvasResolution } from "@hyperframes/core";
|
||||
import type { CanvasResolution, DistributedFps } from "@hyperframes/core";
|
||||
import { c } from "../../ui/colors.js";
|
||||
import {
|
||||
reportVariableIssues,
|
||||
@@ -32,7 +32,7 @@ export interface RenderArgs {
|
||||
stackName: string;
|
||||
siteId?: string;
|
||||
/** Composition config — fps/width/height/format required, rest optional. */
|
||||
fps: 24 | 30 | 60;
|
||||
fps: DistributedFps;
|
||||
width: number;
|
||||
height: number;
|
||||
/**
|
||||
@@ -124,7 +124,11 @@ export async function runRender(args: RenderArgs): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const config: SerializableDistributedRenderConfig = buildLambdaRenderConfig(args, variables);
|
||||
const config: SerializableDistributedRenderConfig = buildLambdaRenderConfig(
|
||||
args,
|
||||
variables,
|
||||
stack.reservedConcurrency,
|
||||
);
|
||||
|
||||
// When the caller passes only --site-id, synthesise the minimum-shape
|
||||
// SiteHandle pointing at the deterministic content-addressed key. The
|
||||
@@ -241,6 +245,7 @@ function sleep(ms: number): Promise<void> {
|
||||
export function buildLambdaRenderConfig(
|
||||
args: RenderArgs,
|
||||
variables: Record<string, unknown> | undefined,
|
||||
workerConcurrency?: number,
|
||||
): SerializableDistributedRenderConfig {
|
||||
const config: SerializableDistributedRenderConfig = {
|
||||
fps: args.fps,
|
||||
@@ -253,6 +258,7 @@ export function buildLambdaRenderConfig(
|
||||
chunkSize: args.chunkSize,
|
||||
maxParallelChunks: args.maxParallelChunks,
|
||||
targetChunkFrames: args.targetChunkFrames,
|
||||
workerConcurrency,
|
||||
runtimeCap: "lambda",
|
||||
variables,
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface StackOutputs {
|
||||
functionName: string;
|
||||
/** Lambda memory MB used during deploy; carried so cost math doesn't have to re-derive it. */
|
||||
lambdaMemoryMb: number;
|
||||
reservedConcurrency?: number;
|
||||
deployedAt: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -704,9 +704,24 @@
|
||||
return colorAlpha(getComputedStyle(element).color) >= 0.35;
|
||||
}
|
||||
|
||||
const RUNTIME_HIDDEN_CLIP = '[data-hf-clip-hidden][style*="visibility: hidden"]';
|
||||
|
||||
// Core's timedClipHide rule hides these clips' whole subtrees: skipping them bounds work by what is on screen.
|
||||
function elementsOnScreenScenes(root) {
|
||||
const elements = [];
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
|
||||
acceptNode: (element) =>
|
||||
element.matches(RUNTIME_HIDDEN_CLIP) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
|
||||
});
|
||||
for (let element = walker.nextNode(); element; element = walker.nextNode()) {
|
||||
elements.push(element);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
function collectSolidTextBlocks(root) {
|
||||
const blocks = [];
|
||||
for (const element of Array.from(root.querySelectorAll("*"))) {
|
||||
for (const element of elementsOnScreenScenes(root)) {
|
||||
if (!isSolidTextBlock(element)) continue;
|
||||
const rects = visibleTextClientRects(element, true);
|
||||
const rect = unionRects(rects);
|
||||
|
||||
@@ -2360,6 +2360,32 @@ describe("layout-audit.browser content overlap", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("never reads inside a scene the runtime hid", () => {
|
||||
document.body.innerHTML = `
|
||||
<div id="root" data-composition-id="main" data-width="1920" data-height="1080">
|
||||
<div id="host" data-hf-clip-hidden style="visibility: hidden"><div id="a">Later scene line</div></div>
|
||||
<div id="b">Current scene line</div>
|
||||
</div>
|
||||
`;
|
||||
installOverlapStyles(
|
||||
{ a: "rgb(0, 0, 0)", b: "rgb(0, 0, 0)" },
|
||||
{ a: "none", b: "none" },
|
||||
{},
|
||||
{ host: "hidden", a: "visible", b: "visible" },
|
||||
);
|
||||
installOverlapGeometry({
|
||||
a: [rect({ left: 100, top: 100, width: 400, height: 100 })],
|
||||
b: [rect({ left: 300, top: 120, width: 400, height: 100 })],
|
||||
});
|
||||
installAuditScript();
|
||||
|
||||
const audit = (window as unknown as { __hyperframesOverlapAudit: OverlapAudit })
|
||||
.__hyperframesOverlapAudit;
|
||||
expect(audit({ time: 1 })).toEqual([]);
|
||||
const read = vi.mocked(window.getComputedStyle).mock.calls.map(([element]) => element.id);
|
||||
expect(read).not.toContain("a");
|
||||
});
|
||||
|
||||
// A typewriter span clipped to nothing (clip-path: inset(0 100% 0 0)) keeps a
|
||||
// normal box but paints zero pixels; overlapping it must not flag the visible
|
||||
// block beneath. The clipped element is unreachable by elementFromPoint, which
|
||||
@@ -3726,6 +3752,8 @@ interface AuditIssue {
|
||||
coveredFraction?: number;
|
||||
}
|
||||
|
||||
type OverlapAudit = (options: { time: number }) => AuditIssue[];
|
||||
|
||||
function runAudit(options?: { proseCoverageFloor?: number }): AuditIssue[] {
|
||||
const audit = (
|
||||
window as unknown as {
|
||||
|
||||
@@ -1871,10 +1871,10 @@ describe("checkRenderResolutionPreflight", () => {
|
||||
expect(result?.kind).toBe("hdr-incompatible");
|
||||
});
|
||||
|
||||
it("classifies a preset smaller than the composition as downsampling", async () => {
|
||||
// 3840×2160 comp + landscape (1920×1080): same 16:9 aspect, target smaller.
|
||||
it("passes a preset smaller than the composition", async () => {
|
||||
// 3840×2160 comp + landscape (1920×1080): same 16:9 aspect, rendered at 0.5× DPR.
|
||||
const result = await checkRenderResolutionPreflight(comp(3840, 2160), "landscape", noModes);
|
||||
expect(result?.kind).toBe("downsampling");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("classifies a non-integer upscale as non-integer-scale", async () => {
|
||||
@@ -1944,12 +1944,18 @@ describe("checkRenderResolutionPreflight", () => {
|
||||
expect(result?.kind).toBe("hdr-incompatible");
|
||||
});
|
||||
|
||||
it("still flags downsampling + aspect-agnostic (same-orientation, smaller preset)", async () => {
|
||||
// 3840×2160 comp with `--resolution 1080p` → `landscape` (1920×1080).
|
||||
// Same orientation, but tier smaller than comp — user asked for a
|
||||
// downsample. That's a real incompatibility, not an orientation swap.
|
||||
it("passes `--resolution 1080p` on a 4K composition (a smaller, same-orientation preset)", async () => {
|
||||
const result = await checkRenderResolutionPreflight(comp(3840, 2160), "landscape", agnostic);
|
||||
expect(result?.kind).toBe("downsampling");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("never adapts `--resolution 4k` to another tier: a 1922×1080 composition is refused, not rendered at 480p", async () => {
|
||||
const result = await checkRenderResolutionPreflight(
|
||||
comp(1922, 1080),
|
||||
"landscape-4k",
|
||||
agnostic,
|
||||
);
|
||||
expect(result?.kind).toBeDefined();
|
||||
});
|
||||
|
||||
it("does NOT auto-clear when the flag was explicit (orientation-locked preset stays strict)", async () => {
|
||||
@@ -1983,14 +1989,10 @@ describe("checkRenderResolutionPreflight", () => {
|
||||
expect(result?.message).toMatch(/preset whose orientation matches|omit --resolution/i);
|
||||
});
|
||||
|
||||
it("blocks a portrait-4K comp + `1080p` downsample early (orientation-flip masks the tier gap)", async () => {
|
||||
// 2160×3840 (portrait 4K) + `--resolution 1080p` — the compile stage
|
||||
// remaps `landscape` → `portrait` (1080×1920), and *then* the preset
|
||||
// is smaller than the composition. The un-remapped preflight let this
|
||||
// slip through as an aspect-mismatch downgrade; the remap-then-check
|
||||
// catches the real failure — downsampling — early.
|
||||
it("passes a portrait-4K comp + `1080p` once remapped to portrait (a smaller preset)", async () => {
|
||||
// 2160×3840 + `--resolution 1080p` remaps `landscape` → `portrait` (1080×1920), rendered at 0.5× DPR.
|
||||
const result = await checkRenderResolutionPreflight(comp(2160, 3840), "landscape", agnostic);
|
||||
expect(result?.kind).toBe("downsampling");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("blocks a portrait 720p comp + `1080p` non-integer upscale early (orientation-flip masks the fractional DPR)", async () => {
|
||||
|
||||
@@ -118,6 +118,7 @@ import {
|
||||
import { chromeLaunchRemediation } from "../browser/linuxDeps.js";
|
||||
import { macosOldChromeCrashRemediation } from "../browser/macosOldChromeCrash.js";
|
||||
import { windowsChromeCrashRemediation } from "../browser/windowsCrash.js";
|
||||
import { sandboxDeniedRemediation } from "../browser/sandboxDenied.js";
|
||||
import { killOrphanedProcessesForRender } from "../utils/orphanCleanup.js";
|
||||
import { createRenderCancellationScope } from "../utils/renderCancellation.js";
|
||||
import {
|
||||
@@ -1759,6 +1760,11 @@ function handleRenderError(
|
||||
// failure on Linux/WSL is an environment problem, not a composition bug.
|
||||
// Replace the generic "Try --docker" hint with the exact per-distro
|
||||
// remediation and a pointer at `doctor`.
|
||||
const sandboxRemediation = sandboxDeniedRemediation(message);
|
||||
if (sandboxRemediation) {
|
||||
errorBox("Render failed — Chrome could not launch", message, sandboxRemediation);
|
||||
failCommand();
|
||||
}
|
||||
const remediation = chromeLaunchRemediation(message);
|
||||
if (remediation) {
|
||||
errorBox("Render failed — Chrome could not launch", message, remediation);
|
||||
|
||||
@@ -640,6 +640,87 @@ describe("hyperframes skills", () => {
|
||||
expect(await commandExitCode()).toBe(1);
|
||||
});
|
||||
|
||||
// GH #5695: the router runs `skills update <workflow>` before every workflow, so a
|
||||
// team that pins its skills and sets HYPERFRAMES_SKIP_SKILLS=1 (like `init`
|
||||
// honours) must not have that pin replaced by the latest upstream skills.
|
||||
describe("with HYPERFRAMES_SKIP_SKILLS=1", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1");
|
||||
invalidateSkillsCache.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("named `skills update` leaves a pinned install alone and exits 0", async () => {
|
||||
setPlatform("linux");
|
||||
const logSpy = vi.spyOn(console, "log");
|
||||
const { checkSkills } = await import("../utils/skillsManifest.js");
|
||||
|
||||
await runSkillsUpdateWith(["product-launch-video"]);
|
||||
|
||||
expect(state.spawnCalls).toHaveLength(0);
|
||||
expect(vi.mocked(checkSkills)).not.toHaveBeenCalled();
|
||||
expect(invalidateSkillsCache).not.toHaveBeenCalled();
|
||||
expect(await commandExitCode()).toBe(0);
|
||||
expect(String(logSpy.mock.calls.at(-1)?.[0] ?? "")).toMatch(/managed externally/);
|
||||
});
|
||||
|
||||
it("bare `skills update` neither installs nor prunes", async () => {
|
||||
setPlatform("linux");
|
||||
const { checkSkills } = await import("../utils/skillsManifest.js");
|
||||
vi.mocked(checkSkills).mockImplementation(
|
||||
async () =>
|
||||
({
|
||||
...DEFAULT_CHECK,
|
||||
skills: [...DEFAULT_CHECK.skills, { name: "graphic-overlays", status: "removed" }],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
await runSkillsUpdate();
|
||||
|
||||
expect(state.spawnCalls).toHaveLength(0);
|
||||
expect(vi.mocked(checkSkills)).not.toHaveBeenCalled();
|
||||
expect(await commandExitCode()).toBe(0);
|
||||
});
|
||||
|
||||
it("bare `skills` does not install the full set", async () => {
|
||||
setPlatform("linux");
|
||||
|
||||
const { default: skillsCmd } = await import("./skills.js");
|
||||
await skillsCmd.run?.({ args: {}, rawArgs: [], cmd: skillsCmd } as never);
|
||||
|
||||
expect(state.spawnCalls).toHaveLength(0);
|
||||
expect(invalidateSkillsCache).not.toHaveBeenCalled();
|
||||
expect(await commandExitCode()).toBe(0);
|
||||
});
|
||||
|
||||
it("--json reports the skip as parseable JSON", async () => {
|
||||
setPlatform("linux");
|
||||
const logSpy = vi.spyOn(console, "log");
|
||||
|
||||
await runSkillsUpdateWith(["pr-to-video"], { json: true });
|
||||
|
||||
expect(await commandExitCode()).toBe(0);
|
||||
const parsed = JSON.parse(String(logSpy.mock.calls.at(-1)?.[0] ?? "")) as {
|
||||
skipped?: boolean;
|
||||
requested?: string[];
|
||||
};
|
||||
expect(parsed.skipped).toBe(true);
|
||||
expect(parsed.requested).toEqual(["pr-to-video"]);
|
||||
});
|
||||
|
||||
it("still rejects flag-like skill names", async () => {
|
||||
setPlatform("linux");
|
||||
|
||||
await runSkillsUpdateWith(["--all"]);
|
||||
|
||||
expect(state.spawnCalls).toHaveLength(0);
|
||||
expect(await commandExitCode()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// The stale-24h-cache regression: the skills commands are excluded from the
|
||||
// background nudge pipeline (cli.ts), so unless they drop the cached verdict
|
||||
// themselves, a successful install keeps the pre-install "N out of date or
|
||||
|
||||
@@ -615,6 +615,37 @@ const checkCommand = defineCommand({
|
||||
},
|
||||
});
|
||||
|
||||
// ── externally managed installs ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* `HYPERFRAMES_SKIP_SKILLS=1` means something other than this CLI owns the skills
|
||||
* install: CI, tests, or a team that pins the skills to one commit. `init` and the
|
||||
* background nudge already stand down for it; the install commands must too, or
|
||||
* the router's trigger-time `skills update <workflow>` replaces a pinned install
|
||||
* with the latest upstream skills (GH #5695).
|
||||
*/
|
||||
function skillsManagedExternally(): boolean {
|
||||
return process.env["HYPERFRAMES_SKIP_SKILLS"] === "1";
|
||||
}
|
||||
|
||||
const SKILLS_MANAGED_EXTERNALLY_NOTICE =
|
||||
"HYPERFRAMES_SKIP_SKILLS=1: skills are managed externally, so the installed skills were left unchanged.";
|
||||
|
||||
/** The skip line for an externally managed install: JSON for agents, one dim line for humans. */
|
||||
function reportSkillsManagedExternally(requested: readonly string[], json: boolean): void {
|
||||
if (json) {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
withMeta({ skipped: true, reason: SKILLS_MANAGED_EXTERNALLY_NOTICE, requested }),
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
console.log(c.dim(SKILLS_MANAGED_EXTERNALLY_NOTICE));
|
||||
}
|
||||
|
||||
// ── update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -713,6 +744,13 @@ const updateCommand = defineCommand({
|
||||
return;
|
||||
}
|
||||
|
||||
// Exit 0 without installing, pruning or touching the nudge cache: the pinned
|
||||
// install is the one the caller wants, so the router's step keeps working.
|
||||
if (skillsManagedExternally()) {
|
||||
reportSkillsManagedExternally(requested, args.json === true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Targeted, not full-set: refresh the core set (entry router + shared
|
||||
// domain skills) plus whatever is already installed, plus anything named
|
||||
// above. Without names a deliberate partial install stays partial
|
||||
@@ -813,6 +851,10 @@ export default defineCommand({
|
||||
// the positional so bare `hyperframes skills` installs, while
|
||||
// `hyperframes skills check|update` does not also re-install.
|
||||
if (!args._?.[0]) {
|
||||
if (skillsManagedExternally()) {
|
||||
reportSkillsManagedExternally([], false);
|
||||
return;
|
||||
}
|
||||
await updateSkills({ all: true });
|
||||
// Same as updateSkills: a full install supersedes the background
|
||||
// nudge's cached pre-install verdict.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { constants } from "node:os";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
const os = vi.hoisted(() => ({ setPriority: vi.fn() }));
|
||||
vi.mock("node:os", async (importOriginal) => ({
|
||||
@@ -8,11 +8,15 @@ vi.mock("node:os", async (importOriginal) => ({
|
||||
}));
|
||||
vi.mock("./utils/lintProject.js", () => ({ lintProject: vi.fn(async () => ({ ok: true })) }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
os.setPriority.mockReset();
|
||||
process.argv[2] = "lint";
|
||||
process.env.HYPERFRAMES_RENDER_SETUP_INPUT = JSON.stringify({ projectDir: "/project" });
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("lints at the lowest CPU priority so it never competes with a Studio boot", async () => {
|
||||
process.argv[2] = "lint";
|
||||
process.env.HYPERFRAMES_RENDER_SETUP_INPUT = JSON.stringify({ projectDir: "/project" });
|
||||
const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
|
||||
await import("./renderSetupWorker.js");
|
||||
@@ -20,3 +24,17 @@ it("lints at the lowest CPU priority so it never competes with a Studio boot", a
|
||||
expect(os.setPriority).toHaveBeenCalledWith(constants.priority.PRIORITY_LOW);
|
||||
expect(write).toHaveBeenCalledWith(expect.stringContaining('{"ok":true}'));
|
||||
});
|
||||
|
||||
it("still lints when a sandbox forbids lowering the priority", async () => {
|
||||
os.setPriority.mockImplementation(() => {
|
||||
throw new Error("uv_os_setpriority returned EPERM (operation not permitted)");
|
||||
});
|
||||
const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
const warn = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
|
||||
await import("./renderSetupWorker.js");
|
||||
|
||||
expect(write).toHaveBeenCalledWith(expect.stringContaining('{"ok":true}'));
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining("EPERM"));
|
||||
});
|
||||
|
||||
@@ -18,11 +18,19 @@ const disposeSignalHandlers = installRenderSetupSignalHandlers(
|
||||
process.env.HYPERFRAMES_RENDER_DETACHED !== "1",
|
||||
);
|
||||
|
||||
function lowerPriority(): void {
|
||||
try {
|
||||
setPriority(constants.priority.PRIORITY_LOW);
|
||||
} catch (error) {
|
||||
process.stderr.write(`Lint runs at normal priority: ${(error as Error).message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runMode(): Promise<unknown> {
|
||||
if (mode === "browser") return ensureBrowser(input);
|
||||
if (mode === "lint") {
|
||||
// Nobody waits on a background lint the way they wait on a Studio boot, so it takes idle CPU only.
|
||||
setPriority(constants.priority.PRIORITY_LOW);
|
||||
lowerPriority();
|
||||
return lintProject(
|
||||
input.projectDir,
|
||||
input.entryFile,
|
||||
|
||||
@@ -137,6 +137,19 @@ export function diff(before: string, after: string): string {
|
||||
return output.length <= 8_000 ? output : `${output.slice(0, 7_997)}...`;
|
||||
}
|
||||
|
||||
function isAncestorOf(ancestor: TimelineRow, row: TimelineRow, timeline: ProjectTimeline): boolean {
|
||||
for (let pointer = row.parentRow; pointer; ) {
|
||||
const parent = rowAt(timeline, pointer);
|
||||
if (parent === ancestor) return true;
|
||||
pointer = parent.parentRow;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function sameLineage(a: TimelineRow, b: TimelineRow, timeline: ProjectTimeline): boolean {
|
||||
return isAncestorOf(a, b, timeline) || isAncestorOf(b, a, timeline);
|
||||
}
|
||||
|
||||
function overlap(
|
||||
row: TimelineRow,
|
||||
timeline: ProjectTimeline,
|
||||
@@ -146,6 +159,7 @@ function overlap(
|
||||
return allRows(timeline).find(
|
||||
(candidate) =>
|
||||
candidate !== row &&
|
||||
!sameLineage(candidate, row, timeline) &&
|
||||
candidate.file === row.file &&
|
||||
candidate.trackIndex === row.trackIndex &&
|
||||
spansShareTime(start, end, candidate.start, candidate.end),
|
||||
@@ -429,6 +443,7 @@ export function mutationConflict(
|
||||
if (verb === "duplicate") {
|
||||
const conflict = allRows(timeline).find(
|
||||
(candidate) =>
|
||||
!sameLineage(candidate, row, timeline) &&
|
||||
candidate.file === row.file &&
|
||||
candidate.trackIndex === row.trackIndex &&
|
||||
isInsideSpan(nextStart, candidate.start, candidate.end),
|
||||
|
||||
@@ -18,12 +18,12 @@ const SCENE = `<template id="scene-template"><div data-composition-id="scene" da
|
||||
beforeAll(ensureDOMParser);
|
||||
|
||||
/** The video rows of a project made of `index` and `compositions/scene.html`. */
|
||||
async function videoRows(index: string, prefix: string) {
|
||||
async function videoRows(index: string, prefix: string, scene = SCENE) {
|
||||
const dir = mkdtempSync(join(tmpdir(), prefix));
|
||||
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
|
||||
mkdirSync(join(dir, "compositions"));
|
||||
writeFileSync(join(dir, "index.html"), index);
|
||||
writeFileSync(join(dir, "compositions", "scene.html"), SCENE);
|
||||
writeFileSync(join(dir, "compositions", "scene.html"), scene);
|
||||
const timeline = await describeProject(join(dir, "index.html"));
|
||||
return timeline.tracks.find((t) => t.kind === "video")!.rows;
|
||||
}
|
||||
@@ -43,6 +43,17 @@ describe("a sub-composition's in-point", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("cuts a clip nested in a timed wrapper like the wrapper's own clips", async () => {
|
||||
const videos = await videoRows(
|
||||
`<div data-composition-id="main" data-duration="9"><div data-playback-start="5" id="half" data-composition-src="compositions/scene.html" data-start="5" data-duration="4"></div></div>`,
|
||||
"hf-timeline-inpoint-nested-",
|
||||
`<div data-composition-id="scene" data-duration="12"><div id="w" data-start="0" data-duration="12">
|
||||
<video id="n" src="../sample.mp4" muted data-start="4" data-duration="4" data-media-start="5"></video></div></div>`,
|
||||
);
|
||||
|
||||
expect(videos.map((r) => [r.id, r.absStart, r.absEnd, r.mediaStart])).toEqual([["n", 5, 8, 6]]);
|
||||
});
|
||||
|
||||
it("moves each cut clip's media in-point by the part the cut skips", async () => {
|
||||
const videos = await videoRows(SPLIT_INDEX, "hf-timeline-inpoint-media-");
|
||||
|
||||
|
||||
@@ -116,6 +116,44 @@ describe("describeProject", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists clips nested in a timed wrapper at their playback time and says when one never shows", async () => {
|
||||
const { rows, text } = await rowsOf(`<html><body>
|
||||
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="10">
|
||||
<div id="shot2" data-start="5" data-duration="5" data-track-index="0">
|
||||
<h1 id="seen" data-start="6" data-duration="2">In</h1>
|
||||
<h1 id="lost" data-start="0" data-duration="2">Out</h1>
|
||||
</div>
|
||||
</div></body></html>`);
|
||||
const byId = (id: string) => rows.find((r) => r.id === id)!;
|
||||
const at = (p: { kind: string; index: number }) =>
|
||||
rows.find((r) => r.trackKind === p.kind && r.index === p.index)!.id;
|
||||
|
||||
expect(byId("shot2").children.map(at).sort()).toEqual(["lost", "seen"]);
|
||||
expect(byId("seen")).toMatchObject({ absStart: 6, absEnd: 8, warnings: [], nested: false });
|
||||
expect(at(byId("seen").parentRow!)).toBe("shot2");
|
||||
expect(byId("lost").warnings).toEqual([
|
||||
"never visible: plays 0-2s, but #shot2 only shows 5-10s; a nested data-start counts from the composition, not from #shot2",
|
||||
]);
|
||||
expect(text).toContain("#lost lost 0-2s warning: never visible");
|
||||
expect(text).not.toContain("no stable name");
|
||||
});
|
||||
|
||||
it("lists a sub-composition mounted inside a timed wrapper with every clip it holds", async () => {
|
||||
const { rows } = await rowsOf(`<html><body>
|
||||
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="10">
|
||||
<div id="shot" data-start="0" data-duration="5" data-track-index="0">
|
||||
<div id="scene" data-composition-src="compositions/title.html" data-start="0" data-duration="5"></div>
|
||||
</div>
|
||||
</div></body></html>`);
|
||||
const childIds = (id: string) =>
|
||||
rows
|
||||
.find((r) => r.id === id)!
|
||||
.children.map((p) => rows.find((r) => r.trackKind === p.kind && r.index === p.index)?.id);
|
||||
|
||||
expect(childIds("shot")).toEqual(["scene"]);
|
||||
expect(childIds("scene")).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("reports each half's out-of-sync offset from its source pair, at the project fps", async () => {
|
||||
const { rows, text } = await rowsOf(`<html><body>
|
||||
<div data-composition-id="main" data-duration="10" data-fps="24">
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type MediaTag,
|
||||
} from "@hyperframes/parsers/media-duration";
|
||||
import {
|
||||
isSubCompositionHost,
|
||||
topLevelElements,
|
||||
trackKindOf,
|
||||
type StructureNode,
|
||||
@@ -67,8 +68,10 @@ export interface TimelineRow extends ClipFact {
|
||||
host: string | null;
|
||||
/** Where that host row is (its kind's `rows[index]`), for hosts whose id is missing or repeated. */
|
||||
hostRow: RowPointer | null;
|
||||
/** Where this row's sub-composition clips are (one level only); each is a full row in its kind's `rows`. */
|
||||
/** Rows directly inside this one: its sub-composition's clips, or timed elements nested in it. */
|
||||
children: RowPointer[];
|
||||
/** The timed row in the same file that contains this clip; `null` at a file's top level. */
|
||||
parentRow: RowPointer | null;
|
||||
/** Signed frames from its `data-sync-origin` partner (+ = late); `null` unpaired or rates differ. */
|
||||
syncOffsetFrames: number | null;
|
||||
mediaStart: number | null;
|
||||
@@ -80,10 +83,14 @@ export interface RowPointer {
|
||||
}
|
||||
|
||||
/** A row before flattening: children are still row objects and refs are not assigned. */
|
||||
type ClipDraft = Omit<TimelineRow, "index" | "nested" | "host" | "hostRow" | "children"> & {
|
||||
type ClipDraft = Omit<
|
||||
TimelineRow,
|
||||
"index" | "nested" | "host" | "hostRow" | "children" | "parentRow"
|
||||
> & {
|
||||
elementId: string | null;
|
||||
hfId: string | null;
|
||||
children: ClipDraft[];
|
||||
inside: ClipDraft[];
|
||||
};
|
||||
|
||||
export interface TimelineTrack {
|
||||
@@ -276,6 +283,7 @@ interface RowTiming {
|
||||
authored: number | null;
|
||||
absStart: number;
|
||||
children: ClipDraft[];
|
||||
inside: ClipDraft[];
|
||||
duration: DurationResolution;
|
||||
}
|
||||
|
||||
@@ -291,11 +299,14 @@ async function resolveRowTiming(scope: DocScope, node: DomNode, depth: number):
|
||||
host && depth === 0
|
||||
? await readSubComposition(host, scope, compositionOriginSeconds(absStart, el), slots)
|
||||
: [];
|
||||
const inside = isSubCompositionHost(node)
|
||||
? []
|
||||
: await Promise.all(topLevelElements(node).map((inner) => describeRow(scope, inner, depth)));
|
||||
const kind = el.tagName.toLowerCase();
|
||||
const duration = MEDIA_TAG.test(kind)
|
||||
? await resolveMediaRowDuration(scope, el, kind as MediaTag, authored)
|
||||
: resolveContainerDuration(authored, children);
|
||||
return { start, authored, absStart, children, duration };
|
||||
return { start, authored, absStart, children, inside, duration };
|
||||
}
|
||||
|
||||
function describeRowFields(scope: DocScope, node: DomNode, timing: RowTiming): ClipDraft {
|
||||
@@ -326,6 +337,7 @@ function describeRowFields(scope: DocScope, node: DomNode, timing: RowTiming): C
|
||||
durationSource: timing.duration.durationSource,
|
||||
pendingReason: timing.duration.pendingReason,
|
||||
children: timing.children,
|
||||
inside: timing.inside,
|
||||
ref: "",
|
||||
warnings: [],
|
||||
elementId: el.id || null,
|
||||
@@ -384,7 +396,8 @@ function cutRow(row: ClipDraft, slots: readonly HostSlot[]): ClipDraft[] {
|
||||
if (kept.end === kept.start && row.absEnd > row.absStart) return [];
|
||||
const skipped = (kept.start - row.absStart) * (row.playbackRate ?? 1);
|
||||
const mediaStart = row.mediaStart === null ? null : roundMs(row.mediaStart + skipped);
|
||||
return [{ ...row, absStart: roundMs(kept.start), absEnd: roundMs(kept.end), mediaStart }];
|
||||
const inside = row.inside.flatMap((inner) => cutRow(inner, slots));
|
||||
return [{ ...row, absStart: roundMs(kept.start), absEnd: roundMs(kept.end), mediaStart, inside }];
|
||||
}
|
||||
|
||||
/** The file's real path when it is a regular file inside the project (symlinks resolved), else null. */
|
||||
@@ -401,10 +414,14 @@ function realFileInside(projectDir: string, path: string): string | null {
|
||||
|
||||
/** One flat, `absStart`-ordered list per kind holding every clip once; `children` become refs into those lists. */
|
||||
function flatten(top: ClipDraft[]): TimelineTrack[] {
|
||||
const entries = [
|
||||
...top.map((clip) => ({ clip, host: null })),
|
||||
...top.flatMap((host) => host.children.map((clip) => ({ clip, host }))),
|
||||
];
|
||||
type Entry = { clip: ClipDraft; host: ClipDraft | null; parent: ClipDraft | null };
|
||||
const entries: Entry[] = [];
|
||||
const add = (clip: ClipDraft, host: ClipDraft | null, parent: ClipDraft | null) => {
|
||||
entries.push({ clip, host, parent });
|
||||
for (const inner of clip.inside) add(inner, host, clip);
|
||||
for (const child of clip.children) add(child, clip, null);
|
||||
};
|
||||
for (const clip of top) add(clip, null, null);
|
||||
const byKind = TRACK_ORDER.map((kind) => ({
|
||||
kind,
|
||||
entries: entries
|
||||
@@ -426,19 +443,21 @@ function flatten(top: ClipDraft[]): TimelineTrack[] {
|
||||
}
|
||||
return byKind.map(({ kind, entries: kindEntries }) => ({
|
||||
kind,
|
||||
rows: kindEntries.map(({ clip, host }, index) => {
|
||||
rows: kindEntries.map(({ clip, host, parent }, index) => {
|
||||
const uniqueId = clip.elementId && fileIds.get(clip.file)?.get(clip.elementId) === 1;
|
||||
const ref = uniqueId
|
||||
? `#${clip.elementId}`
|
||||
: clip.hfId
|
||||
? `hf:${clip.hfId}`
|
||||
: `${kind}/${index}`;
|
||||
const warnings =
|
||||
uniqueId || clip.hfId
|
||||
const warnings = [
|
||||
...(uniqueId || clip.hfId
|
||||
? []
|
||||
: [
|
||||
'row has no stable name; add id="<name>" to the element in this file, then retry with #<name>',
|
||||
];
|
||||
]),
|
||||
...neverVisibleWarning(clip, parent),
|
||||
];
|
||||
return {
|
||||
...clip,
|
||||
index,
|
||||
@@ -447,12 +466,26 @@ function flatten(top: ClipDraft[]): TimelineTrack[] {
|
||||
nested: host !== null,
|
||||
host: host && host.id,
|
||||
hostRow: host && at(host),
|
||||
children: clip.children.map(at),
|
||||
children: [...clip.children, ...clip.inside].map(at),
|
||||
parentRow: parent && at(parent),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The runtime shows a nested clip only inside its parent's window, and its data-start counts from the composition. */
|
||||
export const NEVER_VISIBLE = "never visible";
|
||||
|
||||
function neverVisibleWarning(clip: ClipDraft, parent: ClipDraft | null): string[] {
|
||||
if (!parent || clip.kind === "audio") return [];
|
||||
if (clip.absEnd <= clip.absStart || parent.absEnd <= parent.absStart) return [];
|
||||
if (clip.absEnd > parent.absStart && clip.absStart < parent.absEnd) return [];
|
||||
const name = parent.elementId ? `#${parent.elementId}` : `its parent <${parent.kind}>`;
|
||||
return [
|
||||
`${NEVER_VISIBLE}: plays ${clip.absStart}-${clip.absEnd}s, but ${name} only shows ${parent.absStart}-${parent.absEnd}s; a nested data-start counts from the composition, not from ${name}`,
|
||||
];
|
||||
}
|
||||
|
||||
function projectFps(source: string): number {
|
||||
const parsed = parseFpsWithDefault(readCompositionFps(source) ?? undefined);
|
||||
return fpsToNumber(parsed.ok ? parsed.value : { num: 30, den: 1 });
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ProjectTimeline, TimelineRow, TimelineTrack } from "./describeProject.js";
|
||||
import {
|
||||
NEVER_VISIBLE,
|
||||
type ProjectTimeline,
|
||||
type TimelineRow,
|
||||
type TimelineTrack,
|
||||
} from "./describeProject.js";
|
||||
|
||||
const BAR_WIDTH = 40;
|
||||
const n = (v: number) => String(Math.round(v * 1000) / 1000);
|
||||
@@ -48,6 +53,7 @@ function details(row: TimelineRow): string {
|
||||
row.sourceFile && !row.children.length && "children=unread",
|
||||
row.laneError && `lanes unreadable: ${row.laneError}`,
|
||||
...lanes,
|
||||
...row.warnings.filter((w) => w.startsWith(NEVER_VISIBLE)).map((w) => `warning: ${w}`),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
@@ -63,7 +69,7 @@ function line(row: TimelineRow, total: number): string {
|
||||
}
|
||||
|
||||
function header({ kind, rows }: TimelineTrack): string {
|
||||
const nested = rows.filter((r) => r.nested).length;
|
||||
const nested = rows.filter((r) => r.nested || r.parentRow).length;
|
||||
const split = nested ? `: ${rows.length - nested} top-level, ${nested} nested` : "";
|
||||
return `${kind} (${rows.length}${split})`;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ const row: TimelineRow = {
|
||||
host: null,
|
||||
hostRow: null,
|
||||
children: [],
|
||||
parentRow: null,
|
||||
trackIndex: 0,
|
||||
src: null,
|
||||
sourceFile: null,
|
||||
|
||||
@@ -248,6 +248,27 @@ describe("timeline edit command", () => {
|
||||
};
|
||||
const endOf = (html: string, id: string) =>
|
||||
Number(clip(html, id).start) + Number(clip(html, id).duration);
|
||||
|
||||
it.each([
|
||||
["moves a hidden clip into its wrapper's window", ["move", "#lost", "8"], "lost", "8"],
|
||||
["moves a wrapper without colliding with its own clips", ["move", "#shot2", "4"], "shot2", "4"],
|
||||
["duplicates a clip inside its wrapper", ["duplicate", "#seen"], "seen", "6"],
|
||||
])("%s", (_name, args, id, start) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-timeline-nested-"));
|
||||
writeFileSync(
|
||||
join(dir, "index.html"),
|
||||
`<div data-composition-id="main" data-duration="12"><div id="shot2" data-hf-id="shot2" data-start="5" data-duration="5" data-track-index="0"><div id="seen" data-hf-id="seen" data-start="6" data-duration="2">In</div><div id="lost" data-hf-id="lost" data-start="0" data-duration="2">Out</div></div></div>`,
|
||||
);
|
||||
try {
|
||||
const result = run(dir, ...args);
|
||||
expect(result.stderr).not.toContain("overlap");
|
||||
expect(result.status).toBe(0);
|
||||
expect(clip(readFileSync(join(dir, "index.html"), "utf8"), id).start).toBe(start);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const visibleAt = (html: string, time: number, ids: string[]) =>
|
||||
ids.filter((id) => isClipVisibleAt(time, Number(clip(html, id).start), endOf(html, id), 40));
|
||||
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { beginArtifactCapture } from "@hyperframes/studio-server/history";
|
||||
import { withOwner } from "./historyOwner.js";
|
||||
|
||||
const SKIP_BUSY_HISTORY = { ownerWaitMs: 0 };
|
||||
|
||||
export async function captureArtifactRevision(projectDir: string) {
|
||||
return withOwner(projectDir, async (owner) => {
|
||||
await owner.checkpoint();
|
||||
return beginArtifactCapture(projectDir);
|
||||
});
|
||||
return withOwner(
|
||||
projectDir,
|
||||
async (owner) => {
|
||||
await owner.checkpoint();
|
||||
return beginArtifactCapture(projectDir);
|
||||
},
|
||||
SKIP_BUSY_HISTORY,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -570,6 +570,7 @@ function createPageDriver(page: Page, setTime: (time: number) => void): CheckAud
|
||||
getDuration: () => getCompositionDuration(page),
|
||||
hasNoTimelineDeclaration: () => hasNoTimelineDeclaration(page),
|
||||
getTransitionBoundaries: () => collectTweenBoundaries(page),
|
||||
getClipEdges: () => collectClipEdges(page),
|
||||
getCanvas: () =>
|
||||
page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight })),
|
||||
findAmbiguousSelectors: (selectors) => findAmbiguousSelectors(page, selectors),
|
||||
@@ -644,6 +645,16 @@ async function getCompositionDuration(page: Page): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
async function collectClipEdges(page: Page): Promise<number[]> {
|
||||
return page.evaluate(() => {
|
||||
type Clip = { kind: string; start: number; duration: number };
|
||||
const manifest = Reflect.get(window, "__clipManifest") as { clips?: Clip[] } | undefined;
|
||||
return (manifest?.clips ?? [])
|
||||
.filter((clip) => clip.kind !== "audio")
|
||||
.flatMap((clip) => [clip.start, clip.start + clip.duration]);
|
||||
});
|
||||
}
|
||||
|
||||
async function collectTweenBoundaries(page: Page): Promise<number[]> {
|
||||
// GSAP getter binding and parent-time conversion form one serialized algorithm.
|
||||
// fallow-ignore-next-line complexity
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
buildLayoutSampleTimes,
|
||||
buildTransitionSampleTimes,
|
||||
collapseStaticLayoutIssues,
|
||||
CONTENT_OVERLAP_HELD_ERROR_MS,
|
||||
longestContiguousRunMs,
|
||||
dedupeLayoutIssues,
|
||||
limitLayoutIssues,
|
||||
@@ -489,21 +490,76 @@ async function collectGridSamples(
|
||||
|
||||
// Dense grid catches mid-motion text collisions the sparse layout grid seeks past; text-only overlap collection is cheap enough to afford it.
|
||||
const OVERLAP_SAMPLE_FPS = 8;
|
||||
// Ceiling that bounds dense seeks; past ~75s the grid degrades below 8fps rather than growing the seek budget without limit.
|
||||
const OVERLAP_MAX_SAMPLES = 600;
|
||||
// A fixed ceiling, so check's work does not grow with film length: half uniform, half in clip windows it misses.
|
||||
const OVERLAP_MAX_SAMPLES = 240;
|
||||
// Part of it re-looks at an overlap half a second on where the grid is too sparse to show it held.
|
||||
const OVERLAP_HOLD_PROBES = 60;
|
||||
|
||||
function buildOverlapSampleTimes(duration: number): number[] {
|
||||
function evenlyPicked(times: number[], count: number): number[] {
|
||||
if (times.length <= count) return times;
|
||||
const last = Math.max(1, count - 1);
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, i) => times[Math.floor((i * (times.length - 1)) / last)] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
function uniformTimes(duration: number, fill: number): number[] {
|
||||
const step = duration / Math.max(1, fill - 1);
|
||||
return Array.from({ length: fill }, (_, i) => i * step);
|
||||
}
|
||||
|
||||
function buildOverlapSampleTimes(duration: number, clipEdges: number[]): number[] {
|
||||
if (!Number.isFinite(duration) || duration <= 0) return [];
|
||||
const count = Math.min(
|
||||
OVERLAP_MAX_SAMPLES,
|
||||
OVERLAP_MAX_SAMPLES - OVERLAP_HOLD_PROBES,
|
||||
Math.max(2, Math.ceil(duration * OVERLAP_SAMPLE_FPS) + 1),
|
||||
);
|
||||
const step = duration / (count - 1);
|
||||
const cuts: number[] = [];
|
||||
for (const time of mergeSampleTimes(
|
||||
[0, duration],
|
||||
clipEdges.filter((t) => t > 0 && t < duration),
|
||||
))
|
||||
if (time - (cuts.at(-1) ?? -Infinity) >= CONTENT_OVERLAP_HELD_ERROR_MS / 1000) cuts.push(time);
|
||||
// A stretch where the visible clips stay the same, and that the uniform half steps over, gets one sample.
|
||||
const uncovered = (fill: number): number[] => {
|
||||
const step = duration / Math.max(1, fill - 1);
|
||||
return cuts.slice(1).flatMap((end, i) => {
|
||||
const start = cuts[i] ?? 0;
|
||||
return Math.floor(start / step) === Math.floor(end / step) ? [(start + end) / 2] : [];
|
||||
});
|
||||
};
|
||||
let fill = count - Math.floor(count / 2);
|
||||
let windows = uncovered(fill);
|
||||
if (windows.length < count - fill) {
|
||||
fill = count - windows.length;
|
||||
windows = uncovered(fill);
|
||||
}
|
||||
const picked = evenlyPicked(windows, count - fill);
|
||||
return mergeSampleTimes(
|
||||
Array.from({ length: count }, (_, index) => Math.round(index * step * 1000) / 1000),
|
||||
[...picked, ...uniformTimes(duration, fill)].map((t) => Math.round(t * 1000) / 1000),
|
||||
);
|
||||
}
|
||||
|
||||
/** Looks once more half a second on, where the grid is too sparse to show an overlap is held; each overlap once. */
|
||||
function holdProber(driver: CheckAuditDriver, collected: GridSamples, end: number) {
|
||||
const holdS = CONTENT_OVERLAP_HELD_ERROR_MS / 1000;
|
||||
const held = new Set<string>();
|
||||
const keyOf = (issue: AnchoredLayoutIssue) => `${issue.code} ${issue.selector}`;
|
||||
let probes = 0;
|
||||
return async (time: number, next: number, issues: AnchoredLayoutIssue[]): Promise<void> => {
|
||||
const unproven = new Set(issues.map(keyOf).filter((key) => !held.has(key)));
|
||||
const probe = Math.round((time + holdS) * 1000) / 1000;
|
||||
const sparse = next - time > 2 * holdS && probe <= end;
|
||||
if (!unproven.size || !sparse || probes >= OVERLAP_HOLD_PROBES) return;
|
||||
probes += 1;
|
||||
await driver.seekGeometry(probe);
|
||||
const later = await driver.collectOverlap(probe);
|
||||
collected.layoutIssues.push(...later);
|
||||
for (const key of later.map(keyOf)) if (unproven.has(key)) held.add(key);
|
||||
};
|
||||
}
|
||||
|
||||
/** Reruns content_overlap on a fine grid, unconditionally rather than gated on fingerprint change, since an animation aliased to the sparse grid collides between identical-fingerprint samples. */
|
||||
async function collectMotionOverlapSamples(
|
||||
driver: CheckAuditDriver,
|
||||
@@ -512,15 +568,20 @@ async function collectMotionOverlapSamples(
|
||||
range?: [number, number],
|
||||
): Promise<void> {
|
||||
const baseTimes = new Set(grid.layoutSamples);
|
||||
const overlapTimes = buildOverlapSampleTimes(range ? range[1] - range[0] : grid.duration);
|
||||
const offset = range?.[0] ?? 0;
|
||||
const edges = (await driver.getClipEdges()).map((time) => time - offset);
|
||||
const overlapTimes = buildOverlapSampleTimes(range ? range[1] - range[0] : grid.duration, edges);
|
||||
const shiftedTimes = range
|
||||
? mergeSampleTimes(overlapTimes.map((time) => time + range[0]))
|
||||
: overlapTimes;
|
||||
for (const time of shiftedTimes) {
|
||||
const probeHold = holdProber(driver, collected, range ? range[1] : grid.duration);
|
||||
for (const [index, time] of shiftedTimes.entries()) {
|
||||
if (baseTimes.has(time)) continue;
|
||||
// Settle-free seek: collectOverlap reads getBoundingClientRect geometry, valid synchronously after setTime, so the dense pass skips the per-seek paint settle.
|
||||
await driver.seekGeometry(time);
|
||||
collected.layoutIssues.push(...(await driver.collectOverlap(time)));
|
||||
const issues = await driver.collectOverlap(time);
|
||||
collected.layoutIssues.push(...issues);
|
||||
await probeHold(time, shiftedTimes[index + 1] ?? Number.POSITIVE_INFINITY, issues);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -195,6 +195,7 @@ export interface CheckAuditDriver {
|
||||
/** True when the root composition explicitly declares that it is intentionally timeline-free. */
|
||||
hasNoTimelineDeclaration(): Promise<boolean>;
|
||||
getTransitionBoundaries(): Promise<number[]>;
|
||||
getClipEdges(): Promise<number[]>;
|
||||
getCanvas(): Promise<Canvas>;
|
||||
findAmbiguousSelectors(selectors: string[]): Promise<AnchoredLayoutIssue[]>;
|
||||
seek(time: number): Promise<void>;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { readAllowedCompositionFpsFromDir, readCompositionFps } from "./compositionFps.js";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { defaultCloudFps, readCompositionFps } from "./compositionFps.js";
|
||||
|
||||
const wrap = (body: string) => `<!DOCTYPE html><html><body>${body}</body></html>`;
|
||||
|
||||
@@ -41,11 +41,11 @@ describe("readCompositionFps", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readAllowedCompositionFpsFromDir", () => {
|
||||
describe("defaultCloudFps", () => {
|
||||
const projectDirs: string[] = [];
|
||||
const allowedCloudFps = [24, 30, 60] as const;
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of projectDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -58,50 +58,38 @@ describe("readAllowedCompositionFpsFromDir", () => {
|
||||
return dir;
|
||||
}
|
||||
|
||||
it("uses cloud-allowed data-fps=60 as the default", () => {
|
||||
const dir = makeProject(
|
||||
'<div data-composition-id="root" data-root="true" data-fps="60">x</div>',
|
||||
function root(fps: string): string {
|
||||
return makeProject(
|
||||
`<div data-composition-id="root" data-root="true" data-fps="${fps}">x</div>`,
|
||||
);
|
||||
}
|
||||
|
||||
expect(readAllowedCompositionFpsFromDir(dir, allowedCloudFps)).toBe(60);
|
||||
it.each([24, 25, 30, 60])("uses a supported data-fps=%i without warning", (fps) => {
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
expect(defaultCloudFps(root(String(fps)))).toBe(fps);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses cloud-allowed data-fps=24 as the default", () => {
|
||||
const dir = makeProject(
|
||||
'<div data-composition-id="root" data-root="true" data-fps="24">x</div>',
|
||||
);
|
||||
|
||||
expect(readAllowedCompositionFpsFromDir(dir, allowedCloudFps)).toBe(24);
|
||||
it.each(["48", "50", "30000/1001"])("falls back to 30 and warns for data-fps=%s", (fps) => {
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
expect(defaultCloudFps(root(fps))).toBe(30);
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(String(warn.mock.calls[0]?.[0])).toContain(`data-fps="${fps}"`);
|
||||
});
|
||||
|
||||
it("returns null for data-fps=48 so cloud callers keep their ?? 30 fallback", () => {
|
||||
const dir = makeProject(
|
||||
'<div data-composition-id="root" data-root="true" data-fps="48">x</div>',
|
||||
);
|
||||
|
||||
const declared = readAllowedCompositionFpsFromDir(dir, allowedCloudFps);
|
||||
expect(declared).toBeNull();
|
||||
expect(declared ?? 30).toBe(30);
|
||||
it("uses 30 without warning when index.html has no data-fps", () => {
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
expect(
|
||||
defaultCloudFps(makeProject('<div data-composition-id="root" data-root="true">x</div>')),
|
||||
).toBe(30);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null for fractional data-fps because cloud fps must be an integer", () => {
|
||||
const dir = makeProject(
|
||||
'<div data-composition-id="root" data-root="true" data-fps="30000/1001">x</div>',
|
||||
);
|
||||
|
||||
expect(readAllowedCompositionFpsFromDir(dir, allowedCloudFps)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when index.html has no data-fps", () => {
|
||||
const dir = makeProject('<div data-composition-id="root" data-root="true">x</div>');
|
||||
|
||||
expect(readAllowedCompositionFpsFromDir(dir, allowedCloudFps)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when index.html cannot be read", () => {
|
||||
it("uses 30 without warning when index.html cannot be read", () => {
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const dir = mkdtempSync(join(tmpdir(), "hyperframes-composition-fps-missing-"));
|
||||
projectDirs.push(dir);
|
||||
|
||||
expect(readAllowedCompositionFpsFromDir(dir, allowedCloudFps)).toBeNull();
|
||||
expect(defaultCloudFps(dir)).toBe(30);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core";
|
||||
import { parseHTML } from "linkedom";
|
||||
import { c } from "../ui/colors.js";
|
||||
|
||||
/**
|
||||
* Read a composition's declared frame rate from its root element's `data-fps`
|
||||
@@ -34,26 +36,29 @@ export function readCompositionFps(html: string): string | null {
|
||||
return raw ? raw : null;
|
||||
}
|
||||
|
||||
const DEFAULT_CLOUD_FPS: DistributedFps = 30;
|
||||
|
||||
/**
|
||||
* Cloud render backends (Lambda, Cloud Run) accept only an integer fps
|
||||
* from a small fixed allowed set (currently {24, 30, 60}) — unlike local
|
||||
* `render`, they can't take an arbitrary/fractional data-fps. Reads
|
||||
* `<projectDir>/index.html` and returns its declared data-fps as a number
|
||||
* ONLY when it parses to an integer AND is a member of `allowed`;
|
||||
* otherwise `null` so the caller keeps its own existing default (30).
|
||||
* Cloud render fps when `--fps` is not passed: `<projectDir>/index.html`'s
|
||||
* data-fps if it is in `DISTRIBUTED_FPS`, otherwise 30, with a warning when the
|
||||
* project declared a rate cloud renders cannot use.
|
||||
*/
|
||||
export function readAllowedCompositionFpsFromDir(
|
||||
projectDir: string,
|
||||
allowed: readonly number[],
|
||||
): number | null {
|
||||
export function defaultCloudFps(projectDir: string): DistributedFps {
|
||||
let html: string;
|
||||
try {
|
||||
html = readFileSync(join(projectDir, "index.html"), "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
return DEFAULT_CLOUD_FPS;
|
||||
}
|
||||
const raw = readCompositionFps(html);
|
||||
if (raw == null) return null;
|
||||
if (raw == null) return DEFAULT_CLOUD_FPS;
|
||||
const n = Number(raw);
|
||||
return Number.isInteger(n) && allowed.includes(n) ? n : null;
|
||||
if (isDistributedFps(n)) return n;
|
||||
console.warn(
|
||||
c.warn(
|
||||
`The composition declares data-fps="${raw}", which cloud renders do not support ` +
|
||||
`(${DISTRIBUTED_FPS.join(", ")}). Rendering at ${DEFAULT_CLOUD_FPS} fps; pass --fps to choose.`,
|
||||
),
|
||||
);
|
||||
return DEFAULT_CLOUD_FPS;
|
||||
}
|
||||
|
||||
@@ -172,14 +172,17 @@ function previewOwner(route: (path: string) => string): Owner {
|
||||
};
|
||||
}
|
||||
|
||||
async function directOwner(projectDir: string): Promise<{ owner: Owner; turn: Turn | null }> {
|
||||
async function directOwner(
|
||||
projectDir: string,
|
||||
ownerWaitMs = historyDeps.ownerWaitMs,
|
||||
): Promise<{ owner: Owner; turn: Turn | null }> {
|
||||
let turn: Turn | null = null;
|
||||
const history = await openProjectHistory({
|
||||
projectDir,
|
||||
historyRoot: historyDeps.historyRoot,
|
||||
now: () => historyDeps.now(),
|
||||
pruneGoneProjectsBudgetMs: 1000,
|
||||
ownerWaitMs: historyDeps.ownerWaitMs,
|
||||
ownerWaitMs,
|
||||
closedWindowAfterOwnership: () => {
|
||||
turn = readTurn(projectDir);
|
||||
return turn
|
||||
@@ -214,7 +217,10 @@ async function directOwner(projectDir: string): Promise<{ owner: Owner; turn: Tu
|
||||
}
|
||||
|
||||
/** One owner: a preview that keeps this project's history, else the engine, which refuses a second opener. */
|
||||
async function connect(projectDir: string): Promise<{ owner: Owner; turn: Turn | null }> {
|
||||
async function connect(
|
||||
projectDir: string,
|
||||
ownerWaitMs?: number,
|
||||
): Promise<{ owner: Owner; turn: Turn | null }> {
|
||||
const server = await historyDeps.findServer(projectDir);
|
||||
if (server) {
|
||||
const route = (path: string) => studioApiUrl(server, `history${path}`);
|
||||
@@ -225,16 +231,17 @@ async function connect(projectDir: string): Promise<{ owner: Owner; turn: Turn |
|
||||
);
|
||||
if (status !== 404) return { owner: previewOwner(route), turn: readTurn(projectDir) };
|
||||
}
|
||||
return directOwner(projectDir);
|
||||
return directOwner(projectDir, ownerWaitMs);
|
||||
}
|
||||
|
||||
/** Runs `task` with the project's history. ponytail: with no preview, a command mid-turn splits the turn in two. */
|
||||
export async function withOwner<T>(
|
||||
dir: string | undefined,
|
||||
task: (owner: Owner, turn: Turn | null, projectDir: string) => Promise<T>,
|
||||
{ ownerWaitMs }: { ownerWaitMs?: number } = {},
|
||||
): Promise<T> {
|
||||
const { dir: projectDir } = resolveProject(dir);
|
||||
const { owner, turn } = await connect(projectDir);
|
||||
const { owner, turn } = await connect(projectDir, ownerWaitMs);
|
||||
try {
|
||||
return await task(owner, turn, projectDir);
|
||||
} finally {
|
||||
|
||||
@@ -189,7 +189,7 @@ export function dedupeLayoutIssues(issues: LayoutIssue[]): LayoutIssue[] {
|
||||
}
|
||||
|
||||
// Persistence-tier thresholds (#U10): occurrences>=2 alone can't imply the 500ms floor under dense 8fps sampling, so content_overlap promotion requires a literal firstSeen..lastSeen span >= 500ms — stricter for sparse callers too.
|
||||
const CONTENT_OVERLAP_HELD_ERROR_MS = 500;
|
||||
export const CONTENT_OVERLAP_HELD_ERROR_MS = 500;
|
||||
const HELD_ACROSS_SAMPLES_MIN_OCCURRENCES = 2;
|
||||
|
||||
// Tiering only applies to layout-audit.browser.js's own per-sample seek-grid
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isMissingPackageError, missingPackageMessage } from "./missingPackage.js";
|
||||
|
||||
const notFound = (message: string) =>
|
||||
Object.assign(new Error(message), { code: "ERR_MODULE_NOT_FOUND" });
|
||||
|
||||
describe("isMissingPackageError", () => {
|
||||
it("is true when the package itself is absent", () => {
|
||||
const err = notFound("Cannot find package '@hyperframes/aws-lambda' imported from /app/cli.js");
|
||||
expect(isMissingPackageError(err, "@hyperframes/aws-lambda")).toBe(true);
|
||||
});
|
||||
|
||||
it("is false when an installed package is missing one of its own dependencies", () => {
|
||||
const err = notFound(
|
||||
"Cannot find package 'google-auth-library' imported from /app/node_modules/@hyperframes/gcp-cloud-run/dist/sdk.js",
|
||||
);
|
||||
expect(isMissingPackageError(err, "@hyperframes/gcp-cloud-run")).toBe(false);
|
||||
});
|
||||
|
||||
it("is false for other error codes", () => {
|
||||
const err = Object.assign(new Error("Cannot find package '@hyperframes/aws-lambda'"), {
|
||||
code: "ERR_UNKNOWN_FILE_EXTENSION",
|
||||
});
|
||||
expect(isMissingPackageError(err, "@hyperframes/aws-lambda")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("missingPackageMessage", () => {
|
||||
it("names the command and both install commands", () => {
|
||||
const message = missingPackageMessage("@hyperframes/aws-lambda", "hyperframes lambda deploy");
|
||||
expect(message).toContain("hyperframes lambda deploy");
|
||||
expect(message).toContain("npm install -g @hyperframes/aws-lambda");
|
||||
expect(message).toContain("npm install @hyperframes/aws-lambda");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { c } from "../ui/colors.js";
|
||||
|
||||
/**
|
||||
* True only when `pkg` itself is absent. Node's message for a missing dependency of an
|
||||
* installed `pkg` also names `pkg` (in the importer path), so match the quoted specifier.
|
||||
*/
|
||||
export function isMissingPackageError(error: unknown, pkg: string): boolean {
|
||||
return (
|
||||
(error as NodeJS.ErrnoException)?.code === "ERR_MODULE_NOT_FOUND" &&
|
||||
error instanceof Error &&
|
||||
error.message.includes(`Cannot find package '${pkg}'`)
|
||||
);
|
||||
}
|
||||
|
||||
export function missingPackageMessage(pkg: string, command: string): string {
|
||||
return (
|
||||
`${c.error(`${pkg} is not installed.`)} The ${c.accent(command)} command needs it at runtime.\n` +
|
||||
`Install it alongside the CLI:\n` +
|
||||
` ${c.accent(`npm install -g ${pkg}`)}\n` +
|
||||
`Or, for an opt-in project setup:\n` +
|
||||
` ${c.accent(`npm install ${pkg}`)}`
|
||||
);
|
||||
}
|
||||
@@ -32,6 +32,12 @@
|
||||
"types": "./dist/telemetryRedaction.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./distributed-fps": {
|
||||
"source": "./src/distributedFps.ts",
|
||||
"runtime": "./dist/distributedFps.js",
|
||||
"types": "./dist/distributedFps.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./beats": {
|
||||
"source": "./src/beats/index.ts",
|
||||
"runtime": "./dist/beats/index.js",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hyperframes/core",
|
||||
"version": "0.8.166",
|
||||
"version": "0.8.169",
|
||||
"description": "",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -44,6 +44,12 @@
|
||||
"import": "./src/telemetryRedaction.ts",
|
||||
"types": "./src/telemetryRedaction.ts"
|
||||
},
|
||||
"./distributed-fps": {
|
||||
"bun": "./src/distributedFps.ts",
|
||||
"node": "./dist/distributedFps.js",
|
||||
"import": "./src/distributedFps.ts",
|
||||
"types": "./src/distributedFps.ts"
|
||||
},
|
||||
"./beats": {
|
||||
"bun": "./src/beats/index.ts",
|
||||
"node": "./dist/beats/index.js",
|
||||
@@ -560,6 +566,10 @@
|
||||
"import": "./dist/telemetryRedaction.js",
|
||||
"types": "./dist/telemetryRedaction.d.ts"
|
||||
},
|
||||
"./distributed-fps": {
|
||||
"import": "./dist/distributedFps.js",
|
||||
"types": "./dist/distributedFps.d.ts"
|
||||
},
|
||||
"./beats": {
|
||||
"import": "./dist/beats/index.js",
|
||||
"types": "./dist/beats/index.d.ts"
|
||||
|
||||
@@ -309,3 +309,11 @@ export function enumerateNestedCompositionHosts<TElement extends AssemblyAttribu
|
||||
|
||||
return { hosts, skipped };
|
||||
}
|
||||
|
||||
/** A mount sharing the page root's id counts as a repeat, so it is numbered instead of taking the root's timeline. */
|
||||
export function countPageRoot(counts: Map<string, number>, hosts: readonly Element[]): void {
|
||||
const root = hosts[0]?.ownerDocument.querySelector("[data-composition-id]");
|
||||
const rootId = root && !hosts.includes(root) ? root.getAttribute("data-composition-id") : null;
|
||||
const mounts = rootId ? counts.get(rootId) : undefined;
|
||||
if (rootId && mounts) counts.set(rootId, mounts + 1);
|
||||
}
|
||||
|
||||
@@ -43,6 +43,45 @@ describe("composition scoping", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("never replaces another mount's timeline under the scene's own id", () => {
|
||||
const { document } = parseHTML("<main></main>");
|
||||
const fakeWindow = { document, __timelines: {} as Record<string, unknown>, readBack: "" };
|
||||
const run = (runtimeId: string, timeline: string) =>
|
||||
new Function(
|
||||
"window",
|
||||
wrapScopedCompositionScript(
|
||||
`window.__timelines.scene = ${JSON.stringify(timeline)};
|
||||
window.readBack = window.__timelines.scene;`,
|
||||
"scene",
|
||||
undefined,
|
||||
undefined,
|
||||
runtimeId,
|
||||
),
|
||||
)(fakeWindow);
|
||||
|
||||
run("scene", "first half");
|
||||
run("scene-split", "second half");
|
||||
expect(fakeWindow.__timelines).toEqual({ scene: "first half", "scene-split": "second half" });
|
||||
expect(fakeWindow.readBack).toBe("second half");
|
||||
|
||||
// A mount that owns the scene's id keeps it when its script runs again.
|
||||
const lone = { document, __timelines: {} as Record<string, unknown> };
|
||||
const runLone = (timeline: string) =>
|
||||
new Function(
|
||||
"window",
|
||||
wrapScopedCompositionScript(
|
||||
`window.__timelines.scene = ${JSON.stringify(timeline)};`,
|
||||
"scene",
|
||||
undefined,
|
||||
undefined,
|
||||
"intro",
|
||||
),
|
||||
)(lone);
|
||||
runLone("v1");
|
||||
runLone("v2");
|
||||
expect(lone.__timelines).toEqual({ scene: "v2", intro: "v2" });
|
||||
});
|
||||
|
||||
it("scopes regular selectors while preserving global at-rules", () => {
|
||||
const scoped = scopeCssToComposition(
|
||||
`
|
||||
|
||||
@@ -219,7 +219,14 @@ function fontFaceKey(atRule: AtRule): string {
|
||||
|
||||
/** Drops repeats of an identical `@font-face` across the given style texts, keeping the last copy:
|
||||
* the last matching rule is the one the browser uses, so a rule in between never gains precedence. */
|
||||
export function dedupeFontFaceRules(styleTexts: string[]): string[] {
|
||||
export const dedupeFontFaceRules = (styleTexts: string[]): string[] => dropFontFaces(styleTexts);
|
||||
|
||||
export function hoistFontFaceRules(styleTexts: string[]): { styles: string[]; faces: string[] } {
|
||||
const faces: string[] = [];
|
||||
return { styles: dropFontFaces(styleTexts, faces), faces };
|
||||
}
|
||||
|
||||
function dropFontFaces(styleTexts: string[], hoisted?: string[]): string[] {
|
||||
const seen = new Set<string>();
|
||||
return [...styleTexts]
|
||||
.reverse()
|
||||
@@ -235,12 +242,13 @@ export function dedupeFontFaceRules(styleTexts: string[]): string[] {
|
||||
for (const node of [...(root.nodes ?? [])].reverse()) {
|
||||
if (!isFontFaceAtRule(node)) continue;
|
||||
const key = fontFaceKey(node);
|
||||
if (seen.has(key)) {
|
||||
node.remove();
|
||||
changed = true;
|
||||
} else {
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
if (!hoisted) continue;
|
||||
hoisted.unshift(node.toString());
|
||||
}
|
||||
node.remove();
|
||||
changed = true;
|
||||
}
|
||||
return changed ? root.toResult({ map: false }).css : css;
|
||||
})
|
||||
@@ -415,10 +423,8 @@ export function wrapScopedCompositionScript(
|
||||
if (prop !== __hfCompId) {
|
||||
return Reflect.get(target, prop, target);
|
||||
}
|
||||
var authoredValue = Reflect.get(target, prop, target);
|
||||
return authoredValue === undefined
|
||||
? Reflect.get(target, __hfTimelineCompId, target)
|
||||
: authoredValue;
|
||||
var runtimeValue = Reflect.get(target, __hfTimelineCompId, target);
|
||||
return runtimeValue === undefined ? Reflect.get(target, prop, target) : runtimeValue;
|
||||
},
|
||||
set: function(target, prop, value, receiver) {
|
||||
if (prop !== __hfCompId) {
|
||||
@@ -426,11 +432,15 @@ export function wrapScopedCompositionScript(
|
||||
}
|
||||
// The authored node remains in the compiled DOM when its local id
|
||||
// differs from the runtime mount id, so readiness legitimately sees
|
||||
// both compositions. Publish the same timeline under both identities
|
||||
// instead of replacing one with the other.
|
||||
var authoredSet = Reflect.set(target, __hfCompId, value, target);
|
||||
// both compositions. Publish the same timeline under both identities,
|
||||
// unless another mount of the same file already owns the authored one.
|
||||
var authoredValue = Reflect.get(target, __hfCompId, target);
|
||||
var ownsAuthored =
|
||||
authoredValue === undefined ||
|
||||
authoredValue === Reflect.get(target, __hfTimelineCompId, target);
|
||||
var runtimeSet = Reflect.set(target, __hfTimelineCompId, value, target);
|
||||
return authoredSet && runtimeSet;
|
||||
if (!ownsAuthored) return runtimeSet;
|
||||
return Reflect.set(target, __hfCompId, value, target) && runtimeSet;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1080,6 +1080,30 @@ describe("bundleToSingleHtml", () => {
|
||||
expect(bundled).toContain('var __hfTimelineCompId = "scene__hf2"');
|
||||
});
|
||||
|
||||
it("gives a mount that shares the page root's id its own runtime id", async () => {
|
||||
const cliRoot = (title: string) =>
|
||||
`<div id="root" data-composition-id="main" data-width="1920" data-height="1080"><h1>${title}</h1>`;
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html>
|
||||
<html><head></head><body>
|
||||
${cliRoot("Host")}
|
||||
<div id="main_2" data-composition-id="main" data-composition-src="compositions/scene.html"></div>
|
||||
</div>
|
||||
<script>window.__timelines={};</script>
|
||||
</body></html>`,
|
||||
"compositions/scene.html": `<!doctype html><html><body>${cliRoot("Scene")}</div>
|
||||
<script>window.__timelines["main"] = "scene";</script>
|
||||
</body></html>`,
|
||||
});
|
||||
|
||||
const bundled = await bundleToSingleHtml(dir);
|
||||
const host = parseHTML(bundled).document.querySelector("#main_2");
|
||||
|
||||
expect(host?.getAttribute("data-composition-id")).toBe("main__hf1");
|
||||
expect(host?.getAttribute("data-hf-original-composition-id")).toBe("main");
|
||||
expect(bundled).toContain('var __hfTimelineCompId = "main__hf1"');
|
||||
});
|
||||
|
||||
it("uniquifies duplicate sub-compositions across inline-template and external hosts", async () => {
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html>
|
||||
@@ -3158,7 +3182,7 @@ describe("bundleToSingleHtml sceneParts", () => {
|
||||
const partsOf = (doc: Document, scene: string) =>
|
||||
[...doc.querySelectorAll(`[data-hf-scene="${scene}"]`)].map((el) => el.tagName.toLowerCase());
|
||||
|
||||
it("keeps each scene's own copy of a shared @font-face, so one scene still swaps alone", async () => {
|
||||
it("puts a @font-face two scenes share in one style outside the scenes, once", async () => {
|
||||
const face = `@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2'); }`;
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html>
|
||||
@@ -3178,8 +3202,14 @@ describe("bundleToSingleHtml sceneParts", () => {
|
||||
const css = [...doc.querySelectorAll(`style[data-hf-scene="${scene}"]`)]
|
||||
.map((el) => el.textContent ?? "")
|
||||
.join("\n");
|
||||
expect(css).toContain("@font-face");
|
||||
expect(css).not.toContain("@font-face");
|
||||
}
|
||||
const fonts = doc.querySelector("style[data-hf-scene-fonts]");
|
||||
expect(fonts?.hasAttribute("data-hf-scene")).toBe(false);
|
||||
const faces = (css: string) => css.match(/@font-face/g)?.length ?? 0;
|
||||
expect(faces(fonts?.textContent ?? "")).toBe(1);
|
||||
const allCss = [...doc.querySelectorAll("style")].map((el) => el.textContent ?? "").join("\n");
|
||||
expect(faces(allCss)).toBe(1);
|
||||
});
|
||||
|
||||
it("tags each top-level scene's host, styles and scripts, with nested scenes in their parent's parts", async () => {
|
||||
@@ -3316,6 +3346,66 @@ ${["a", "b", "c", "d", "e", "f"].map((id, i) => ` <div data-composition-id="$
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the classic provider of an eager inline module available at boot", async () => {
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html><html><head></head><body>
|
||||
<div data-composition-id="main" data-duration="60" data-width="1920" data-height="1080">
|
||||
<div data-composition-id="b" data-composition-src="b.html" data-start="30" data-duration="5"></div>
|
||||
<div data-composition-id="a" data-composition-src="a.html" data-start="0" data-duration="5"></div>
|
||||
</div></body></html>`,
|
||||
"b.html": `<template><div data-composition-id="b"><p>provider</p><script>
|
||||
window.__timelines = window.__timelines || {}; window.__timelines.b = gsap.timeline();
|
||||
</script></div></template>`,
|
||||
"a.html": `<template><div data-composition-id="a"><output class="answer"></output>
|
||||
<script type="module">document.querySelector(".answer").textContent = typeof window.__timelines.b;</script>
|
||||
</div></template>`,
|
||||
});
|
||||
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
|
||||
expect(doc.querySelector('div[data-hf-scene="b"]')?.hasAttribute("data-hf-scene-eager")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the other provider of a scene reader's shared authored alias eager", async () => {
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html><html><head></head><body>
|
||||
<div data-composition-id="main" data-duration="60" data-width="1920" data-height="1080">
|
||||
<div data-composition-id="b" data-composition-src="b.html" data-start="30" data-duration="5"></div>
|
||||
<div data-composition-id="b" data-composition-src="b.html" data-start="0" data-duration="5"></div>
|
||||
</div></body></html>`,
|
||||
"b.html": `<template><div data-composition-id="b"><output class="answer"></output><script>
|
||||
window.__timelines = window.__timelines || {};
|
||||
document.querySelector(".answer").textContent = typeof window.__timelines.b;
|
||||
window.__timelines.b = gsap.timeline();
|
||||
</script></div></template>`,
|
||||
});
|
||||
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
|
||||
const copies = [
|
||||
...doc.querySelectorAll('[data-hf-original-composition-id="b"][data-hf-scene]'),
|
||||
];
|
||||
expect(copies).toHaveLength(2);
|
||||
expect(copies.every((host) => host.hasAttribute("data-hf-scene-eager"))).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a root reader's provider eager through a comment after typeof's registry", async () => {
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html><html><head></head><body>
|
||||
<div data-composition-id="main" data-duration="60" data-width="1920" data-height="1080">
|
||||
<div data-composition-id="b" data-composition-src="b.html" data-start="30" data-duration="5"></div>
|
||||
</div><output id="answer"></output><script>
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.getElementById("answer").textContent = typeof window.__timelines /* availability */ .b;
|
||||
});</script></body></html>`,
|
||||
"b.html": `<template><div data-composition-id="b"><p>provider</p><script>
|
||||
window.__timelines = window.__timelines || {}; window.__timelines.b = gsap.timeline();
|
||||
</script></div></template>`,
|
||||
});
|
||||
const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
|
||||
expect(doc.querySelector('div[data-hf-scene="b"]')?.hasAttribute("data-hf-scene-eager")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps every scene an eager scene reads eager too, however far out it starts", async () => {
|
||||
const scene = (id: string, script: string) =>
|
||||
`<template id="${id}-template"><div data-composition-id="${id}"><p>${id}</p>
|
||||
|
||||
@@ -11,11 +11,12 @@ import {
|
||||
type CompositionStyle,
|
||||
} from "./scriptRuns";
|
||||
import {
|
||||
countPageRoot,
|
||||
executableScripts,
|
||||
isJavaScriptType,
|
||||
planCompositionAssembly,
|
||||
} from "./compositionAssembly";
|
||||
import { SCENE_PART_ATTR } from "../sceneParts";
|
||||
import { SCENE_FONTS_ATTR, SCENE_PART_ATTR } from "../sceneParts";
|
||||
import {
|
||||
ensureExternalScriptTag,
|
||||
readExternalScriptAttributes,
|
||||
@@ -53,6 +54,7 @@ import {
|
||||
import {
|
||||
buildVariablesByCompScript,
|
||||
dedupeFontFaceRules,
|
||||
hoistFontFaceRules,
|
||||
scopeCssToComposition,
|
||||
wrapInlineScriptWithErrorBoundary,
|
||||
scopedModulePrelude,
|
||||
@@ -554,6 +556,7 @@ function countBundledAuthoredCompositionIds(hosts: Element[]): Map<string, numbe
|
||||
if (!authoredCompositionId) continue;
|
||||
counts.set(authoredCompositionId, (counts.get(authoredCompositionId) || 0) + 1);
|
||||
}
|
||||
countPageRoot(counts, hosts);
|
||||
return counts;
|
||||
}
|
||||
|
||||
@@ -1406,13 +1409,20 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
if (srcset)
|
||||
el.setAttribute("srcset", rewriteSrcsetWithInlinedAssets(srcset, projectDir, inlineAssets));
|
||||
}
|
||||
// Before inlining, so postcss reads paths not font bytes; scene parts keep copies to swap alone.
|
||||
if (!options?.sceneParts) {
|
||||
const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
|
||||
const dedupedStyles = dedupeFontFaceRules(liveStyles.map((el) => el.textContent || ""));
|
||||
liveStyles.forEach((el, i) => {
|
||||
el.textContent = dedupedStyles[i] ?? "";
|
||||
});
|
||||
// Before inlining, so postcss reads paths not font bytes.
|
||||
const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
|
||||
const liveCss = liveStyles.map((el) => el.textContent || "");
|
||||
const { styles, faces } = options?.sceneParts
|
||||
? hoistFontFaceRules(liveCss)
|
||||
: { styles: dedupeFontFaceRules(liveCss), faces: [] };
|
||||
liveStyles.forEach((el, i) => {
|
||||
el.textContent = styles[i] ?? "";
|
||||
});
|
||||
if (faces.length > 0) {
|
||||
const holder = document.createElement("style");
|
||||
holder.setAttribute(SCENE_FONTS_ATTR, "");
|
||||
holder.textContent = faces.join("\n");
|
||||
document.head.prepend(holder);
|
||||
}
|
||||
for (const styleEl of document.querySelectorAll("style")) {
|
||||
styleEl.textContent = rewriteCssUrlsWithInlinedAssets(
|
||||
|
||||
@@ -1109,7 +1109,19 @@ describe("registryReads", () => {
|
||||
registryReads(
|
||||
'window.__timelines["a"] = tl; window.__timelines.b.progress(1); __timelines?.["c"]; __timelines?.d;',
|
||||
),
|
||||
).toEqual({ names: ["a", "b", "c", "d"], everyScene: false });
|
||||
).toEqual({ names: ["b", "c", "d"], everyScene: false });
|
||||
});
|
||||
it("keeps member reads through comment trivia without treating a bare typeof guard as a dependency", () => {
|
||||
for (const trivia of [" /* availability */ ", " // availability\n "]) {
|
||||
expect(registryReads(`typeof window.__timelines${trivia}.b`)).toEqual({
|
||||
names: ["b"],
|
||||
everyScene: false,
|
||||
});
|
||||
expect(registryReads(`typeof window.__timelines${trivia};`)).toEqual({
|
||||
names: [],
|
||||
everyScene: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
it("reads every scene when a read is not to one named key", () => {
|
||||
for (const script of [
|
||||
|
||||
@@ -85,16 +85,24 @@ const REGISTRY_SETUP_RE =
|
||||
const REGISTRY_KEY_RE =
|
||||
/^\s*(?:(?:\?\.)?\s*\[\s*(["'`])([\w-]+)\1\s*\]|\??\.\s*([A-Za-z_$][\w$]*))/;
|
||||
const REGISTRY_WRITE_RE = /^\s*\[[^\]]*\]\s*=(?!=)/;
|
||||
const leadingTrivia = (text: string) =>
|
||||
text.replace(/^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*(?:\r?\n|$))+/, "");
|
||||
|
||||
/** The scene ids a script reads from the timeline registry; `everyScene` when a read is not to one named key. */
|
||||
export function registryReads(script: string): { names: string[]; everyScene: boolean } {
|
||||
const rest = script.replace(REGISTRY_SETUP_RE, "");
|
||||
const rest = script.replace(REGISTRY_SETUP_RE, (setup: string, at: number) =>
|
||||
setup.startsWith("typeof") &&
|
||||
/^(?:\?\.|\.|\[)/.test(leadingTrivia(script.slice(at + setup.length)))
|
||||
? setup
|
||||
: "",
|
||||
);
|
||||
const names: string[] = [];
|
||||
for (const m of rest.matchAll(/__timelines\b/g)) {
|
||||
const after = rest.slice(m.index + m[0].length, m.index + m[0].length + 200);
|
||||
const after = leadingTrivia(rest.slice(m.index + m[0].length, m.index + m[0].length + 200));
|
||||
const key = REGISTRY_KEY_RE.exec(after);
|
||||
if (key) names.push(key[2] ?? key[3] ?? "");
|
||||
else if (!REGISTRY_WRITE_RE.test(after)) return { names, everyScene: true };
|
||||
if (key) {
|
||||
if (!/^\s*=(?!=)/.test(after.slice(key[0].length))) names.push(key[2] ?? key[3] ?? "");
|
||||
} else if (!REGISTRY_WRITE_RE.test(after)) return { names, everyScene: true };
|
||||
}
|
||||
return { names, everyScene: false };
|
||||
}
|
||||
@@ -325,6 +333,7 @@ export interface InlineSubCompositionsResult {
|
||||
export interface SceneReads {
|
||||
hosts: Map<string, Element>;
|
||||
literals: Map<string, Set<string>>;
|
||||
registryNames: Map<string, Set<string>>;
|
||||
/** Scenes whose scripts read the timeline registry by a key no analysis can name. */
|
||||
readEveryScene: Set<string>;
|
||||
}
|
||||
@@ -393,6 +402,7 @@ export function inlineSubCompositions(
|
||||
|
||||
const sceneHosts = new Map<string, Element>();
|
||||
const sceneLiterals = new Map<string, Set<string>>();
|
||||
const registryNames = new Map<string, Set<string>>();
|
||||
const readEveryScene = new Set<string>();
|
||||
const queue = hosts.map((element) => ({
|
||||
element,
|
||||
@@ -569,13 +579,11 @@ export function inlineSubCompositions(
|
||||
SCENE_EAGER_ATTR,
|
||||
() => unknownCode ?? (externalSrc ? null : sceneScriptEagerReason(authored)),
|
||||
);
|
||||
if (scene && !externalSrc && !unknownCode) {
|
||||
if (scene && !externalSrc && type !== "importmap") {
|
||||
const { names, everyScene } = registryReads(authored);
|
||||
const literals = [...authored.matchAll(STRING_LITERAL_RE)].map((m) => m[2] ?? "");
|
||||
sceneLiterals.set(
|
||||
scene,
|
||||
new Set([...(sceneLiterals.get(scene) ?? []), ...literals, ...names]),
|
||||
);
|
||||
sceneLiterals.set(scene, new Set([...(sceneLiterals.get(scene) ?? []), ...literals]));
|
||||
registryNames.set(scene, new Set([...(registryNames.get(scene) ?? []), ...names]));
|
||||
if (everyScene) readEveryScene.add(scene);
|
||||
}
|
||||
if (type === "importmap") {
|
||||
@@ -787,14 +795,14 @@ export function inlineSubCompositions(
|
||||
variablesByComp,
|
||||
importMaps,
|
||||
moduleScripts,
|
||||
sceneReads: { hosts: sceneHosts, literals: sceneLiterals, readEveryScene },
|
||||
sceneReads: { hosts: sceneHosts, literals: sceneLiterals, registryNames, readEveryScene },
|
||||
};
|
||||
}
|
||||
|
||||
/** A script that names a scene's composition id reads what that scene's script left, so the scene runs at boot whenever
|
||||
* its reader does. Root scripts always run at boot; run this after every other eager mark. */
|
||||
export function keepScenesReadAtBootEager(
|
||||
{ hosts: sceneHosts, literals: sceneLiterals, readEveryScene }: SceneReads,
|
||||
{ hosts: sceneHosts, literals: sceneLiterals, registryNames, readEveryScene }: SceneReads,
|
||||
rootScripts: string[],
|
||||
): void {
|
||||
// A renamed duplicate (`b__hf1`) still registers under the id its author gave it.
|
||||
@@ -809,9 +817,11 @@ export function keepScenesReadAtBootEager(
|
||||
]),
|
||||
);
|
||||
const ids = new Map([...sceneHosts].map(([scene, host]) => [scene, idsOf(host)]));
|
||||
const namedBy = (literals: Iterable<string>, own = new Set<string>()) => {
|
||||
const named = [...literals].filter((l) => l && !own.has(l));
|
||||
return [...ids].filter(([, other]) => named.some((l) => other.has(l))).map(([id]) => id);
|
||||
const namedBy = (literals: Iterable<string>, reader?: string) => {
|
||||
const named = [...literals].filter(Boolean);
|
||||
return [...ids]
|
||||
.filter(([id, other]) => id !== reader && named.some((l) => other.has(l)))
|
||||
.map(([id]) => id);
|
||||
};
|
||||
const ROOT = "a root script";
|
||||
const rootReads = rootScripts.map(registryReads);
|
||||
@@ -823,9 +833,15 @@ export function keepScenesReadAtBootEager(
|
||||
const readsOf = (reader: string) => {
|
||||
if (reader === ROOT ? rootReadsEveryScene : readEveryScene.has(reader))
|
||||
return [...ids.keys()].filter((id) => id !== reader);
|
||||
return reader === ROOT
|
||||
? namedBy(rootLiterals)
|
||||
: namedBy(sceneLiterals.get(reader) ?? [], ids.get(reader));
|
||||
if (reader === ROOT) return namedBy(rootLiterals);
|
||||
const own = ids.get(reader);
|
||||
return namedBy(
|
||||
[
|
||||
...[...(sceneLiterals.get(reader) ?? [])].filter((name) => !own?.has(name)),
|
||||
...(registryNames.get(reader) ?? []),
|
||||
],
|
||||
reader,
|
||||
);
|
||||
};
|
||||
for (const [scene, host] of sceneHosts) {
|
||||
const named = readsOf(scene)[0];
|
||||
|
||||
@@ -87,4 +87,23 @@ describe("addScenePartsManifest", () => {
|
||||
expect(ba.scenes).toEqual(ab.scenes);
|
||||
expect(ba.shared).not.toBe(ab.shared);
|
||||
});
|
||||
|
||||
it("leaves the shared fonts style out of the shared hash, so a scene that brings a font still swaps", () => {
|
||||
const withFonts = (faces: string) =>
|
||||
doc("one", "<h1>t</h1>").replace(
|
||||
"<head>",
|
||||
`<head><style data-hf-scene-fonts>${faces}</style>`,
|
||||
);
|
||||
const one = manifestOf(
|
||||
addScenePartsManifest(withFonts('@font-face{font-family:"A";src:url(a.woff2)}')),
|
||||
);
|
||||
const two = manifestOf(
|
||||
addScenePartsManifest(
|
||||
withFonts(
|
||||
'@font-face{font-family:"A";src:url(a.woff2)}\n@font-face{font-family:"B";src:url(b.woff2)}',
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(two.shared).toBe(one.shared);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { SCENE_PART_ATTR, SCENE_PARTS_META, type SceneParts } from "../sceneParts";
|
||||
import {
|
||||
SCENE_FONTS_ATTR,
|
||||
SCENE_PART_ATTR,
|
||||
SCENE_PARTS_META,
|
||||
type SceneParts,
|
||||
} from "../sceneParts";
|
||||
import { injectTagsAtHeadStart, parseHTMLContent } from "./htmlDocument";
|
||||
|
||||
const hash = (text: string) => createHash("sha1").update(text).digest("hex").slice(0, 16);
|
||||
@@ -20,7 +25,10 @@ export function addScenePartsManifest(html: string, ignore: readonly string[] =
|
||||
// A marker keeps each part's place in `shared`, so moving or reordering a scene changes it.
|
||||
for (const el of parts)
|
||||
el.replaceWith(doc.createComment(`hf-scene:${el.getAttribute(SCENE_PART_ATTR)}`));
|
||||
for (const el of ignore.flatMap((sel) => [...doc.querySelectorAll(sel)])) el.remove();
|
||||
for (const el of [...ignore, `style[${SCENE_FONTS_ATTR}]`].flatMap((sel) => [
|
||||
...doc.querySelectorAll(sel),
|
||||
]))
|
||||
el.remove();
|
||||
const manifest: SceneParts = {
|
||||
shared: hash(doc.toString()),
|
||||
scenes: Object.fromEntries([...byScene].map(([scene, html]) => [scene, hash(html.join("\n"))])),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Integer rates the distributed renderer (Lambda, Cloud Run) accepts; fractional fps renders in-process only. */
|
||||
export const DISTRIBUTED_FPS = [24, 25, 30, 60] as const;
|
||||
export type DistributedFps = (typeof DISTRIBUTED_FPS)[number];
|
||||
|
||||
export function isDistributedFps(value: unknown): value is DistributedFps {
|
||||
return (DISTRIBUTED_FPS as readonly unknown[]).includes(value);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ function googleStylesheetFamilies(urlText: string): string[] {
|
||||
}
|
||||
|
||||
function importUrls(css: string): string[] {
|
||||
if (!/@import/i.test(css)) return [];
|
||||
let root: postcss.Root;
|
||||
try {
|
||||
root = postcss.parse(css);
|
||||
|
||||
@@ -63,7 +63,7 @@ describe("system font capture — allowSystemFontCapture option", () => {
|
||||
// allowSystemFontCapture intentionally omitted
|
||||
});
|
||||
expect(result.includes("data-hyperframes-deterministic-fonts")).toBe(false);
|
||||
}, 15_000); // The system font locator runs system_profiler on macOS which can take >5s.
|
||||
});
|
||||
});
|
||||
|
||||
describe("system font capture — integration (macOS only)", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import postcss from "postcss";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -50,6 +51,17 @@ describe("existing font-face recognition", () => {
|
||||
const html = `<html><head><style>${css}</style></head><body>Hello</body></html>`;
|
||||
expect(await injectDeterministicFontFaces(html, { allowSystemFontCapture: false })).toBe(html);
|
||||
});
|
||||
|
||||
it("never parses a stylesheet that has no font-family or custom property", async () => {
|
||||
const parse = vi.spyOn(postcss, "parse");
|
||||
try {
|
||||
const html = `<html><head><style>${"@font-face{{".repeat(1_000)}</style></head><body>Hello</body></html>`;
|
||||
await injectDeterministicFontFaces(html, { allowSystemFontCapture: false });
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
parse.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Google Fonts CSS request caching", () => {
|
||||
|
||||
@@ -246,6 +246,7 @@ export type FontFamilyDeclaration = {
|
||||
};
|
||||
|
||||
function collectCssCustomProperties(css: string, customProperties: Map<string, string>): void {
|
||||
if (!css.includes("--")) return;
|
||||
const root = parseCssRoot(css);
|
||||
if (!root) return;
|
||||
root.walkDecls((decl) => {
|
||||
@@ -272,6 +273,7 @@ function* iterateCssRootFontFamilyDeclarations(
|
||||
}
|
||||
|
||||
function* iterateCssFontFamilyDeclarations(css: string): Generator<FontFamilyDeclaration> {
|
||||
if (!/font-family/i.test(css)) return;
|
||||
const root = parseCssRoot(css);
|
||||
if (!root) return;
|
||||
yield* iterateCssRootFontFamilyDeclarations(root);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const execFileSync = vi.hoisted(() => vi.fn(() => ""));
|
||||
vi.mock("node:child_process", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("node:child_process")>()),
|
||||
execFileSync,
|
||||
}));
|
||||
vi.mock("node:os", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("node:os")>()),
|
||||
platform: () => "darwin",
|
||||
}));
|
||||
|
||||
const { locateSystemFont, locateSystemFontVariants } = await import("./systemFontLocator");
|
||||
|
||||
describe("systemFontLocator on macOS", () => {
|
||||
// system_profiler SPFontsDataType takes about 10 s, so every lookup would block a compile for its timeout.
|
||||
it("finds fonts without spawning a process", () => {
|
||||
locateSystemFontVariants("Hf Darwin Probe");
|
||||
locateSystemFont("Hf Darwin Probe");
|
||||
expect(execFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
SYSTEM_FONT_SIZE_LIMIT,
|
||||
} from "./systemFontLocator";
|
||||
|
||||
describe("systemFontLocator", { timeout: 15_000 }, () => {
|
||||
describe("systemFontLocator", () => {
|
||||
beforeAll(() => {
|
||||
clearSystemFontCache();
|
||||
});
|
||||
|
||||
@@ -4,7 +4,6 @@ import { homedir, platform } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
export const SYSTEM_FONT_SIZE_LIMIT = 5 * 1024 * 1024;
|
||||
const PROFILER_TIMEOUT_MS = 5000;
|
||||
const FC_MATCH_TIMEOUT_MS = 3000;
|
||||
|
||||
export type FontFileFormat = "ttf" | "otf" | "woff2" | "woff" | "ttc";
|
||||
@@ -221,70 +220,6 @@ function pickBestCandidate(candidates: FontCandidate[]): LocatedFont | null {
|
||||
return { path: best.path, format: best.format };
|
||||
}
|
||||
|
||||
type SystemProfilerEntry = {
|
||||
family: string;
|
||||
path: string;
|
||||
format: FontFileFormat;
|
||||
isRegular: boolean;
|
||||
};
|
||||
|
||||
let profilerCache: Map<string, SystemProfilerEntry[]> | null = null;
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
function getSystemProfilerIndex(): Map<string, SystemProfilerEntry[]> {
|
||||
if (profilerCache) return profilerCache;
|
||||
profilerCache = new Map();
|
||||
if (platform() !== "darwin") return profilerCache;
|
||||
|
||||
try {
|
||||
const raw = execFileSync("system_profiler", ["SPFontsDataType", "-json"], {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 12 * 1024 * 1024,
|
||||
timeout: PROFILER_TIMEOUT_MS,
|
||||
});
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed?.SPFontsDataType || !Array.isArray(parsed.SPFontsDataType)) return profilerCache;
|
||||
|
||||
for (const fontEntry of parsed.SPFontsDataType) {
|
||||
if (!fontEntry?.typefaces || !Array.isArray(fontEntry.typefaces)) continue;
|
||||
for (const typeface of fontEntry.typefaces) {
|
||||
if (!typeface) continue;
|
||||
const family = typeface.family ?? typeface.fullname ?? typeface._name;
|
||||
if (typeof family !== "string") continue;
|
||||
const filePath = typeface.path;
|
||||
if (typeof filePath !== "string" || !FONT_EXT_RE.test(filePath)) continue;
|
||||
const normalized = normalizeName(family);
|
||||
const ext = filePath.match(FONT_EXT_RE)?.[1] ?? "ttf";
|
||||
const entry: SystemProfilerEntry = {
|
||||
family: normalized,
|
||||
path: filePath,
|
||||
format: extensionToFormat(ext),
|
||||
isRegular: isRegularWeight(filePath),
|
||||
};
|
||||
const list = profilerCache.get(normalized) ?? [];
|
||||
list.push(entry);
|
||||
profilerCache.set(normalized, list);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// system_profiler unavailable
|
||||
}
|
||||
|
||||
return profilerCache;
|
||||
}
|
||||
|
||||
function locateViaSystemProfiler(targetFamily: string): LocatedFont | null {
|
||||
const index = getSystemProfilerIndex();
|
||||
const entries = index.get(targetFamily);
|
||||
if (!entries || entries.length === 0) return null;
|
||||
|
||||
const candidates: FontCandidate[] = entries
|
||||
.filter((e) => isRegularFile(e.path) && isPathBounded(e.path))
|
||||
.map((e) => ({ path: e.path, format: e.format, isRegular: e.isRegular }));
|
||||
|
||||
return pickBestCandidate(candidates);
|
||||
}
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
function locateViaFcMatch(targetFamily: string): LocatedFont | null {
|
||||
if (platform() !== "linux") return null;
|
||||
@@ -311,13 +246,7 @@ export function locateSystemFont(family: string): LocatedFont | null {
|
||||
const cached = cache.get(normalized);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let result: LocatedFont | null = null;
|
||||
|
||||
result = locateViaSystemProfiler(normalized);
|
||||
|
||||
if (!result) {
|
||||
result = locateViaFcMatch(normalized);
|
||||
}
|
||||
let result = locateViaFcMatch(normalized);
|
||||
|
||||
if (!result) {
|
||||
const allCandidates: FontCandidate[] = [];
|
||||
@@ -373,18 +302,6 @@ export function locateSystemFontVariants(family: string): LocatedFontVariant[] {
|
||||
if (!normalized) return [];
|
||||
|
||||
const variants: LocatedFontVariant[] = [];
|
||||
|
||||
const profilerIndex = getSystemProfilerIndex();
|
||||
const profilerEntries = profilerIndex.get(normalized);
|
||||
if (profilerEntries && profilerEntries.length > 0) {
|
||||
for (const e of profilerEntries) {
|
||||
if (!isRegularFile(e.path) || !isPathBounded(e.path)) continue;
|
||||
const { weight, style } = inferWeightAndStyle(e.path);
|
||||
variants.push({ path: e.path, format: e.format, weight, style });
|
||||
}
|
||||
if (variants.length > 0) return dedupeVariants(variants);
|
||||
}
|
||||
|
||||
const allCandidates: FontCandidate[] = [];
|
||||
for (const dir of fontDirectories()) {
|
||||
allCandidates.push(...collectCandidatesFromDir(dir, normalized));
|
||||
@@ -405,13 +322,7 @@ function dedupeVariants(variants: LocatedFontVariant[]): LocatedFontVariant[] {
|
||||
return Array.from(seen.values());
|
||||
}
|
||||
|
||||
export function getSystemProfilerFamilies(): string[] {
|
||||
const index = getSystemProfilerIndex();
|
||||
return Array.from(index.keys());
|
||||
}
|
||||
|
||||
export function clearSystemFontCache(): void {
|
||||
cache.clear();
|
||||
profilerCache = null;
|
||||
allowedDirsCache = null;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,12 @@ describe("@hyperframes/core public API exports", () => {
|
||||
"portrait-4k",
|
||||
"square",
|
||||
"square-4k",
|
||||
"landscape-720p",
|
||||
"portrait-720p",
|
||||
"square-720p",
|
||||
"landscape-480p",
|
||||
"portrait-480p",
|
||||
"square-480p",
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -81,6 +81,8 @@ export {
|
||||
getDefaultStageZoom,
|
||||
} from "./core.types";
|
||||
|
||||
export { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "./distributedFps";
|
||||
|
||||
// Templates
|
||||
export { generateBaseHtml, getStageStyles } from "./templates/base";
|
||||
export {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseFps, fpsToNumber, fpsToFfmpegArg } from "./core.types";
|
||||
import { fpsToFfmpegArg, fpsToNumber, parseFps } from "./core.types";
|
||||
import { DISTRIBUTED_FPS, isDistributedFps } from "./distributedFps";
|
||||
|
||||
describe("parseFps — integer forms", () => {
|
||||
it("parses integer string '30' as { num: 30, den: 1 }", () => {
|
||||
@@ -156,3 +157,16 @@ describe("fpsToNumber + fpsToFfmpegArg + frame interval math", () => {
|
||||
expect(fpsToFfmpegArg({ num: 60000, den: 1001 })).toBe("60000/1001");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isDistributedFps", () => {
|
||||
it("accepts exactly the integer rates the distributed renderer supports", () => {
|
||||
expect(DISTRIBUTED_FPS).toEqual([24, 25, 30, 60]);
|
||||
for (const n of DISTRIBUTED_FPS) expect(isDistributedFps(n)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects other rates, fractions and non-numbers", () => {
|
||||
for (const v of [0, 23.976, 29.97, 48, 50, 120, "30", null, undefined]) {
|
||||
expect(isDistributedFps(v)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import gsap from "gsap";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createGsapAdapter, rerenderGsapTimelineAt, seekGsapTimeline } from "./gsap";
|
||||
import type { GsapStructureKey } from "./gsap";
|
||||
import type { RuntimeTimelineLike } from "../types";
|
||||
|
||||
// Every 0.1 s: hide all three frames, then show one, as frame-by-frame films do.
|
||||
@@ -578,6 +579,135 @@ describe("seekGsapTimeline", () => {
|
||||
seekGsapTimeline(film.timeline, 0.1, false);
|
||||
expect(film.calls()).toBe(1);
|
||||
});
|
||||
|
||||
const structures = new WeakMap<object, GsapStructureKey>();
|
||||
const structureOf = (timeline: object) => {
|
||||
if (!structures.has(timeline)) structures.set(timeline, { owner: timeline, version: "1" });
|
||||
return structures.get(timeline)!;
|
||||
};
|
||||
// What init's root seek does: the shared seek, then its own redraw unless the seek already redrew.
|
||||
const rootSeek = (timeline: RuntimeTimelineLike, t: number) => {
|
||||
if (!seekGsapTimeline(timeline, t, false, structureOf(timeline)))
|
||||
rerenderGsapTimelineAt(timeline as never, t, structureOf(timeline));
|
||||
};
|
||||
const sceneSeek = (timeline: RuntimeTimelineLike, t: number) =>
|
||||
seekGsapTimeline(timeline, t, false, structureOf(timeline));
|
||||
|
||||
// A scene that reveals its content with steps at 0, as scenes built from template clones do.
|
||||
function revealedAtZero() {
|
||||
const field = document.body.appendChild(document.createElement("div"));
|
||||
const timeline = gsap.timeline({ paused: true });
|
||||
timeline.set(field, { visibility: "hidden" }, 0);
|
||||
timeline.set(field, { visibility: "visible" }, 0);
|
||||
timeline.to(field, { x: 100, duration: 2 }, 0);
|
||||
timeline.set(field, { visibility: "hidden" }, 1.5);
|
||||
return { field, timeline: timeline as unknown as RuntimeTimelineLike };
|
||||
}
|
||||
|
||||
it("shows a scene's steps at 0 after the playhead comes back to 0 from later", () => {
|
||||
const scene = revealedAtZero();
|
||||
sceneSeek(scene.timeline, 1);
|
||||
sceneSeek(scene.timeline, 0);
|
||||
expect(scene.field.style.visibility).toBe("visible");
|
||||
sceneSeek(scene.timeline, 0.5);
|
||||
expect(scene.field.style.visibility).toBe("visible");
|
||||
});
|
||||
|
||||
it("shows a nested scene's steps at 0 after its parent parks it there from later", () => {
|
||||
const scene = revealedAtZero();
|
||||
const root = gsap
|
||||
.timeline({ paused: true })
|
||||
.add(scene.timeline as unknown as gsap.core.Timeline, 6);
|
||||
root.set({}, {}, 12);
|
||||
// What a runtime seek does: the root, then the scene at its own time, held at 0 before it starts.
|
||||
const seekBoth = (t: number) => {
|
||||
root.totalTime(t);
|
||||
sceneSeek(scene.timeline, Math.max(0, t - 6));
|
||||
};
|
||||
seekBoth(8);
|
||||
seekBoth(5.9);
|
||||
seekBoth(6.5);
|
||||
expect(scene.field.style.visibility).toBe("visible");
|
||||
});
|
||||
|
||||
it("shows two steps on one later time in authored order after the playhead comes back onto it", () => {
|
||||
const word = document.body.appendChild(document.createElement("span"));
|
||||
const timeline = gsap.timeline({ paused: true });
|
||||
timeline.set(word, { visibility: "hidden" }, 1).set(word, { visibility: "visible" }, 1);
|
||||
timeline.to({}, { duration: 3 }, 0);
|
||||
const scene = timeline as unknown as RuntimeTimelineLike;
|
||||
sceneSeek(scene, 2);
|
||||
sceneSeek(scene, 1);
|
||||
expect(word.style.visibility).toBe("visible");
|
||||
sceneSeek(scene, 1.2);
|
||||
expect(word.style.visibility).toBe("visible");
|
||||
});
|
||||
|
||||
it("keeps a scene's steps at 0 through the root's redraw at 0 on every seek", () => {
|
||||
const scene = revealedAtZero();
|
||||
rootSeek(scene.timeline, 1);
|
||||
rootSeek(scene.timeline, 0);
|
||||
rootSeek(scene.timeline, 0);
|
||||
expect(scene.field.style.visibility).toBe("visible");
|
||||
});
|
||||
|
||||
const keyframeForms: Record<string, gsap.TweenVars> = {
|
||||
"a keyframes array": { keyframes: [{ x: 10 }, { x: 100 }] },
|
||||
"percent keyframes": { keyframes: { "0%": { x: 5 }, "100%": { x: 60 } } },
|
||||
};
|
||||
const keyframedAtZero = (form: string) => {
|
||||
const o = { x: 0 };
|
||||
const timeline = gsap.timeline({ paused: true });
|
||||
timeline.to(o, { ...keyframeForms[form], duration: 1 }, 0).to({}, { duration: 3 }, 0);
|
||||
return { o, timeline: timeline as unknown as RuntimeTimelineLike };
|
||||
};
|
||||
const landings: [string, number[]][] = [
|
||||
["root", [2, 0]],
|
||||
["root", [0.5, 0]],
|
||||
["root", [0.5, 0, 0, 0]],
|
||||
["scene", [0.5, 0, 0, 1 / 30]],
|
||||
["scene", [1, 0]],
|
||||
];
|
||||
|
||||
it.each(
|
||||
Object.keys(keyframeForms).flatMap((form) =>
|
||||
landings.map(([path, times]) => ({ form, path, times })),
|
||||
),
|
||||
)("draws $form starting at 0 as plain GSAP does when the $path seeks $times", (landing) => {
|
||||
const ours = keyframedAtZero(landing.form);
|
||||
const plain = keyframedAtZero(landing.form);
|
||||
for (const t of landing.times) {
|
||||
(landing.path === "root" ? rootSeek : sceneSeek)(ours.timeline, t);
|
||||
plain.timeline.totalTime!(t, false);
|
||||
expect(ours.o.x).toBeCloseTo(plain.o.x, 6);
|
||||
}
|
||||
});
|
||||
|
||||
it("fires a call on the landing time as often as plain GSAP across back-and-forth seeks", () => {
|
||||
const fires = (ours: boolean) => {
|
||||
let calls = 0;
|
||||
const word = document.body.appendChild(document.createElement("span"));
|
||||
const timeline = gsap.timeline({ paused: true }).to({}, { duration: 3 }, 0);
|
||||
timeline.set(word, { visibility: "hidden" }, 1).call(() => void calls++, [], 1);
|
||||
timeline.set(word, { visibility: "visible" }, 1);
|
||||
const scene = timeline as unknown as RuntimeTimelineLike;
|
||||
for (const t of [2, 1, 1.5, 1, 0.5, 1, 2, 1, 1]) {
|
||||
if (ours) sceneSeek(scene, t);
|
||||
else timeline.totalTime(t, false);
|
||||
}
|
||||
return calls;
|
||||
};
|
||||
expect(fires(true)).toBe(fires(false));
|
||||
});
|
||||
|
||||
it("never redraws a whole scene for a backward landing, on steps or between them", () => {
|
||||
const scene = revealedAtZero();
|
||||
sceneSeek(scene.timeline, 2);
|
||||
expect(sceneSeek(scene.timeline, 1.5)).toBe(false);
|
||||
expect(scene.field.style.visibility).toBe("hidden");
|
||||
sceneSeek(scene.timeline, 2);
|
||||
expect(sceneSeek(scene.timeline, 0.37)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rerenderGsapTimelineAt with a structure key", () => {
|
||||
|
||||
@@ -33,10 +33,7 @@ export function rerenderGsapTimelineAt(
|
||||
);
|
||||
for (const [child] of skipped) child._ts = 0;
|
||||
try {
|
||||
const below = t >= REDRAW_STEP;
|
||||
timeline.totalTime(below ? t - REDRAW_STEP : t + REDRAW_STEP, true);
|
||||
primeTweensStartingAt(children, t, below ? REDRAW_STEP : 0);
|
||||
timeline.totalTime(t, true);
|
||||
renderOntoInAuthoredOrder(timeline, children, t, structure);
|
||||
} finally {
|
||||
for (const [child, timeScale] of skipped) child._ts = timeScale;
|
||||
for (const [parent, dur, tDur, end, dirty] of lengths) {
|
||||
@@ -50,6 +47,31 @@ export function rerenderGsapTimelineAt(
|
||||
}
|
||||
}
|
||||
|
||||
function renderOntoInAuthoredOrder(
|
||||
timeline: Parameters<typeof rerenderGsapTimelineAt>[0],
|
||||
children: unknown[],
|
||||
t: number,
|
||||
structure: GsapStructureKey | undefined,
|
||||
): void {
|
||||
const below = t >= REDRAW_STEP;
|
||||
timeline.totalTime(below ? t - REDRAW_STEP : t + REDRAW_STEP, true);
|
||||
primeTweensStartingAt(children, t, below ? REDRAW_STEP : 0);
|
||||
timeline.totalTime(t, true);
|
||||
if (!below && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);
|
||||
}
|
||||
|
||||
function reapplyStepsInAuthoredOrder(
|
||||
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
|
||||
structure: GsapStructureKey,
|
||||
t: number,
|
||||
): void {
|
||||
for (const step of stepsAt(timeline, structure, t)) {
|
||||
const { ratio, _zTime, _act } = step;
|
||||
step.render(0, true, true);
|
||||
Object.assign(step, { ratio, _zTime, _act });
|
||||
}
|
||||
}
|
||||
|
||||
type GsapRenderState = { _initted?: number };
|
||||
|
||||
function gsapNeverRendered(timeline: RuntimeTimelineLike): boolean {
|
||||
@@ -68,14 +90,16 @@ export function seekGsapTimeline(
|
||||
timeline: RuntimeTimelineLike,
|
||||
t: number,
|
||||
suppressEvents: boolean,
|
||||
structure?: GsapStructureKey,
|
||||
): boolean {
|
||||
if (typeof timeline.totalTime !== "function") {
|
||||
timeline.seek(t, suppressEvents);
|
||||
return false;
|
||||
}
|
||||
const gsapSkipsRenderInPlace = Number(timeline.totalTime()) === t;
|
||||
const from = Number(timeline.totalTime());
|
||||
timeline.totalTime(t, suppressEvents);
|
||||
if (!gsapSkipsRenderInPlace || !gsapNeverRendered(timeline)) return false;
|
||||
if (t < from && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);
|
||||
if (from !== t || !gsapNeverRendered(timeline)) return false;
|
||||
rerenderGsapTimelineAt(
|
||||
{
|
||||
totalTime: timeline.totalTime.bind(timeline),
|
||||
@@ -83,6 +107,7 @@ export function seekGsapTimeline(
|
||||
getChildren: timeline.getChildren?.bind(timeline),
|
||||
},
|
||||
t,
|
||||
structure,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -119,6 +144,10 @@ function childrenStartingAfter(
|
||||
|
||||
type GsapLandingMarks = { ratio: number; _zTime?: number; _act?: number };
|
||||
|
||||
type GsapStep = GsapLandingMarks & {
|
||||
render: (totalTime: number, suppressEvents: boolean, force: boolean) => unknown;
|
||||
};
|
||||
|
||||
function childrenWithLandingMarksIn(timeline: {
|
||||
getChildren?: RuntimeTimelineLike["getChildren"];
|
||||
}): GsapLandingMarks[] {
|
||||
@@ -184,17 +213,39 @@ function firstPointFrom(points: PlacedMarks["points"], time: number): number {
|
||||
return lo;
|
||||
}
|
||||
|
||||
function placedLandingMarks(
|
||||
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
|
||||
structure: GsapStructureKey,
|
||||
): PlacedMarks {
|
||||
let placed = landingMarksCache.get(structure.owner);
|
||||
if (placed?.version !== structure.version) {
|
||||
placed = placeLandingMarks(timeline, structure);
|
||||
landingMarksCache.set(structure.owner, placed);
|
||||
}
|
||||
return placed;
|
||||
}
|
||||
|
||||
function stepsAt(
|
||||
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
|
||||
structure: GsapStructureKey,
|
||||
t: number,
|
||||
): GsapStep[] {
|
||||
const { points } = placedLandingMarks(timeline, structure);
|
||||
const steps: GsapStep[] = [];
|
||||
for (let i = firstPointFrom(points, t - PLAYHEAD_FLOAT_NOISE); i < points.length; i++) {
|
||||
if (points[i]!.at > t + PLAYHEAD_FLOAT_NOISE) break;
|
||||
steps.push(points[i]!.mark as GsapStep);
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
function landingMarksOf(
|
||||
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
|
||||
structure: GsapStructureKey | undefined,
|
||||
t: number,
|
||||
): GsapLandingMarks[] {
|
||||
if (!structure) return childrenWithLandingMarksIn(timeline);
|
||||
let placed = landingMarksCache.get(structure.owner);
|
||||
if (placed?.version !== structure.version) {
|
||||
placed = placeLandingMarks(timeline, structure);
|
||||
landingMarksCache.set(structure.owner, placed);
|
||||
}
|
||||
const placed = placedLandingMarks(timeline, structure);
|
||||
const { points } = placed;
|
||||
const near = [...placed.always];
|
||||
const last = t + LANDING_MARK_REACH;
|
||||
|
||||
@@ -21,6 +21,7 @@ import { swallow } from "../diagnostics";
|
||||
let _lastDispatchedTime = -1;
|
||||
type SeekCompletionResult = { status: "fulfilled" } | { status: "rejected"; reason: unknown };
|
||||
let _pendingCompletions = new Set<Promise<SeekCompletionResult>>();
|
||||
let _videoFrameCompletions = new WeakSet<Promise<SeekCompletionResult>>();
|
||||
let _pendingFailure: { reason: unknown } | undefined;
|
||||
let _activeCompletionBarriers = 0;
|
||||
|
||||
@@ -62,11 +63,12 @@ function dispatch(time: number): void {
|
||||
* its preview-side capture here, so the CLI seek paths that already await this
|
||||
* barrier wait for a `self` chain's paint instead of racing it.
|
||||
*/
|
||||
export function registerSeekCompletion(promise: Promise<unknown>): void {
|
||||
export function registerSeekCompletion(promise: Promise<unknown>, kind?: "video-frame"): void {
|
||||
const completion = promise
|
||||
.then<SeekCompletionResult>(() => ({ status: "fulfilled" }))
|
||||
.catch<SeekCompletionResult>((reason: unknown) => ({ status: "rejected", reason }));
|
||||
_pendingCompletions.add(completion);
|
||||
if (kind === "video-frame") _videoFrameCompletions.add(completion);
|
||||
void completion.then((result) => {
|
||||
if (!_pendingCompletions.delete(completion)) return;
|
||||
if (result.status === "rejected" && _pendingFailure === undefined) {
|
||||
@@ -100,15 +102,20 @@ export function isSeekCompletionBarrierActive(): boolean {
|
||||
return _activeCompletionBarriers > 0;
|
||||
}
|
||||
|
||||
export async function waitForSeekCompletion(): Promise<void> {
|
||||
/** `videoFrames: false` skips only the video-frame holds: a geometry read needs every other completion. */
|
||||
export async function waitForSeekCompletion(options?: { videoFrames?: boolean }): Promise<void> {
|
||||
const awaited = () =>
|
||||
[..._pendingCompletions].filter(
|
||||
(completion) => options?.videoFrames !== false || !_videoFrameCompletions.has(completion),
|
||||
);
|
||||
_activeCompletionBarriers += 1;
|
||||
let failed = _pendingFailure;
|
||||
try {
|
||||
// Let concurrently started barriers snapshot the same retained failure
|
||||
// before either one consumes it.
|
||||
await Promise.resolve();
|
||||
while (_pendingCompletions.size > 0) {
|
||||
const results = await Promise.all([..._pendingCompletions]);
|
||||
for (let pending = awaited(); pending.length > 0; pending = awaited()) {
|
||||
const results = await Promise.all(pending);
|
||||
const rejected = results.find((result) => result.status === "rejected");
|
||||
if (failed === undefined && rejected?.status === "rejected") {
|
||||
failed = { reason: rejected.reason };
|
||||
@@ -131,6 +138,7 @@ export async function waitForSeekCompletion(): Promise<void> {
|
||||
export function resetSeekDispatchState(): void {
|
||||
_lastDispatchedTime = -1;
|
||||
_pendingCompletions = new Set();
|
||||
_videoFrameCompletions = new WeakSet();
|
||||
_pendingFailure = undefined;
|
||||
_activeCompletionBarriers = 0;
|
||||
}
|
||||
|
||||
@@ -697,6 +697,30 @@ describe("loadCompositions external hosts", () => {
|
||||
expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
||||
});
|
||||
|
||||
it("gives a mount that shares the page root's id its own runtime id", async () => {
|
||||
const root = document.createElement("div");
|
||||
root.setAttribute("data-composition-id", "main");
|
||||
document.body.appendChild(root);
|
||||
const host = document.createElement("div");
|
||||
host.setAttribute("data-composition-src", "https://example.com/scene.html");
|
||||
host.setAttribute("data-composition-id", "main");
|
||||
root.appendChild(host);
|
||||
vi.spyOn(globalThis, "fetch").mockImplementation(
|
||||
async () =>
|
||||
new Response(
|
||||
`<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><h1>Scene</h1></div></body></html>`,
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
await loadFixture();
|
||||
|
||||
expect(root.getAttribute("data-composition-id")).toBe("main");
|
||||
expect(host.getAttribute("data-composition-id")).toBe("main__hf1");
|
||||
expect(host.getAttribute("data-hf-original-composition-id")).toBe("main");
|
||||
expect(host.querySelector("h1")?.textContent).toBe("Scene");
|
||||
});
|
||||
|
||||
it("normalizes a runtime composition id back to the authored id when only one host remains", async () => {
|
||||
const hostA = document.createElement("div");
|
||||
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
refreshSvgSelectorAliases,
|
||||
} from "../compiler/svgSelectorAliases";
|
||||
import {
|
||||
countPageRoot,
|
||||
planCompositionAssembly,
|
||||
extractedCompositionAssets,
|
||||
} from "../compiler/compositionAssembly";
|
||||
@@ -300,6 +301,7 @@ function countAuthoredCompositionIds(hosts: Element[]): Map<string, number> {
|
||||
if (!compId) continue;
|
||||
hostCountsByCompositionId.set(compId, (hostCountsByCompositionId.get(compId) || 0) + 1);
|
||||
}
|
||||
countPageRoot(hostCountsByCompositionId, hosts);
|
||||
return hostCountsByCompositionId;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,19 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("frame sources", () => {
|
||||
it("holds a geometry read that skips video frames until its asynchronous draw lands", async () => {
|
||||
const frame = deferred();
|
||||
disposers.push(registerFrameSource({ element: mount(), render: () => frame.promise }));
|
||||
adapter().seek({ time: 2 });
|
||||
let captured = false;
|
||||
const capture = waitForSeekCompletion({ videoFrames: false }).then(() => (captured = true));
|
||||
await Promise.resolve();
|
||||
expect(captured).toBe(false);
|
||||
frame.resolve();
|
||||
await capture;
|
||||
expect(captured).toBe(true);
|
||||
});
|
||||
|
||||
it("holds capture through setup and asynchronous drawing", async () => {
|
||||
const setup = deferred();
|
||||
const frame = deferred();
|
||||
|
||||
@@ -110,6 +110,42 @@ describe("scene scripts held until the playhead nears", () => {
|
||||
expect(ran()).toBe("near tied far ");
|
||||
});
|
||||
|
||||
it.each([0, 10])(
|
||||
"runs a nested held scene on its first direct root-time seek, with parent in-point %s",
|
||||
async (inPoint) => {
|
||||
(globalThis as { CSS?: { escape?: (v: string) => string } }).CSS ??= {};
|
||||
globalThis.CSS.escape ??= (v: string) => v;
|
||||
document.head.appendChild(
|
||||
Object.assign(document.createElement("meta"), { name: STUDIO_PREVIEW_MARK_META }),
|
||||
);
|
||||
document.body.innerHTML =
|
||||
`<div data-composition-id="main" data-root="true" data-start="0" data-duration="60" data-width="1920" data-height="1080">` +
|
||||
`<div data-composition-id="group" data-start="20" data-duration="40" data-playback-start="${inPoint}">` +
|
||||
host("far", 30) +
|
||||
`</div></div>` +
|
||||
sceneScript("far");
|
||||
window.__timelines = { main: timeline(60) };
|
||||
const register = () => {
|
||||
window.__timelines!.far = timeline(5);
|
||||
};
|
||||
document.addEventListener("scene-ran", register);
|
||||
try {
|
||||
vi.resetModules();
|
||||
await import("./entry");
|
||||
await vi.waitFor(() => expect(window.__player).toBeDefined());
|
||||
expect(ran()).toBe("");
|
||||
window.__player!.seek(51 - inPoint);
|
||||
await window.__hfWaitForSeekCompletion?.();
|
||||
expect(ran()).toBe("far ");
|
||||
window.__player!.seek(52 - inPoint);
|
||||
await window.__hfWaitForSeekCompletion?.();
|
||||
expect(ran()).toBe("far ");
|
||||
} finally {
|
||||
document.removeEventListener("scene-ran", register);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("runs a far scene the playback reaches without pausing the clock", async () => {
|
||||
await boot(true);
|
||||
window.__player!.seek(19.5);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { SCENE_EAGER_ATTR, SCENE_PART_ATTR } from "../sceneParts";
|
||||
import { parseStrictFiniteTimingNumber } from "./playbackRate";
|
||||
import { skipsHiddenImages } from "./timedClipHide";
|
||||
import { createRuntimeStartTimeResolver } from "./startResolver";
|
||||
|
||||
/** How far ahead of the playhead a held scene's scripts run, so they finish before it shows. */
|
||||
const SCENE_LEAD_SECONDS = 10;
|
||||
@@ -17,13 +18,18 @@ const held = new Map<string, HeldScene>();
|
||||
const timing = (host: Element, name: string) =>
|
||||
parseStrictFiniteTimingNumber(host.getAttribute(name));
|
||||
|
||||
function holdable(host: Element | undefined): HeldScene | null {
|
||||
function holdable(
|
||||
host: Element | undefined,
|
||||
resolveStart: (host: Element, fallback?: number) => number,
|
||||
): HeldScene | null {
|
||||
// Swaps and boot give captions their edited words; a mount would not.
|
||||
if (!host || host.hasAttribute(SCENE_EAGER_ATTR) || host.querySelector(".caption-group"))
|
||||
return null;
|
||||
const start = timing(host, "data-start");
|
||||
const authoredStart = timing(host, "data-start");
|
||||
const duration = timing(host, "data-duration");
|
||||
if (start == null || duration == null || start <= SCENE_LEAD_SECONDS) return null;
|
||||
if (authoredStart == null || duration == null) return null;
|
||||
const start = resolveStart(host, NaN);
|
||||
if (!Number.isFinite(start) || start <= SCENE_LEAD_SECONDS) return null;
|
||||
return { host, start, end: start + duration, scripts: [] };
|
||||
}
|
||||
|
||||
@@ -32,6 +38,10 @@ function holdable(host: Element | undefined): HeldScene | null {
|
||||
export function holdFarSceneScripts(scripts: Element[]): Element[] {
|
||||
held.clear();
|
||||
if (!skipsHiddenImages()) return scripts;
|
||||
const { resolveStartForElement } = createRuntimeStartTimeResolver({
|
||||
documentRef: document,
|
||||
includeAuthoredTimingAttrs: true,
|
||||
});
|
||||
const hosts = new Map<string, Element>();
|
||||
for (const el of document.querySelectorAll(`[${SCENE_PART_ATTR}]`))
|
||||
if (el.tagName !== "SCRIPT" && el.tagName !== "STYLE")
|
||||
@@ -39,7 +49,7 @@ export function holdFarSceneScripts(scripts: Element[]): Element[] {
|
||||
return scripts.filter((script) => {
|
||||
const scene = script.getAttribute(SCENE_PART_ATTR);
|
||||
if (scene == null || script.hasAttribute("src")) return true;
|
||||
const entry = held.get(scene) ?? holdable(hosts.get(scene));
|
||||
const entry = held.get(scene) ?? holdable(hosts.get(scene), resolveStartForElement);
|
||||
if (!entry) return true;
|
||||
held.set(scene, entry);
|
||||
entry.scripts.push(script);
|
||||
|
||||
@@ -199,6 +199,100 @@ describe("runtime sub-composition placement", () => {
|
||||
expect(window.__player?.getDuration()).toBe(9);
|
||||
});
|
||||
|
||||
it("rests a scene's longer animation at its clip's end, where the clip hides", () => {
|
||||
document.body.innerHTML =
|
||||
`<div data-composition-id="main" data-root="true" data-duration="10">` +
|
||||
`<div id="host" class="clip" data-composition-id="scene" data-start="1" data-duration="2">` +
|
||||
`<div id="s"></div></div></div>`;
|
||||
let renders = 0;
|
||||
const scene = gsap
|
||||
.timeline({ paused: true })
|
||||
.to("#s", { x: 100, duration: 8, ease: "none", onUpdate: () => renders++ }, 0);
|
||||
const root = gsap.timeline({ paused: true }).to({}, { duration: 10 }, 0);
|
||||
window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
|
||||
initSandboxRuntimeModular();
|
||||
|
||||
window.__player?.seek(2);
|
||||
expect(shownX()).toBe(12.5);
|
||||
window.__player?.seek(5);
|
||||
expect(shownX()).toBe(25);
|
||||
expect(getComputedStyle(document.getElementById("host")!).visibility).toBe("hidden");
|
||||
renders = 0;
|
||||
window.__player?.seek(6);
|
||||
expect(renders).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps a slow scene with no clip window animating while it shows", () => {
|
||||
document.body.innerHTML =
|
||||
`<div data-composition-id="main" data-root="true" data-duration="20">` +
|
||||
`<div id="host" data-composition-id="scene" data-playback-rate="0.5">` +
|
||||
`<div id="s"></div></div></div>`;
|
||||
const scene = gsap
|
||||
.timeline({ paused: true })
|
||||
.to("#s", { x: 100, duration: 8, ease: "none" }, 0);
|
||||
const root = gsap.timeline({ paused: true }).to({}, { duration: 20 }, 0);
|
||||
window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
|
||||
initSandboxRuntimeModular();
|
||||
|
||||
window.__player?.seek(6);
|
||||
window.__player?.seek(12);
|
||||
expect(shownX()).toBe(75);
|
||||
});
|
||||
|
||||
it("keeps a slow scene Studio stamped animating past its stamp, once the root has grown", () => {
|
||||
const parent = window.parent;
|
||||
Object.defineProperty(window, "parent", { configurable: true, value: {} });
|
||||
try {
|
||||
// What Studio leaves after a root extension: the host's discovery stamp still ends at 10 s.
|
||||
document.body.innerHTML =
|
||||
`<div data-composition-id="main" data-root="true" data-duration="20">` +
|
||||
`<div id="host" style="position: absolute" data-composition-id="scene" data-playback-rate="0.5"` +
|
||||
` data-start="0" data-duration="10" data-hf-autostamped="1"><div id="s"></div></div></div>`;
|
||||
const scene = gsap
|
||||
.timeline({ paused: true })
|
||||
.to("#s", { x: 100, duration: 8, ease: "none" }, 0);
|
||||
const root = gsap.timeline({ paused: true }).to({}, { duration: 20 }, 0);
|
||||
window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
|
||||
initSandboxRuntimeModular();
|
||||
|
||||
window.__player?.seek(6);
|
||||
window.__player?.seek(12);
|
||||
expect(shownX()).toBe(75);
|
||||
expect(getComputedStyle(document.getElementById("host")!).visibility).not.toBe("hidden");
|
||||
} finally {
|
||||
Object.defineProperty(window, "parent", { configurable: true, value: parent });
|
||||
}
|
||||
});
|
||||
|
||||
it("renders a scene past its clip's end where root propagation leaves it, replaying no callbacks", () => {
|
||||
document.body.innerHTML =
|
||||
`<div data-composition-id="main" data-root="true" data-duration="10">` +
|
||||
`<div id="host" class="clip" data-composition-id="scene" data-start="1" data-duration="2">` +
|
||||
`<div id="s"></div></div></div>`;
|
||||
let callbacks = 0;
|
||||
const scene = gsap.timeline({ paused: true }).to(
|
||||
"#s",
|
||||
{
|
||||
x: 100,
|
||||
duration: 8,
|
||||
ease: "none",
|
||||
onUpdate: () => callbacks++,
|
||||
onComplete: () => callbacks++,
|
||||
},
|
||||
0,
|
||||
);
|
||||
const root = gsap.timeline({ paused: true }).to({}, { duration: 10 }, 0);
|
||||
window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
|
||||
initSandboxRuntimeModular();
|
||||
|
||||
window.__player?.renderSeek(9.1);
|
||||
expect(shownX()).toBe(100);
|
||||
callbacks = 0;
|
||||
window.__player?.renderSeek(9.2);
|
||||
window.__player?.renderSeek(9.3, { suppressEvents: true });
|
||||
expect(callbacks).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the scene in one root after a tween first renders, when the root's own timeline is empty", async () => {
|
||||
const runFrames = stubFrames();
|
||||
document.body.innerHTML =
|
||||
|
||||
@@ -273,6 +273,30 @@ describe("__hfSwapScenes", () => {
|
||||
expect(JSON.parse(meta).scenes.a).toBe("ha2");
|
||||
});
|
||||
|
||||
it("adds only the fonts a swapped scene brings, leaving the loaded ones' style as it was", async () => {
|
||||
const faceA = '@font-face{font-family:"A";src:url(a.woff2)}';
|
||||
const faceB = '@font-face{font-family:"B";src:url(b.woff2)}';
|
||||
boot(
|
||||
[A1, B],
|
||||
trackingRoot().root,
|
||||
(head) => `<style data-hf-scene-fonts>${faceA}</style>${head}`,
|
||||
);
|
||||
await tick();
|
||||
const loaded = document.querySelector("style[data-hf-scene-fonts]")!;
|
||||
|
||||
const next = preview([A2, B]).html.replace(
|
||||
"<head>",
|
||||
`<head><style data-hf-scene-fonts>${faceA}\n${faceB}</style>`,
|
||||
);
|
||||
await window.__hfSwapScenes!(next);
|
||||
|
||||
expect(sceneHost("a").textContent).toBe("A two");
|
||||
const holders = [...document.querySelectorAll("style[data-hf-scene-fonts]")];
|
||||
expect(holders[0]).toBe(loaded);
|
||||
expect(loaded.textContent).toBe(faceA);
|
||||
expect(holders.map((el) => el.textContent)).toEqual([faceA, faceB]);
|
||||
});
|
||||
|
||||
it("runs the swapped scene's script only once web fonts are ready", async () => {
|
||||
const { root } = trackingRoot();
|
||||
boot([A1, B], root);
|
||||
|
||||
@@ -104,9 +104,11 @@ import {
|
||||
fetchCaptionOverrides,
|
||||
} from "./captionOverrides";
|
||||
import {
|
||||
SCENE_FONTS_ATTR,
|
||||
SCENE_NO_SWAP_ATTR,
|
||||
SCENE_PART_ATTR,
|
||||
SCENE_PARTS_META,
|
||||
fontFaceBlocks,
|
||||
type SceneParts,
|
||||
} from "../sceneParts";
|
||||
import {
|
||||
@@ -434,6 +436,9 @@ function loadPreviewImagesIn(root: Element): void {
|
||||
export function initSandboxRuntimeModular(): void {
|
||||
const state = createRuntimeState();
|
||||
const stampsForStudio = window.parent !== window;
|
||||
// Studio's discovery stamps time a clip for the timeline only; nothing hides it at their end.
|
||||
const isDiscoveryStamped = (el: Element) =>
|
||||
stampsForStudio && el.hasAttribute(RUNTIME_STAMPED_ATTR);
|
||||
authoredMediaObserver?.disconnect();
|
||||
authoredMediaObserver = null;
|
||||
if (readSceneParts(document)) recordAuthoredMedia(document.documentElement);
|
||||
@@ -2960,7 +2965,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
visibleAt(rawNode, currentTime) &&
|
||||
clipChainVisibleAt(rawNode.parentElement, currentTime, visibleAt, rootComp);
|
||||
visibilityDecided.set(rawNode, isVisibleNow);
|
||||
const isRuntimeStamped = stampsForStudio && rawNode.hasAttribute(RUNTIME_STAMPED_ATTR);
|
||||
const isRuntimeStamped = isDiscoveryStamped(rawNode);
|
||||
if (!isRuntimeStamped) rawNode.style.visibility = isVisibleNow ? "visible" : "hidden";
|
||||
rawNode.toggleAttribute(CLIP_HIDDEN_ATTR, !isRuntimeStamped && !isVisibleNow);
|
||||
const upcoming =
|
||||
@@ -3715,6 +3720,24 @@ export function initSandboxRuntimeModular(): void {
|
||||
}
|
||||
}
|
||||
};
|
||||
// Only the rules not here yet: rewriting a loaded rule's style would load its font again.
|
||||
const addNewFontFaces = (next: Document) => {
|
||||
const holders = (doc: Document) =>
|
||||
Array.from(doc.querySelectorAll(`style[${SCENE_FONTS_ATTR}]`));
|
||||
const live = holders(document);
|
||||
const have = new Set(live.flatMap((el) => fontFaceBlocks(el.textContent ?? "")));
|
||||
const added = new Set(
|
||||
holders(next)
|
||||
.flatMap((el) => fontFaceBlocks(el.textContent ?? ""))
|
||||
.filter((face) => !have.has(face)),
|
||||
);
|
||||
if (added.size === 0) return;
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute(SCENE_FONTS_ATTR, "");
|
||||
style.textContent = [...added].join("\n");
|
||||
if (live.length > 0) live.at(-1)!.after(style);
|
||||
else document.head.prepend(style);
|
||||
};
|
||||
// Swap edited scenes in place from a rebuilt preview document. Refuses before changing anything unless
|
||||
// the documents differ only inside existing scenes; a later failure is left to the caller's reload.
|
||||
// Nests the timelines a scene's scripts just made and redraws the current frame with them.
|
||||
@@ -3907,6 +3930,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
swappedHosts.push(host);
|
||||
if (host.querySelector(".caption-group")) captionHosts.push(host);
|
||||
}
|
||||
addNewFontFaces(next);
|
||||
// Run once every host is replaced, so no new script binds to a scene still to be swapped.
|
||||
refreshSvgSelectorAliases();
|
||||
const sceneScripts = swaps.flatMap(({ newParts }) =>
|
||||
@@ -4414,6 +4438,14 @@ export function initSandboxRuntimeModular(): void {
|
||||
let playingPollWitness = "";
|
||||
let lastTickPlaying = false;
|
||||
|
||||
const gsapStructureOf = (timeline: RuntimeTimelineLike): GsapStructureKey | undefined =>
|
||||
renderCaptureSeekStarted
|
||||
? undefined
|
||||
: {
|
||||
owner: timeline,
|
||||
version: `${compositionTimingRevision}:${timeline.getChildren?.(false, true, true).length ?? 0}`,
|
||||
};
|
||||
|
||||
const seekRuntimeTimeline = (
|
||||
timeline: RuntimeTimelineLike,
|
||||
timeSeconds: number,
|
||||
@@ -4424,7 +4456,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
const suppressEvents = options?.suppressEvents === true;
|
||||
// Guarded: a partial timeline without pause() must still get its seek.
|
||||
pauseTimelineIfPossible(timeline);
|
||||
seekGsapTimeline(timeline, timeSeconds, suppressEvents);
|
||||
seekGsapTimeline(timeline, timeSeconds, suppressEvents, gsapStructureOf(timeline));
|
||||
} catch (err) {
|
||||
swallow(swallowLabel, err);
|
||||
}
|
||||
@@ -4443,7 +4475,10 @@ export function initSandboxRuntimeModular(): void {
|
||||
standaloneHosts.set(compositionId, node ?? { missingAt: compositionTimingRevision });
|
||||
return node;
|
||||
};
|
||||
const seekStandaloneRegisteredTimelines = (timeSeconds: number, options?: RuntimeSeekOptions) => {
|
||||
const seekStandaloneRegisteredTimelines = (
|
||||
timeSeconds: number,
|
||||
options?: RuntimeSeekOptions & { activateChildren?: boolean },
|
||||
) => {
|
||||
const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;
|
||||
const rootCompositionId =
|
||||
resolveRootCompositionElement()?.getAttribute("data-composition-id") ?? null;
|
||||
@@ -4453,10 +4488,18 @@ export function initSandboxRuntimeModular(): void {
|
||||
if (!node) continue;
|
||||
const start = resolveStartForElement(node, 0);
|
||||
if (!Number.isFinite(start)) continue;
|
||||
// Rest only where the visibility pass hides the host and no rearmed root propagation moves it.
|
||||
const hiddenFrom =
|
||||
!options?.activateChildren && node.hasAttribute("data-start") && !isDiscoveryStamped(node)
|
||||
? start + (resolveDurationForElement(node) ?? Infinity)
|
||||
: Infinity;
|
||||
const timelineDuration = getTimelineDurationSeconds(timeline);
|
||||
const sourceTime =
|
||||
readElementPlaybackStart(node) +
|
||||
sourceTimeAt(readElementRateSpec(node), Math.max(0, timeSeconds - start));
|
||||
sourceTimeAt(
|
||||
readElementRateSpec(node),
|
||||
Math.max(0, Math.min(timeSeconds, hiddenFrom) - start),
|
||||
);
|
||||
const localTime = Math.max(
|
||||
0,
|
||||
timelineDuration != null && timelineDuration > 0
|
||||
@@ -4610,13 +4653,8 @@ export function initSandboxRuntimeModular(): void {
|
||||
}
|
||||
try {
|
||||
if (typeof tl.totalTime === "function") {
|
||||
const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents);
|
||||
const structure = renderCaptureSeekStarted
|
||||
? undefined
|
||||
: {
|
||||
owner: tl,
|
||||
version: `${compositionTimingRevision}:${tl.getChildren?.(false, true, true).length ?? 0}`,
|
||||
};
|
||||
const structure = gsapStructureOf(tl);
|
||||
const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents, structure);
|
||||
if (!redrawn && !suppressEvents && !hasZeroDurationCallbackTween(tl, structure)) {
|
||||
// The first seek is the only eventful one; the re-render only refreshes styles.
|
||||
rerenderGsapTimelineAt(
|
||||
|
||||
@@ -742,6 +742,12 @@ describe("syncRuntimeMedia", () => {
|
||||
expect(await barrierSettled(barrier)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not hold a geometry read for a seeking video's frame", async () => {
|
||||
seekColdVideo();
|
||||
expect(await barrierSettled(waitForSeekCompletion({ videoFrames: false }))).toBe(true);
|
||||
expect(await barrierSettled(waitForSeekCompletion())).toBe(false);
|
||||
});
|
||||
|
||||
function seekLoadingVideo(): RuntimeMediaClip {
|
||||
const clip = createMockClip({ start: 7.1, end: 18.24 });
|
||||
Object.defineProperty(clip.el, "readyState", { value: 0, configurable: true });
|
||||
|
||||
@@ -48,6 +48,7 @@ function holdSeekBarrierUntilVideoLands(el: HTMLMediaElement): void {
|
||||
for (const type of HOLD_END_EVENTS) el.addEventListener(type, done, true);
|
||||
releaseHeldVideo.set(el, done);
|
||||
}),
|
||||
"video-frame",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -347,7 +347,10 @@ export function swapToProxy(
|
||||
});
|
||||
});
|
||||
// A frame capture holds for the copy as it held for a loading video before, up to the same cap.
|
||||
registerSeekCompletion(Promise.race([swap, new Promise((cap) => setTimeout(cap, HOLD_CAP_MS))]));
|
||||
registerSeekCompletion(
|
||||
Promise.race([swap, new Promise((cap) => setTimeout(cap, HOLD_CAP_MS))]),
|
||||
"video-frame",
|
||||
);
|
||||
const codecName = entry?.codecName ?? null;
|
||||
const details: Record<string, RuntimeJson> = {
|
||||
asset: originalSrc,
|
||||
|
||||
+2
-2
@@ -132,9 +132,9 @@ declare global {
|
||||
__hfReseekGpu?: (time: number) => void;
|
||||
/**
|
||||
* Await GPU work registered synchronously by `hf-seek` listeners through
|
||||
* `event.detail.waitUntil(...)`.
|
||||
* `event.detail.waitUntil(...)`; `videoFrames: false` skips the video-frame holds.
|
||||
*/
|
||||
__hfWaitForSeekCompletion?: () => Promise<void>;
|
||||
__hfWaitForSeekCompletion?: (options?: { videoFrames?: boolean }) => Promise<void>;
|
||||
/**
|
||||
* Canonical root-timeline start for a media element. Snapshot capture uses
|
||||
* this runtime-owned resolver so reference expressions, authored timing
|
||||
|
||||
@@ -2,6 +2,11 @@ export const SCENE_PART_ATTR = "data-hf-scene";
|
||||
|
||||
export const SCENE_PARTS_META = "hf-scene-parts";
|
||||
|
||||
export const SCENE_FONTS_ATTR = "data-hf-scene-fonts";
|
||||
|
||||
export const fontFaceBlocks = (css: string): string[] =>
|
||||
css.match(/@font-face\s*\{[^}]*\}/gi) ?? [];
|
||||
|
||||
/** On a scene's top-level host: why the scene cannot be swapped in place, so edits to it reload. */
|
||||
export const SCENE_NO_SWAP_ATTR = "data-hf-scene-no-swap";
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user