Files
hyperframes/packages/core/scripts/test-hyperframe-runtime-contract.ts
Miguel Ángel 0285a711e9 feat(core): expose pretext text measurement on window.__hyperframes (#3302)
## What

Exposes the `pretext` text-measurement API on `window.__hyperframes`, so the API our agent-facing docs already describe actually exists.

Adds `pretext.prepare`, `.layout`, `.prepareWithSegments`, `.measureLineStats`, `.measureNaturalWidth`.

## Why

`skills/hyperframes-core/references/determinism-rules.md` is required reading for any agent authoring a composition. Line 59 tells them to call `window.__hyperframes.pretext.prepare(text, font)` then `pretext.layout(prepared, maxWidth, lineHeight)` for text measurement without a DOM reflow.

That object did not exist. The runtime exposed exactly `fitTextFontSize` and `getVariables`. Any composition following the documented recipe threw at runtime.

Deleting the doc line was the smaller change, but reflow-free measurement is genuinely the right tool for sizing text per frame, and `fitTextFontSize` is already built on it. Making the docs true is the better fix.

## How

- New `packages/core/src/text/pretext.ts` assembles the exposed surface in one place, with the include/exclude rationale next to it.
- `entry.ts` attaches it alongside the existing helpers. Sub-compositions inherit it for free: the scoping shim builds its scoped variant with `Object.assign({}, base, { getVariables })`, so anything added to the base object is carried through.

Two deliberate decisions:

**Wider than the doc named.** `layout()` returns only `{ lineCount, height }`. The doc's own "shrinkwrap containers" use case needs a width, which is impossible with just `prepare` + `layout`. `measureNaturalWidth` and `measureLineStats` make that claim achievable; `prepareWithSegments` is their required input.

**`clearCache` and `setLocale` withheld.** Both mutate state shared across compositions. Exposing them would let one composition change how a later one measures, making a render depend on what ran before it.

**Doc correction.** The reference called this "pure arithmetic, ~0.0002 ms per call". Not quite: `prepare` measures fonts through a canvas and throws outside a browser. Only the steps after a prepared string are arithmetic. Reworded, and documented the width helpers and the omissions.

## Trade-off

The runtime bundle grows **4,903 bytes (+1.30%)**, from 377,865 to 382,768. That ships inline in every composition. Measured by building the artifact with and without the change.

## Test plan

- [x] Unit tests added/updated
- [x] Manual testing performed
- [x] Documentation updated (if applicable)

`packages/core/src/text/pretext.test.ts` guards the shape of the published surface: the two documented names exist, the width helpers exist, and the two stateful functions are absent. Behaviour is deliberately not asserted there. `prepare` needs a canvas, and mocking it (as `fitTextFontSize.test.ts` must) would assert nothing real.

Real behaviour was verified by rendering a composition that calls the documented API:

```
lines=2  height=216  naturalWidth=1785
```

Self-consistent: natural width 1785 exceeds the 1600 container so it wraps to 2 lines, and 2 x 108 line-height is exactly the reported 216. The frame was inspected visually.

Also run:
- `packages/core` full suite from the package root: **903 passed, 46 files**
- `tsc --noEmit` and `tsc --noEmit -p tsconfig.runtime.json`: clean
- `oxlint` / `oxfmt`: clean

## Follow-ups (not in this PR)

An audit of the wider attribute surface found several more doc/runtime mismatches, including `data-gpu-mode` documented as an HTML attribute when it is a config field, and `data-no-timeline` being real, load-bearing, and absent from the table agents read. Those are separate changes.
2026-08-17 16:42:27 -04:00

107 lines
3.9 KiB
TypeScript

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadHyperframeRuntimeSource } from "../src/inline-scripts/hyperframe";
function assert(condition: unknown, message: string): void {
if (!condition) {
throw new Error(message);
}
}
const runtimeSource = loadHyperframeRuntimeSource();
assert(runtimeSource !== null, "loadHyperframeRuntimeSource() returned null — entry.ts not found");
const requiredSnippets = [
"window.__player",
"window.__playerReady",
"window.__renderReady",
"hf-preview",
"hf-parent",
"renderSeek",
"__hyperframes",
"fitTextFontSize",
];
for (const snippet of requiredSnippets) {
assert(runtimeSource.includes(snippet), `Runtime contract snippet missing: ${snippet}`);
}
// Snippet checks cannot prove what `window.__hyperframes` ends up carrying.
// A name can reach the bundle through an unrelated import: `fitTextFontSize.ts`
// imports `prepare`/`layout` from `@chenglou/pretext`, so grepping for
// "pretext" stays green even if the attachment in entry.ts is deleted. Run the
// runtime and read the object back instead.
const { JSDOM } = await import("jsdom");
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
runScripts: "outside-only",
});
// The runtime's DOMContentLoaded path calls requestAnimationFrame. jsdom only
// provides it under `pretendToBeVisual`, which also starts a frame loop that
// keeps the process alive, so stub it instead. The stub never fires: we are
// asserting what the runtime attaches at evaluation time, not what it animates.
Object.defineProperty(dom.window, "requestAnimationFrame", {
value: () => 0,
configurable: true,
});
Object.defineProperty(dom.window, "cancelAnimationFrame", {
value: () => {},
configurable: true,
});
dom.window.eval(runtimeSource);
const hyperframes = (dom.window as unknown as { __hyperframes?: Record<string, unknown> })
.__hyperframes;
assert(hyperframes, "Runtime did not attach window.__hyperframes");
// Each of these is an API the agent-facing docs tell composition authors to
// call. If one stops being attached, every composition written against the
// docs throws at render time, which no other check would catch.
const requiredHelpers = ["fitTextFontSize", "getVariables"];
for (const helper of requiredHelpers) {
assert(
typeof hyperframes[helper] === "function",
`window.__hyperframes.${helper} is not attached`,
);
}
const pretext = hyperframes.pretext as Record<string, unknown> | undefined;
assert(pretext, "window.__hyperframes.pretext is not attached");
const requiredPretextFns = [
"prepare",
"layout",
"prepareWithSegments",
"measureLineStats",
"measureNaturalWidth",
];
for (const fn of requiredPretextFns) {
assert(typeof pretext[fn] === "function", `window.__hyperframes.pretext.${fn} is not attached`);
}
// clearCache/setLocale mutate state shared across compositions. Keeping them
// off the surface is a deliberate determinism choice, so assert it holds.
for (const forbidden of ["clearCache", "setLocale"]) {
assert(
!(forbidden in pretext),
`window.__hyperframes.pretext.${forbidden} must not be exposed (mutates shared state)`,
);
}
const scriptDir = resolve(fileURLToPath(new URL(".", import.meta.url)));
const manifestPath = resolve(scriptDir, "../dist/hyperframe.manifest.json");
try {
const manifestRaw = readFileSync(manifestPath, "utf8");
const manifest = JSON.parse(manifestRaw) as { artifacts?: { iife?: string; esm?: string } };
assert(Boolean(manifest.artifacts?.iife), "Manifest is missing iife artifact");
assert(Boolean(manifest.artifacts?.esm), "Manifest is missing esm artifact");
} catch {
// Build may not have run yet; contract-only checks above still provide signal.
}
console.log(
JSON.stringify({
event: "hyperframe_runtime_contract_verified",
requiredSnippetsChecked: requiredSnippets.length,
}),
);