[teamai] Push 87 resource(s) from XingfenD
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Seek and measure every sample for one tween inside a single browser
|
||||
* evaluation. GSAP/HyperFrames seeks update DOM state synchronously, so a
|
||||
* separate CDP round trip and wall-clock sleep per sample only adds latency.
|
||||
*/
|
||||
export async function sampleTweenBboxes(page, selector, times) {
|
||||
return page.evaluate(
|
||||
({ selector: sel, times: sampleTimes }) => {
|
||||
const seek = (time) => {
|
||||
if (window.__hf && typeof window.__hf.seek === "function") {
|
||||
window.__hf.seek(time);
|
||||
return;
|
||||
}
|
||||
const timelines = window.__timelines;
|
||||
if (!timelines) return;
|
||||
for (const timeline of Object.values(timelines)) {
|
||||
if (typeof timeline.seek === "function") timeline.seek(time);
|
||||
}
|
||||
};
|
||||
|
||||
return sampleTimes.map((time) => {
|
||||
seek(time);
|
||||
const el = document.querySelector(sel);
|
||||
if (!el) return { t: time, x: 0, y: 0, w: 0, h: 0, missing: true };
|
||||
const rect = el.getBoundingClientRect();
|
||||
const style = getComputedStyle(el);
|
||||
return {
|
||||
t: time,
|
||||
x: Math.round(rect.x),
|
||||
y: Math.round(rect.y),
|
||||
w: Math.round(rect.width),
|
||||
h: Math.round(rect.height),
|
||||
opacity: parseFloat(style.opacity),
|
||||
visible: style.visibility !== "hidden" && style.display !== "none",
|
||||
};
|
||||
});
|
||||
},
|
||||
{ selector, times },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { sampleTweenBboxes } from "./animation-map-sampling.mjs";
|
||||
|
||||
test("samples every tween time in one browser evaluation", async () => {
|
||||
const calls = [];
|
||||
const seekTimes = [];
|
||||
const originalGlobals = {
|
||||
window: globalThis.window,
|
||||
document: globalThis.document,
|
||||
getComputedStyle: globalThis.getComputedStyle,
|
||||
};
|
||||
let currentTime = 0;
|
||||
globalThis.window = { __hf: { seek: (time) => (currentTime = time) } };
|
||||
globalThis.document = {
|
||||
querySelector: () => ({
|
||||
getBoundingClientRect: () => ({ x: currentTime, y: 20, width: 30, height: 40 }),
|
||||
}),
|
||||
};
|
||||
globalThis.getComputedStyle = () => ({ opacity: "1", visibility: "visible", display: "block" });
|
||||
const page = {
|
||||
async evaluate(callback, payload) {
|
||||
calls.push(payload);
|
||||
const originalSeek = globalThis.window.__hf.seek;
|
||||
globalThis.window.__hf.seek = (time) => {
|
||||
seekTimes.push(time);
|
||||
originalSeek(time);
|
||||
};
|
||||
return callback(payload);
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await sampleTweenBboxes(page, "#card", [1, 2, 3]);
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{ t: 1, x: 1, y: 20, w: 30, h: 40, opacity: 1, visible: true },
|
||||
{ t: 2, x: 2, y: 20, w: 30, h: 40, opacity: 1, visible: true },
|
||||
{ t: 3, x: 3, y: 20, w: 30, h: 40, opacity: 1, visible: true },
|
||||
]);
|
||||
assert.deepEqual(seekTimes, [1, 2, 3]);
|
||||
assert.deepEqual(calls, [{ selector: "#card", times: [1, 2, 3] }]);
|
||||
} finally {
|
||||
globalThis.window = originalGlobals.window;
|
||||
globalThis.document = originalGlobals.document;
|
||||
globalThis.getComputedStyle = originalGlobals.getComputedStyle;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,659 @@
|
||||
#!/usr/bin/env node
|
||||
// animation-map.mjs — HyperFrames animation map for agents
|
||||
//
|
||||
// Reads every GSAP timeline registered in window.__timelines, enumerates
|
||||
// tweens, samples bboxes at N points per tween, computes flags and
|
||||
// human-readable summaries. Outputs a single animation-map.json.
|
||||
//
|
||||
// Usage:
|
||||
// node skills/hyperframes-animation/scripts/animation-map.mjs <composition-dir> \
|
||||
// [--frames N] [--out <dir>] [--min-duration S] [--width W] [--height H] [--fps N]
|
||||
//
|
||||
// Env:
|
||||
// HYPERFRAMES_SKILL_PKG_VERSION — pin the @hyperframes/producer version used
|
||||
// when bootstrapping (global skill installs cannot infer it; falls back to
|
||||
// @latest with a warning otherwise).
|
||||
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve, join } from "node:path";
|
||||
import { sampleTweenBboxes } from "./animation-map-sampling.mjs";
|
||||
import {
|
||||
bundleCompositionForCapture,
|
||||
hyperframesPackageSpec,
|
||||
importPackagesOrBootstrap,
|
||||
initializeSessionWithRetry,
|
||||
} from "./package-loader.mjs";
|
||||
|
||||
const packages = await importPackagesOrBootstrap(
|
||||
["@hyperframes/producer", "@hyperframes/core", "@hyperframes/core/compiler"],
|
||||
{
|
||||
npmPackages: [
|
||||
hyperframesPackageSpec("@hyperframes/producer"),
|
||||
hyperframesPackageSpec("@hyperframes/core"),
|
||||
],
|
||||
},
|
||||
);
|
||||
const { createFileServer, createCaptureSession, closeCaptureSession, getCompositionDuration } =
|
||||
packages["@hyperframes/producer"];
|
||||
const { parseFps } = packages["@hyperframes/core"];
|
||||
|
||||
// ─── CLI ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args.composition) die("missing <composition-dir>");
|
||||
|
||||
const FRAMES = Number(args.frames ?? 6);
|
||||
const OUT_DIR = resolve(args.out ?? ".hyperframes/anim-map");
|
||||
const MIN_DUR = Number(args["min-duration"] ?? 0.15);
|
||||
const WIDTH = Number(args.width ?? 1920);
|
||||
const HEIGHT = Number(args.height ?? 1080);
|
||||
const parsedFps = parseFps(args.fps ?? 30);
|
||||
if (!parsedFps.ok) die(`Invalid --fps "${args.fps ?? ""}": ${parsedFps.reason}`);
|
||||
const FPS = parsedFps.value;
|
||||
const COMP_DIR = resolve(args.composition);
|
||||
|
||||
await mkdir(OUT_DIR, { recursive: true });
|
||||
|
||||
// ─── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Raw modular hosts do not mount child compositions in the capture helper.
|
||||
// Bundle first so duration/timeline discovery sees the same DOM as render/check.
|
||||
const bundle = await bundleCompositionForCapture(packages["@hyperframes/core/compiler"], COMP_DIR);
|
||||
let server;
|
||||
let session;
|
||||
try {
|
||||
server = await createFileServer({
|
||||
projectDir: COMP_DIR,
|
||||
compiledDir: bundle.compiledDir,
|
||||
port: 0,
|
||||
});
|
||||
// Canonical transient-init retry/cleanup (mirrors the render pipeline's
|
||||
// probeStage): a valid modular project's sub-composition timelines register
|
||||
// asynchronously, so the first attempt can time out as transient
|
||||
// "zero duration / Runtime ready: false" — retry once with a fresh browser
|
||||
// instead of false-failing the project.
|
||||
session = await initializeSessionWithRetry(
|
||||
packages["@hyperframes/producer"],
|
||||
() =>
|
||||
createCaptureSession(
|
||||
server.url,
|
||||
OUT_DIR,
|
||||
{ width: WIDTH, height: HEIGHT, fps: FPS, format: "png" },
|
||||
null,
|
||||
),
|
||||
{ log: (message) => console.error(`animation-map: ${message}`) },
|
||||
);
|
||||
|
||||
const duration = await getCompositionDuration(session);
|
||||
const tweens = await enumerateTweens(session);
|
||||
const kept = tweens.filter((tw) => tw.end - tw.start >= MIN_DUR);
|
||||
|
||||
const report = {
|
||||
composition: COMP_DIR,
|
||||
duration,
|
||||
totalTweens: tweens.length,
|
||||
mappedTweens: kept.length,
|
||||
skippedMicroTweens: tweens.length - kept.length,
|
||||
tweens: [],
|
||||
};
|
||||
|
||||
for (let i = 0; i < kept.length; i++) {
|
||||
const tw = kept[i];
|
||||
const times = Array.from(
|
||||
{ length: FRAMES },
|
||||
(_, k) => +(tw.start + ((k + 0.5) / FRAMES) * (tw.end - tw.start)).toFixed(3),
|
||||
);
|
||||
|
||||
// No selector means no element to measure (an onUpdate driver). Sampling anyway
|
||||
// would hand querySelector an unmatchable string.
|
||||
const bboxes = tw.selectorHint
|
||||
? await sampleTweenBboxes(session.page, tw.selectorHint, times)
|
||||
: [];
|
||||
|
||||
const animProps = tw.props.filter(
|
||||
(p) => !["parent", "overwrite", "immediateRender", "startAt", "runBackwards"].includes(p),
|
||||
);
|
||||
const flags = computeFlags(tw, bboxes, { width: WIDTH, height: HEIGHT });
|
||||
const summary = describeTween(tw, animProps, bboxes, flags);
|
||||
|
||||
report.tweens.push({
|
||||
index: i + 1,
|
||||
selector: tw.selectorHint ?? "(onUpdate driver)",
|
||||
driver: tw.driver,
|
||||
targets: tw.targetCount,
|
||||
props: animProps,
|
||||
start: +tw.start.toFixed(3),
|
||||
end: +tw.end.toFixed(3),
|
||||
duration: +(tw.end - tw.start).toFixed(3),
|
||||
ease: tw.ease,
|
||||
bboxes,
|
||||
flags,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
|
||||
markCollisions(report.tweens);
|
||||
|
||||
for (const tw of report.tweens) {
|
||||
if (tw.flags.includes("collision") && !tw.summary.includes("collision")) {
|
||||
tw.summary += " Overlaps another animated element.";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Composition-level analysis ──
|
||||
report.choreography = buildTimeline(report.tweens, duration);
|
||||
report.density = computeDensity(report.tweens, duration);
|
||||
// Staggers and lifecycles are per-ELEMENT, and a driver tween has none. Keyed on
|
||||
// tw.selector they would collapse every driver in the composition into one
|
||||
// "(onUpdate driver)" pseudo-element with null geometry, and let three same-duration
|
||||
// drivers read as a stagger no element performs. Density, dead zones and the timeline
|
||||
// still count them — those are per-SPAN, which is what a driver does have.
|
||||
const elementTweens = report.tweens.filter((tw) => tw.driver !== "onUpdate");
|
||||
report.staggers = detectStaggers(elementTweens);
|
||||
report.elements = buildElementLifecycles(elementTweens);
|
||||
report.deadZones = findDeadZones(report.density, duration);
|
||||
report.snapshots = await captureSnapshots(session, report.tweens, duration);
|
||||
|
||||
await writeFile(join(OUT_DIR, "animation-map.json"), JSON.stringify(report, null, 2));
|
||||
|
||||
printSummary(report);
|
||||
} finally {
|
||||
if (session) await closeCaptureSession(session).catch(() => {});
|
||||
server?.close();
|
||||
bundle.cleanup();
|
||||
}
|
||||
|
||||
// ─── Seek helper ────────────────────────────────────────────────────────────
|
||||
|
||||
async function seekTo(session, t) {
|
||||
await session.page.evaluate((time) => {
|
||||
if (window.__hf && typeof window.__hf.seek === "function") {
|
||||
window.__hf.seek(time);
|
||||
return;
|
||||
}
|
||||
const tls = window.__timelines;
|
||||
if (tls) {
|
||||
for (const tl of Object.values(tls)) {
|
||||
if (typeof tl.seek === "function") tl.seek(time);
|
||||
}
|
||||
}
|
||||
}, t);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
|
||||
// ─── Timeline introspection ──────────────────────────────────────────────────
|
||||
|
||||
async function enumerateTweens(session) {
|
||||
return await session.page.evaluate(() => {
|
||||
const results = [];
|
||||
const registry = window.__timelines || {};
|
||||
|
||||
const selectorOf = (el) => {
|
||||
if (!el || !(el instanceof Element)) return null;
|
||||
if (el.id) return `#${el.id}`;
|
||||
const cls = [...el.classList].slice(0, 2).join(".");
|
||||
return cls ? `${el.tagName.toLowerCase()}.${cls}` : el.tagName.toLowerCase();
|
||||
};
|
||||
|
||||
const walk = (node, parentOffset = 0, parentDriven = false) => {
|
||||
if (!node) return;
|
||||
if (typeof node.getChildren === "function") {
|
||||
const offset = parentOffset + (node.startTime?.() ?? 0);
|
||||
// A TIMELINE can own the driver instead of the tween. The WebGL/uniform idiom is
|
||||
// gsap.timeline({ onUpdate: renderFrame }) over children that tween plain uniform
|
||||
// objects; those children carry no onUpdate of their own, so the driver has to
|
||||
// reach them from above or their motion reads as a dead zone all the same.
|
||||
const driven = parentDriven || typeof node.vars?.onUpdate === "function";
|
||||
for (const child of node.getChildren(true, true, true)) {
|
||||
walk(child, offset, driven);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const targets = (node.targets?.() ?? []).filter((t) => t instanceof Element);
|
||||
const vars = node.vars ?? {};
|
||||
const props = Object.keys(vars).filter(
|
||||
(k) =>
|
||||
![
|
||||
"duration",
|
||||
"ease",
|
||||
"delay",
|
||||
"repeat",
|
||||
"yoyo",
|
||||
"onStart",
|
||||
"onUpdate",
|
||||
"onComplete",
|
||||
"stagger",
|
||||
].includes(k),
|
||||
);
|
||||
// The proxy-driver idiom tweens a plain object and applies the motion in onUpdate,
|
||||
// so targets() holds no Element. Dropping those tweens hid real motion from the
|
||||
// map: computeDensity saw zero active tweens over their span and findDeadZones
|
||||
// reported it as dead. There is no element to select or measure here, but the span
|
||||
// is real, so keep the tween and mark why it carries no geometry.
|
||||
//
|
||||
// Under an inherited driver the tween must also CHANGE something. Its own onUpdate is
|
||||
// proof of work by itself (a repaint loop need not animate a property), but a parent's
|
||||
// is not: a bare `tl.to({}, { duration: D })` spacer inside a driven timeline advances
|
||||
// the playhead without altering any value, so counting it would mask a genuine dead
|
||||
// zone — the exact false positive the tween-local rule was careful to avoid.
|
||||
const isProxyDriver =
|
||||
targets.length === 0 &&
|
||||
(typeof vars.onUpdate === "function" || (parentDriven && props.length > 0));
|
||||
if (!targets.length && !isProxyDriver) return;
|
||||
const start = parentOffset + (node.startTime?.() ?? 0);
|
||||
const end = start + (node.duration?.() ?? 0);
|
||||
results.push({
|
||||
// null, not a placeholder string: this feeds document.querySelector downstream,
|
||||
// so it must be absent rather than unmatchable.
|
||||
selectorHint: isProxyDriver ? null : (selectorOf(targets[0]) ?? "(unknown)"),
|
||||
driver: isProxyDriver ? "onUpdate" : "target",
|
||||
targetCount: targets.length,
|
||||
props,
|
||||
start,
|
||||
end,
|
||||
ease: typeof vars.ease === "string" ? vars.ease : (vars.ease?.toString?.() ?? "none"),
|
||||
});
|
||||
};
|
||||
|
||||
for (const tl of Object.values(registry)) walk(tl, 0);
|
||||
results.sort((a, b) => a.start - b.start);
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Tween description (the key output for agents) ──────────────────────────
|
||||
|
||||
function describeTween(tw, props, bboxes, flags) {
|
||||
const dur = (tw.end - tw.start).toFixed(2);
|
||||
const parts = [];
|
||||
|
||||
if (tw.selectorHint) {
|
||||
parts.push(`${tw.selectorHint} animates ${props.join("+")} over ${dur}s (${tw.ease})`);
|
||||
} else {
|
||||
// An onUpdate driver: the span and props are known, the affected element is not.
|
||||
parts.push(
|
||||
`an onUpdate driver animates ${props.join("+")} over ${dur}s (${tw.ease}) — ` +
|
||||
`motion is applied in JS, so no element geometry was measured`,
|
||||
);
|
||||
}
|
||||
|
||||
// Movement
|
||||
const first = bboxes[0];
|
||||
const last = bboxes[bboxes.length - 1];
|
||||
if (first && last) {
|
||||
const dx = last.x - first.x;
|
||||
const dy = last.y - first.y;
|
||||
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {
|
||||
const dirs = [];
|
||||
if (Math.abs(dy) > 3) dirs.push(dy < 0 ? `${Math.abs(dy)}px up` : `${Math.abs(dy)}px down`);
|
||||
if (Math.abs(dx) > 3)
|
||||
dirs.push(dx < 0 ? `${Math.abs(dx)}px left` : `${Math.abs(dx)}px right`);
|
||||
parts.push(`moves ${dirs.join(" and ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Opacity
|
||||
if (first && last && first.opacity !== undefined && last.opacity !== undefined) {
|
||||
const o1 = first.opacity;
|
||||
const o2 = last.opacity;
|
||||
if (Math.abs(o2 - o1) > 0.1) {
|
||||
if (o1 < 0.1 && o2 > 0.5) parts.push("fades in");
|
||||
else if (o1 > 0.5 && o2 < 0.1) parts.push("fades out");
|
||||
else parts.push(`opacity ${o1.toFixed(1)}→${o2.toFixed(1)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Scale (from props)
|
||||
if (props.includes("scale") || props.includes("scaleX") || props.includes("scaleY")) {
|
||||
parts.push("scales");
|
||||
}
|
||||
|
||||
// Size changes
|
||||
if (first && last) {
|
||||
const dw = last.w - first.w;
|
||||
const dh = last.h - first.h;
|
||||
if (Math.abs(dw) > 5) parts.push(`width ${first.w}→${last.w}px`);
|
||||
if (Math.abs(dh) > 5) parts.push(`height ${first.h}→${last.h}px`);
|
||||
}
|
||||
|
||||
// Visibility
|
||||
if (first && last && first.visible !== last.visible) {
|
||||
parts.push(last.visible ? "becomes visible" : "becomes hidden");
|
||||
}
|
||||
|
||||
// Final position
|
||||
if (last && !last.missing) {
|
||||
parts.push(`ends at (${last.x}, ${last.y}) ${last.w}×${last.h}px`);
|
||||
}
|
||||
|
||||
// Flags
|
||||
if (flags.length > 0) {
|
||||
parts.push(`FLAGS: ${flags.join(", ")}`);
|
||||
}
|
||||
|
||||
return parts.join(". ") + ".";
|
||||
}
|
||||
|
||||
// ─── Flag computation ───────────────────────────────────────────────────────
|
||||
|
||||
function computeFlags(tw, bboxes, { width, height }) {
|
||||
const flags = [];
|
||||
const dur = tw.end - tw.start;
|
||||
|
||||
// No samples at all (an onUpdate driver has no element to measure) is not evidence of
|
||||
// a degenerate or invisible box — `[].every()` is vacuously true, so guard the
|
||||
// geometry-derived flags. The pacing flags below read only start/end and still apply.
|
||||
if (bboxes.length && bboxes.every((b) => b.w === 0 || b.h === 0)) flags.push("degenerate");
|
||||
|
||||
const anyOffscreen = bboxes.some(
|
||||
(b) =>
|
||||
b.x + b.w <= 0 ||
|
||||
b.y + b.h <= 0 ||
|
||||
b.x >= width ||
|
||||
b.y >= height ||
|
||||
b.x < -b.w * 0.5 ||
|
||||
b.y < -b.h * 0.5 ||
|
||||
b.x + b.w > width + b.w * 0.5 ||
|
||||
b.y + b.h > height + b.h * 0.5,
|
||||
);
|
||||
if (anyOffscreen) flags.push("offscreen");
|
||||
|
||||
if (
|
||||
bboxes.length &&
|
||||
bboxes.every((b) => b.opacity !== undefined && b.opacity < 0.01 && b.visible)
|
||||
) {
|
||||
flags.push("invisible");
|
||||
}
|
||||
|
||||
if (dur < 0.2 && tw.props.some((p) => ["y", "x", "opacity", "scale"].includes(p))) {
|
||||
flags.push("paced-fast");
|
||||
}
|
||||
if (dur > 2.0) flags.push("paced-slow");
|
||||
|
||||
return flags;
|
||||
}
|
||||
|
||||
function markCollisions(tweens) {
|
||||
for (let i = 0; i < tweens.length; i++) {
|
||||
for (let j = i + 1; j < tweens.length; j++) {
|
||||
const a = tweens[i];
|
||||
const b = tweens[j];
|
||||
if (a.end <= b.start || b.end <= a.start) continue;
|
||||
for (const ba of a.bboxes) {
|
||||
const bb = b.bboxes.find((x) => Math.abs(x.t - ba.t) < 0.05);
|
||||
if (!bb) continue;
|
||||
const overlap = rectOverlapArea(ba, bb);
|
||||
const aArea = ba.w * ba.h;
|
||||
if (aArea > 0 && overlap / aArea > 0.3) {
|
||||
if (!a.flags.includes("collision")) a.flags.push("collision");
|
||||
if (!b.flags.includes("collision")) b.flags.push("collision");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rectOverlapArea(a, b) {
|
||||
const x1 = Math.max(a.x, b.x);
|
||||
const y1 = Math.max(a.y, b.y);
|
||||
const x2 = Math.min(a.x + a.w, b.x + b.w);
|
||||
const y2 = Math.min(a.y + a.h, b.y + b.h);
|
||||
return Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
|
||||
}
|
||||
|
||||
// ─── Composition-level analysis ─────────────────────────────────────────────
|
||||
|
||||
function buildTimeline(tweens, duration) {
|
||||
const cols = 60;
|
||||
const lines = [];
|
||||
const secPerCol = duration / cols;
|
||||
|
||||
lines.push("Timeline (" + duration.toFixed(1) + "s, each char ≈ " + secPerCol.toFixed(2) + "s):");
|
||||
lines.push(" " + "0s" + " ".repeat(cols - 8) + duration.toFixed(0) + "s");
|
||||
lines.push(" " + "┼" + "─".repeat(cols - 1) + "┤");
|
||||
|
||||
for (const tw of tweens) {
|
||||
const startCol = Math.floor(tw.start / secPerCol);
|
||||
const endCol = Math.min(cols, Math.ceil(tw.end / secPerCol));
|
||||
const bar =
|
||||
" ".repeat(startCol) +
|
||||
"█".repeat(Math.max(1, endCol - startCol)) +
|
||||
" ".repeat(Math.max(0, cols - endCol));
|
||||
const label = tw.selector + " " + tw.props.join("+");
|
||||
lines.push(" " + bar + " " + label);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function computeDensity(tweens, duration) {
|
||||
const buckets = [];
|
||||
for (let t = 0; t < duration; t += 0.5) {
|
||||
const active = tweens.filter((tw) => tw.start <= t + 0.5 && tw.end >= t);
|
||||
buckets.push({ t: +t.toFixed(1), activeTweens: active.length });
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
function findDeadZones(density, duration) {
|
||||
const zones = [];
|
||||
let zoneStart = null;
|
||||
for (const d of density) {
|
||||
if (d.activeTweens === 0) {
|
||||
if (zoneStart === null) zoneStart = d.t;
|
||||
} else {
|
||||
if (zoneStart !== null) {
|
||||
const zoneEnd = d.t;
|
||||
if (zoneEnd - zoneStart >= 1.0) {
|
||||
zones.push({
|
||||
start: zoneStart,
|
||||
end: zoneEnd,
|
||||
duration: +(zoneEnd - zoneStart).toFixed(1),
|
||||
note:
|
||||
"No animation for " +
|
||||
(zoneEnd - zoneStart).toFixed(1) +
|
||||
"s. Intentional hold or missing entrance?",
|
||||
});
|
||||
}
|
||||
zoneStart = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (zoneStart !== null && duration - zoneStart >= 1.0) {
|
||||
zones.push({
|
||||
start: zoneStart,
|
||||
end: +duration.toFixed(1),
|
||||
duration: +(duration - zoneStart).toFixed(1),
|
||||
note:
|
||||
"No animation for " +
|
||||
(duration - zoneStart).toFixed(1) +
|
||||
"s at end. Final hold or missing outro?",
|
||||
});
|
||||
}
|
||||
return zones;
|
||||
}
|
||||
|
||||
function detectStaggers(tweens) {
|
||||
const groups = [];
|
||||
const used = new Set();
|
||||
|
||||
for (let i = 0; i < tweens.length; i++) {
|
||||
if (used.has(i)) continue;
|
||||
const tw = tweens[i];
|
||||
const group = [tw];
|
||||
used.add(i);
|
||||
|
||||
for (let j = i + 1; j < tweens.length; j++) {
|
||||
if (used.has(j)) continue;
|
||||
const other = tweens[j];
|
||||
const sameProps = tw.props.join(",") === other.props.join(",");
|
||||
const sameDuration = Math.abs(tw.duration - other.duration) < 0.05;
|
||||
const closeInTime = other.start - tw.start < tw.duration * 4;
|
||||
if (sameProps && sameDuration && closeInTime) {
|
||||
group.push(other);
|
||||
used.add(j);
|
||||
}
|
||||
}
|
||||
|
||||
if (group.length >= 3) {
|
||||
const intervals = [];
|
||||
for (let k = 1; k < group.length; k++) {
|
||||
intervals.push(+(group[k].start - group[k - 1].start).toFixed(3));
|
||||
}
|
||||
const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
|
||||
const maxDrift = Math.max(...intervals.map((iv) => Math.abs(iv - avgInterval)));
|
||||
const consistent = maxDrift < avgInterval * 0.3;
|
||||
|
||||
groups.push({
|
||||
elements: group.map((g) => g.selector),
|
||||
props: tw.props,
|
||||
count: group.length,
|
||||
intervals,
|
||||
avgInterval: +avgInterval.toFixed(3),
|
||||
consistent,
|
||||
note: consistent
|
||||
? group.length +
|
||||
" elements stagger at " +
|
||||
(avgInterval * 1000).toFixed(0) +
|
||||
"ms intervals"
|
||||
: group.length +
|
||||
" elements stagger with uneven intervals (" +
|
||||
intervals.map((iv) => (iv * 1000).toFixed(0) + "ms").join(", ") +
|
||||
")",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
function buildElementLifecycles(tweens) {
|
||||
const elements = {};
|
||||
for (const tw of tweens) {
|
||||
const sel = tw.selector;
|
||||
if (!elements[sel]) {
|
||||
elements[sel] = { firstTween: tw.start, lastTween: tw.end, tweenCount: 0, props: new Set() };
|
||||
}
|
||||
elements[sel].firstTween = Math.min(elements[sel].firstTween, tw.start);
|
||||
elements[sel].lastTween = Math.max(elements[sel].lastTween, tw.end);
|
||||
elements[sel].tweenCount++;
|
||||
tw.props.forEach((p) => elements[sel].props.add(p));
|
||||
}
|
||||
|
||||
const result = {};
|
||||
for (const [sel, data] of Object.entries(elements)) {
|
||||
const lastBbox = findLastBbox(tweens, sel);
|
||||
result[sel] = {
|
||||
firstAppears: +data.firstTween.toFixed(3),
|
||||
lastAnimates: +data.lastTween.toFixed(3),
|
||||
tweenCount: data.tweenCount,
|
||||
props: [...data.props],
|
||||
endsVisible: lastBbox ? lastBbox.opacity > 0.1 && lastBbox.visible : null,
|
||||
finalPosition: lastBbox
|
||||
? { x: lastBbox.x, y: lastBbox.y, w: lastBbox.w, h: lastBbox.h }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function findLastBbox(tweens, selector) {
|
||||
for (let i = tweens.length - 1; i >= 0; i--) {
|
||||
if (tweens[i].selector === selector && tweens[i].bboxes?.length > 0) {
|
||||
return tweens[i].bboxes[tweens[i].bboxes.length - 1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function captureSnapshots(session, tweens, duration) {
|
||||
const times = [0, duration * 0.25, duration * 0.5, duration * 0.75, duration - 0.1];
|
||||
const snapshots = [];
|
||||
|
||||
for (const t of times) {
|
||||
await seekTo(session, t);
|
||||
const visible = await session.page.evaluate(() => {
|
||||
const out = [];
|
||||
const els = document.querySelectorAll("[id]");
|
||||
for (const el of els) {
|
||||
const cs = getComputedStyle(el);
|
||||
if (cs.display === "none") continue;
|
||||
const opacity = parseFloat(cs.opacity);
|
||||
if (opacity < 0.01) continue;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width < 1 || rect.height < 1) continue;
|
||||
out.push({
|
||||
id: el.id,
|
||||
x: Math.round(rect.x),
|
||||
y: Math.round(rect.y),
|
||||
w: Math.round(rect.width),
|
||||
h: Math.round(rect.height),
|
||||
opacity: +opacity.toFixed(2),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
const activeTweens = tweens
|
||||
.filter((tw) => tw.start <= t && tw.end >= t)
|
||||
.map((tw) => tw.selector);
|
||||
|
||||
snapshots.push({
|
||||
t: +t.toFixed(2),
|
||||
visibleElements: visible.length,
|
||||
animatingNow: activeTweens,
|
||||
elements: visible,
|
||||
});
|
||||
}
|
||||
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
// ─── Output ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function printSummary(report) {
|
||||
console.log(
|
||||
`\nAnimation map: ${report.mappedTweens}/${report.totalTweens} tweens (skipped ${report.skippedMicroTweens} micro-tweens)`,
|
||||
);
|
||||
|
||||
const flagCounts = {};
|
||||
for (const tw of report.tweens) {
|
||||
for (const f of tw.flags) flagCounts[f] = (flagCounts[f] ?? 0) + 1;
|
||||
}
|
||||
if (Object.keys(flagCounts).length > 0) {
|
||||
for (const [f, n] of Object.entries(flagCounts)) console.log(` ${f}: ${n}`);
|
||||
}
|
||||
if (report.staggers?.length > 0) {
|
||||
console.log(` staggers: ${report.staggers.map((s) => s.note).join("; ")}`);
|
||||
}
|
||||
if (report.deadZones?.length > 0) {
|
||||
console.log(
|
||||
` dead zones: ${report.deadZones.map((z) => z.start + "-" + z.end + "s").join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(report.choreography);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
let positional = 0;
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a.startsWith("--")) {
|
||||
const k = a.slice(2);
|
||||
const v = argv[i + 1]?.startsWith("--") ? true : argv[++i];
|
||||
out[k] = v;
|
||||
} else if (positional === 0) {
|
||||
out.composition = a;
|
||||
positional++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function die(msg) {
|
||||
console.error(`animation-map: ${msg}`);
|
||||
process.exit(2);
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const HELPERS = [
|
||||
join(REPO_ROOT, "skills", "hyperframes-animation", "scripts", "animation-map.mjs"),
|
||||
join(REPO_ROOT, "skills", "hyperframes-creative", "scripts", "contrast-report.mjs"),
|
||||
];
|
||||
|
||||
describe("HyperFrames skill helpers", () => {
|
||||
for (const helper of HELPERS)
|
||||
it(`${helper.split("/").at(-1)} bundles modular input and uses rational fps`, () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-helper-test-"));
|
||||
const packageDir = join(root, "node_modules", "@hyperframes", "producer");
|
||||
const corePackageDir = join(root, "node_modules", "@hyperframes", "core");
|
||||
const sharpPackageDir = join(root, "node_modules", "sharp");
|
||||
const compositionDir = join(root, "composition");
|
||||
mkdirSync(packageDir, { recursive: true });
|
||||
mkdirSync(corePackageDir, { recursive: true });
|
||||
mkdirSync(sharpPackageDir, { recursive: true });
|
||||
mkdirSync(compositionDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(packageDir, "package.json"),
|
||||
JSON.stringify({ name: "@hyperframes/producer", type: "module", exports: "./index.mjs" }),
|
||||
);
|
||||
writeFileSync(
|
||||
join(packageDir, "index.mjs"),
|
||||
[
|
||||
'import { readFileSync } from "node:fs";',
|
||||
'import { join } from "node:path";',
|
||||
"export async function createFileServer(options) {",
|
||||
' const bundled = readFileSync(join(options.compiledDir, "index.html"), "utf8");',
|
||||
' if (bundled !== "<!doctype html><main>bundled modular composition</main>") {',
|
||||
" throw new Error(`UNEXPECTED_BUNDLE=${bundled}`);",
|
||||
" }",
|
||||
' return { url: "http://test", close() {} };',
|
||||
"}",
|
||||
"export async function createCaptureSession(_url, _out, options) {",
|
||||
" throw new Error(`CAPTURE_OPTIONS=${JSON.stringify(options)}`);",
|
||||
"}",
|
||||
"export async function initializeSession() {}",
|
||||
"export async function closeCaptureSession() {}",
|
||||
"export async function getCompositionDuration() { return 0; }",
|
||||
].join("\n"),
|
||||
);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "@hyperframes/core",
|
||||
type: "module",
|
||||
exports: { ".": "./index.mjs", "./compiler": "./compiler.mjs" },
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "index.mjs"),
|
||||
[
|
||||
"export function parseFps(input) {",
|
||||
" if (input === '30000/1001') return { ok: true, value: { num: 30000, den: 1001 } };",
|
||||
" if (input === '29.97') return { ok: false, reason: 'ambiguous-decimal' };",
|
||||
" return { ok: true, value: { num: Number(input), den: 1 } };",
|
||||
"}",
|
||||
].join("\n"),
|
||||
);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "compiler.mjs"),
|
||||
[
|
||||
"export async function bundleToSingleHtml() {",
|
||||
' return "<!doctype html><main>bundled modular composition</main>";',
|
||||
"}",
|
||||
].join("\n"),
|
||||
);
|
||||
writeFileSync(
|
||||
join(sharpPackageDir, "package.json"),
|
||||
JSON.stringify({ name: "sharp", type: "module", exports: "./index.mjs" }),
|
||||
);
|
||||
writeFileSync(join(sharpPackageDir, "index.mjs"), "export default function sharp() {}\n");
|
||||
|
||||
try {
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[helper, compositionDir, "--fps", "30000/1001", "--out", join(root, "output")],
|
||||
{
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
HYPERFRAMES_SKILL_NODE_MODULES: join(root, "node_modules"),
|
||||
},
|
||||
},
|
||||
);
|
||||
const output = `${result.stdout}\n${result.stderr}`;
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(output, /CAPTURE_OPTIONS=.*"fps":\{"num":30000,"den":1001\}/);
|
||||
|
||||
const invalid = spawnSync(
|
||||
process.execPath,
|
||||
[helper, compositionDir, "--fps", "29.97", "--out", join(root, "invalid-output")],
|
||||
{
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
HYPERFRAMES_SKILL_NODE_MODULES: join(root, "node_modules"),
|
||||
},
|
||||
},
|
||||
);
|
||||
const invalidOutput = `${invalid.stdout}\n${invalid.stderr}`;
|
||||
assert.notEqual(invalid.status, 0);
|
||||
assert.match(invalidOutput, /Invalid --fps "29\.97": ambiguous-decimal/);
|
||||
assert.doesNotMatch(invalidOutput, /CAPTURE_OPTIONS=/);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The two package-loader.mjs copies are intentionally byte-identical (each
|
||||
// skill ships standalone, so neither can import the other's) and now carry
|
||||
// shared logic (initializeSessionWithRetry + FALLBACK_TRANSIENT_PATTERNS)
|
||||
// that a future fix could land in one copy and silently miss in the other —
|
||||
// the exact drift class the audio.mjs identity pin was born to catch.
|
||||
describe("package-loader parity", () => {
|
||||
it("package-loader.mjs is byte-identical to hyperframes-creative's copy (the stated contract)", () => {
|
||||
const here = readFileSync(
|
||||
join(REPO_ROOT, "skills", "hyperframes-animation", "scripts", "package-loader.mjs"),
|
||||
"utf8",
|
||||
);
|
||||
const sibling = readFileSync(
|
||||
join(REPO_ROOT, "skills", "hyperframes-creative", "scripts", "package-loader.mjs"),
|
||||
"utf8",
|
||||
);
|
||||
assert.equal(here, sibling);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Transient-init retry (the zero-duration false-fail fix) ─────────────────
|
||||
// A valid modular project's sub-composition timelines register asynchronously;
|
||||
// the first initializeSession can time out with the transient "zero duration /
|
||||
// Runtime ready: false" diagnostic. The render pipeline closes the crashed
|
||||
// session and retries once with a fresh browser (probeStage) — the standalone
|
||||
// helpers must do the same instead of reporting the project as zero-duration.
|
||||
|
||||
/** Write a fake node_modules with the given producer index.mjs source. */
|
||||
function writeFakeEnv(root, producerIndexSource) {
|
||||
const packageDir = join(root, "node_modules", "@hyperframes", "producer");
|
||||
const corePackageDir = join(root, "node_modules", "@hyperframes", "core");
|
||||
const sharpPackageDir = join(root, "node_modules", "sharp");
|
||||
const compositionDir = join(root, "composition");
|
||||
mkdirSync(packageDir, { recursive: true });
|
||||
mkdirSync(corePackageDir, { recursive: true });
|
||||
mkdirSync(sharpPackageDir, { recursive: true });
|
||||
mkdirSync(compositionDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(packageDir, "package.json"),
|
||||
JSON.stringify({ name: "@hyperframes/producer", type: "module", exports: "./index.mjs" }),
|
||||
);
|
||||
writeFileSync(join(packageDir, "index.mjs"), producerIndexSource);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "@hyperframes/core",
|
||||
type: "module",
|
||||
exports: { ".": "./index.mjs", "./compiler": "./compiler.mjs" },
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "index.mjs"),
|
||||
"export function parseFps(input) { return { ok: true, value: { num: Number(input), den: 1 } }; }",
|
||||
);
|
||||
writeFileSync(
|
||||
join(corePackageDir, "compiler.mjs"),
|
||||
'export async function bundleToSingleHtml() { return "<!doctype html><main>x</main>"; }',
|
||||
);
|
||||
writeFileSync(
|
||||
join(sharpPackageDir, "package.json"),
|
||||
JSON.stringify({ name: "sharp", type: "module", exports: "./index.mjs" }),
|
||||
);
|
||||
writeFileSync(join(sharpPackageDir, "index.mjs"), "export default function sharp() {}\n");
|
||||
return compositionDir;
|
||||
}
|
||||
|
||||
function runHelper(helper, root, compositionDir) {
|
||||
const result = spawnSync(process.execPath, [helper, compositionDir, "--out", join(root, "out")], {
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, HYPERFRAMES_SKILL_NODE_MODULES: join(root, "node_modules") },
|
||||
});
|
||||
return `${result.stdout}\n${result.stderr}`;
|
||||
}
|
||||
|
||||
const FAKE_PRODUCER_COMMON = [
|
||||
'export async function createFileServer() { return { url: "http://test", close() {} }; }',
|
||||
'export async function createCaptureSession() { console.error("SESSION_CREATED"); return {}; }',
|
||||
'export async function closeCaptureSession() { console.error("SESSION_CLOSED"); }',
|
||||
"export async function getCompositionDuration() { return 0; }",
|
||||
].join("\n");
|
||||
|
||||
describe("transient-init retry", () => {
|
||||
for (const helper of HELPERS) {
|
||||
it(`${helper.split("/").at(-1)} retries a transient zero-duration init once with a fresh session`, () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-retry-test-"));
|
||||
try {
|
||||
const compositionDir = writeFakeEnv(
|
||||
root,
|
||||
[
|
||||
FAKE_PRODUCER_COMMON,
|
||||
"let initCalls = 0;",
|
||||
"export async function initializeSession() {",
|
||||
" initCalls++;",
|
||||
" if (initCalls === 1) {",
|
||||
// The transient shape: readiness deadline hit before async
|
||||
// sub-composition timelines landed (Runtime ready: false).
|
||||
' throw new Error("Composition has zero duration after initialization.\\nRuntime ready: false");',
|
||||
" }",
|
||||
' throw new Error("INIT_ATTEMPT_2_REACHED");',
|
||||
"}",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const output = runHelper(helper, root, compositionDir);
|
||||
|
||||
// Retried: fresh session created for attempt 2, crashed one closed.
|
||||
assert.match(output, /retrying with a fresh browser session/);
|
||||
assert.equal((output.match(/SESSION_CREATED/g) ?? []).length, 2);
|
||||
assert.equal((output.match(/SESSION_CLOSED/g) ?? []).length, 2);
|
||||
// ...and the retry genuinely re-ran init (bounded: no third attempt).
|
||||
assert.match(output, /INIT_ATTEMPT_2_REACHED/);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it(`${helper.split("/").at(-1)} does NOT retry a genuine authoring failure (Runtime ready: true)`, () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-retry-test-"));
|
||||
try {
|
||||
const compositionDir = writeFakeEnv(
|
||||
root,
|
||||
[
|
||||
FAKE_PRODUCER_COMMON,
|
||||
"export async function initializeSession() {",
|
||||
// The fast-fail shape: runtime IS ready, there is genuinely no
|
||||
// timeline/duration — an authoring bug retries can't fix.
|
||||
' throw new Error("Composition has zero duration after initialization.\\nRuntime ready: true");',
|
||||
"}",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const output = runHelper(helper, root, compositionDir);
|
||||
|
||||
assert.doesNotMatch(output, /retrying with a fresh browser session/);
|
||||
assert.equal((output.match(/SESSION_CREATED/g) ?? []).length, 1);
|
||||
assert.match(output, /Composition has zero duration/);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("prefers the producer's own isTransientBrowserError classifier when exported", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-retry-test-"));
|
||||
try {
|
||||
const compositionDir = writeFakeEnv(
|
||||
root,
|
||||
[
|
||||
FAKE_PRODUCER_COMMON,
|
||||
// A message the frozen fallback patterns would NOT match — only the
|
||||
// producer-provided classifier can mark it transient.
|
||||
"export function isTransientBrowserError(err) { return String(err && err.message).includes('CUSTOM_TRANSIENT'); }",
|
||||
"let initCalls = 0;",
|
||||
"export async function initializeSession() {",
|
||||
" initCalls++;",
|
||||
' if (initCalls === 1) throw new Error("CUSTOM_TRANSIENT flake");',
|
||||
' throw new Error("INIT_ATTEMPT_2_REACHED");',
|
||||
"}",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const output = runHelper(HELPERS[0], root, compositionDir);
|
||||
|
||||
assert.match(output, /retrying with a fresh browser session/);
|
||||
assert.match(output, /INIT_ATTEMPT_2_REACHED/);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ── Proxy-driver tweens (the false dead-zone fix) ───────────────────────────
|
||||
// The proxy-driver idiom tweens a plain object and applies the motion inside
|
||||
// onUpdate, so the tween's targets() holds no Element. The map used to drop those
|
||||
// tweens outright, which meant computeDensity counted zero active tweens over their
|
||||
// span and findDeadZones reported real motion as a dead zone.
|
||||
//
|
||||
// The fake producer hands animation-map a session whose page.evaluate runs the
|
||||
// callback in this process, against a stubbed window/document. That exercises the real
|
||||
// enumerateTweens/computeDensity/findDeadZones code without a browser.
|
||||
const FAKE_PROXY_DRIVER_ENV = [
|
||||
"globalThis.Element = class Element {};",
|
||||
"const mover = new globalThis.Element();",
|
||||
'mover.id = "mover";',
|
||||
"mover.classList = [];",
|
||||
// 0-1s: an ordinary element tween.
|
||||
"const elementTween = {",
|
||||
" targets: () => [mover],",
|
||||
' vars: { x: 900, duration: 1, ease: "power2.out" },',
|
||||
" startTime: () => 0,",
|
||||
" duration: () => 1,",
|
||||
"};",
|
||||
// 2-4s: a proxy driver. Real motion, no Element target.
|
||||
"const proxyTween = {",
|
||||
" targets: () => [{ v: 0 }],",
|
||||
' vars: { v: 100, duration: 2, ease: "none", onUpdate() {} },',
|
||||
" startTime: () => 2,",
|
||||
" duration: () => 2,",
|
||||
"};",
|
||||
// 2-4s as well: a bare spacer with no onUpdate. Produces nothing, must stay dropped,
|
||||
// otherwise every full-span anchor tween would mask genuine dead zones.
|
||||
"const spacerTween = {",
|
||||
" targets: () => [{}],",
|
||||
" vars: { duration: 2 },",
|
||||
" startTime: () => 2,",
|
||||
" duration: () => 2,",
|
||||
"};",
|
||||
"const timeline = {",
|
||||
" getChildren: () => [elementTween, proxyTween, spacerTween],",
|
||||
" startTime: () => 0,",
|
||||
" duration: () => 4,",
|
||||
" seek() {},",
|
||||
"};",
|
||||
"globalThis.window = { __timelines: { main: timeline } };",
|
||||
"globalThis.document = { querySelector: () => null, querySelectorAll: () => [] };",
|
||||
"globalThis.getComputedStyle = () => ({",
|
||||
' opacity: "1",',
|
||||
' visibility: "visible",',
|
||||
' display: "block",',
|
||||
"});",
|
||||
'export async function createFileServer() { return { url: "http://test", close() {} }; }',
|
||||
"export async function createCaptureSession() {",
|
||||
" return { page: { evaluate: async (fn, arg) => fn(arg) } };",
|
||||
"}",
|
||||
"export async function closeCaptureSession() {}",
|
||||
"export async function initializeSession() {}",
|
||||
"export async function getCompositionDuration() { return 4; }",
|
||||
].join("\n");
|
||||
|
||||
// The WebGL/uniform shape, e.g. skills/music-to-video/references/templates/
|
||||
// held-message-living-field: the TIMELINE carries onUpdate: renderFrame and its children
|
||||
// tween plain uniform objects. No child has an onUpdate of its own, so a tween-local
|
||||
// discriminator misses all of them and the whole composition reads as one dead zone.
|
||||
const FAKE_PARENT_DRIVER_ENV = [
|
||||
"globalThis.Element = class Element {};",
|
||||
"const uniformTween = {",
|
||||
" targets: () => [{ value: 0 }],",
|
||||
' vars: { value: 12, duration: 12, ease: "none" },',
|
||||
" startTime: () => 0,",
|
||||
" duration: () => 12,",
|
||||
"};",
|
||||
// Same driven timeline, but this one alters nothing — the repaint it triggers is
|
||||
// identical frame to frame, so it must NOT count as motion.
|
||||
"const spacerTween = {",
|
||||
" targets: () => [{}],",
|
||||
" vars: { duration: 12 },",
|
||||
" startTime: () => 0,",
|
||||
" duration: () => 12,",
|
||||
"};",
|
||||
"const timeline = {",
|
||||
" vars: { onUpdate() {} },",
|
||||
" getChildren: () => [uniformTween, spacerTween],",
|
||||
" startTime: () => 0,",
|
||||
" duration: () => 12,",
|
||||
" seek() {},",
|
||||
"};",
|
||||
"globalThis.window = { __timelines: { main: timeline } };",
|
||||
"globalThis.document = { querySelector: () => null, querySelectorAll: () => [] };",
|
||||
"globalThis.getComputedStyle = () => ({",
|
||||
' opacity: "1",',
|
||||
' visibility: "visible",',
|
||||
' display: "block",',
|
||||
"});",
|
||||
'export async function createFileServer() { return { url: "http://test", close() {} }; }',
|
||||
"export async function createCaptureSession() {",
|
||||
" return { page: { evaluate: async (fn, arg) => fn(arg) } };",
|
||||
"}",
|
||||
"export async function closeCaptureSession() {}",
|
||||
"export async function initializeSession() {}",
|
||||
"export async function getCompositionDuration() { return 12; }",
|
||||
].join("\n");
|
||||
|
||||
describe("proxy-driver tweens", () => {
|
||||
it("counts an onUpdate driver's span instead of reporting it as a dead zone", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-proxy-test-"));
|
||||
try {
|
||||
const compositionDir = writeFakeEnv(root, FAKE_PROXY_DRIVER_ENV);
|
||||
const output = runHelper(HELPERS[0], root, compositionDir);
|
||||
const report = JSON.parse(readFileSync(join(root, "out", "animation-map.json"), "utf8"));
|
||||
|
||||
const drivers = report.tweens.filter((tw) => tw.driver === "onUpdate");
|
||||
assert.equal(drivers.length, 1, `expected one onUpdate driver in:\n${output}`);
|
||||
assert.equal(drivers[0].start, 2);
|
||||
assert.equal(drivers[0].end, 4);
|
||||
assert.equal(drivers[0].targets, 0);
|
||||
assert.deepEqual(drivers[0].bboxes, [], "there is no element to measure");
|
||||
// `[].every()` is vacuously true, so unmeasured must not read as degenerate/invisible.
|
||||
assert.deepEqual(drivers[0].flags, []);
|
||||
|
||||
assert.deepEqual(report.deadZones, [], "2-4s is animating, not dead");
|
||||
// The bare spacer stays out — only the element tween and the driver are mapped.
|
||||
assert.equal(report.tweens.length, 2);
|
||||
|
||||
// Per-ELEMENT analyses must not adopt the driver as a pseudo-element.
|
||||
assert.deepEqual(Object.keys(report.elements), ["#mover"]);
|
||||
assert.deepEqual(report.staggers, []);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("inherits a driver the TIMELINE owns, without counting a spacer under it", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hyperframes-skill-parent-driver-test-"));
|
||||
try {
|
||||
const compositionDir = writeFakeEnv(root, FAKE_PARENT_DRIVER_ENV);
|
||||
const output = runHelper(HELPERS[0], root, compositionDir);
|
||||
const report = JSON.parse(readFileSync(join(root, "out", "animation-map.json"), "utf8"));
|
||||
|
||||
const drivers = report.tweens.filter((tw) => tw.driver === "onUpdate");
|
||||
assert.equal(drivers.length, 1, `expected one inherited driver in:\n${output}`);
|
||||
assert.deepEqual(drivers[0].props, ["value"]);
|
||||
assert.equal(drivers[0].start, 0);
|
||||
assert.equal(drivers[0].end, 12);
|
||||
|
||||
assert.deepEqual(report.deadZones, [], "the uniform tween animates the whole span");
|
||||
// Nothing element-backed here at all, so both per-element analyses stay empty.
|
||||
assert.deepEqual(report.elements, {});
|
||||
assert.deepEqual(report.staggers, []);
|
||||
// The spacer changes no value, so the parent's onUpdate repaints an identical frame.
|
||||
// Counting it would mask a real dead zone.
|
||||
assert.equal(report.tweens.length, 1);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,415 @@
|
||||
// package-loader — bootstrap optional helper packages only when missing, with
|
||||
// defense-in-depth so a malicious or typo'd dependency can't run on install:
|
||||
// • specs are version-pinned (assertPinnedPackageSpecs) — no floating "latest"
|
||||
// • install runs `npm install --ignore-scripts` — package lifecycle scripts
|
||||
// never execute
|
||||
// • `--no-save` into a throwaway tmp dir — the host project is left untouched
|
||||
// • requires an interactive y/N (or an explicit $HYPERFRAMES_SKILL_BOOTSTRAP_DEPS=1)
|
||||
// • npm is spawned with an argv array (no shell) — never a built command string
|
||||
// The `installLine` strings below are DISPLAY ONLY (shown in the prompt / error
|
||||
// text); they are never handed to a shell or executed.
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, delimiter, dirname, join, parse, resolve, win32 as win32Path } from "node:path";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const VERSION_OVERRIDE_ENV = "HYPERFRAMES_SKILL_PKG_VERSION";
|
||||
const BOOTSTRAP_ENV = "HYPERFRAMES_SKILL_DEPS_BOOTSTRAPPED";
|
||||
const BOOTSTRAP_CONFIRM_ENV = "HYPERFRAMES_SKILL_BOOTSTRAP_DEPS";
|
||||
const NODE_MODULES_ENV = "HYPERFRAMES_SKILL_NODE_MODULES";
|
||||
|
||||
export async function importPackagesOrBootstrap(packageNames, options = {}) {
|
||||
const entries = new Map();
|
||||
const missing = [];
|
||||
|
||||
for (const packageName of packageNames) {
|
||||
const entry = resolvePackageEntry(packageName);
|
||||
if (entry) entries.set(packageName, entry);
|
||||
else missing.push(packageName);
|
||||
}
|
||||
|
||||
if (missing.length > 0 && !process.env[BOOTSTRAP_ENV]) {
|
||||
const npmPackages = options.npmPackages ?? missing;
|
||||
assertPinnedPackageSpecs(npmPackages);
|
||||
await confirmBootstrap(npmPackages);
|
||||
bootstrapWithNpmInstall(npmPackages);
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
[
|
||||
`Could not resolve required package(s): ${missing.join(", ")}`,
|
||||
"Install them in this project, for example:",
|
||||
` npm install --save-dev ${packageNames.map(shellQuote).join(" ")}`,
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
const modules = {};
|
||||
for (const [packageName, entry] of entries) {
|
||||
modules[packageName] = await import(pathToFileURL(entry).href);
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
|
||||
export async function bundleCompositionForCapture(compiler, projectDir) {
|
||||
const compiledDir = mkdtempSync(join(tmpdir(), "hyperframes-skill-bundle-"));
|
||||
try {
|
||||
const html = await compiler.bundleToSingleHtml(projectDir);
|
||||
writeFileSync(join(compiledDir, "index.html"), html);
|
||||
return {
|
||||
compiledDir,
|
||||
cleanup() {
|
||||
rmSync(compiledDir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
rmSync(compiledDir, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Transient-init retry ─────────────────────────────────────────────────────
|
||||
// Frozen snapshot of the engine's TRANSIENT_BROWSER_ERROR_PATTERNS (see
|
||||
// packages/engine frameCapture.ts), used only when the imported
|
||||
// @hyperframes/producer predates the isTransientBrowserError re-export. The
|
||||
// last pattern is the load-bearing one for modular projects: sub-composition
|
||||
// timelines register asynchronously, so a first init attempt can time out as
|
||||
// "zero duration / Runtime ready: false" on a valid project.
|
||||
const FALLBACK_TRANSIENT_PATTERNS = [
|
||||
/Navigating frame was detached/i,
|
||||
/Target closed/i,
|
||||
/Session closed/i,
|
||||
/browser has disconnected/i,
|
||||
/Page crashed/i,
|
||||
/Execution context was destroyed/i,
|
||||
/Cannot find context with specified id/i,
|
||||
/Failed to launch the browser process/i,
|
||||
/Navigation timeout of \d+ ms exceeded/i,
|
||||
/ECONNREFUSED/i,
|
||||
/net::ERR_NETWORK_CHANGED/i,
|
||||
/Composition has zero duration[\s\S]*Runtime ready: false/,
|
||||
];
|
||||
|
||||
/**
|
||||
* Create + initialize a capture session with the canonical transient-init
|
||||
* retry/cleanup the render pipeline uses (see probeStage in
|
||||
* @hyperframes/producer): on a transient failure, close the crashed session
|
||||
* and retry ONCE with a fresh browser. Without this, a standalone helper
|
||||
* false-fails valid modular projects whose sub-composition timelines land a
|
||||
* beat after the first readiness deadline ("zero duration" with
|
||||
* "Runtime ready: false").
|
||||
*
|
||||
* `producer` is the imported @hyperframes/producer namespace;
|
||||
* `createSession` is a factory returning a fresh (uninitialized) session.
|
||||
* Non-transient init failures (e.g. the "Runtime ready: true" zero-duration
|
||||
* fast-fail — a genuine authoring bug) still throw on the first attempt.
|
||||
*/
|
||||
export async function initializeSessionWithRetry(producer, createSession, options = {}) {
|
||||
const maxAttempts = options.maxAttempts ?? 2;
|
||||
const log = options.log ?? ((message) => console.error(message));
|
||||
const isTransient =
|
||||
typeof producer.isTransientBrowserError === "function"
|
||||
? producer.isTransientBrowserError
|
||||
: (err) => {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return FALLBACK_TRANSIENT_PATTERNS.some((pattern) => pattern.test(message));
|
||||
};
|
||||
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const session = await createSession();
|
||||
try {
|
||||
await producer.initializeSession(session);
|
||||
return session;
|
||||
} catch (error) {
|
||||
await producer.closeCaptureSession(session).catch(() => {});
|
||||
if (attempt >= maxAttempts || !isTransient(error)) throw error;
|
||||
log(
|
||||
`transient browser-init failure (attempt ${attempt}/${maxAttempts}): ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
log("retrying with a fresh browser session...");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function hyperframesPackageSpec(packageName) {
|
||||
const override = process.env[VERSION_OVERRIDE_ENV]?.trim();
|
||||
if (override) return `${packageName}@${override}`;
|
||||
|
||||
const version = readBundledHyperframesVersion();
|
||||
if (version) return `${packageName}@${version}`;
|
||||
|
||||
// Global skill installs have no hyperframes package.json
|
||||
// in their ancestor chain, so the bundled version is unknowable. Fall back to
|
||||
// @latest instead of throwing: already-installed packages still import, and a
|
||||
// bootstrap install can still proceed (@latest satisfies the pinned-spec guard).
|
||||
process.stderr.write(
|
||||
[
|
||||
`hyperframes: could not determine the bundled version for ${packageName}; using @latest.`,
|
||||
`Set ${VERSION_OVERRIDE_ENV}=<version> to pin it.`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
return `${packageName}@latest`;
|
||||
}
|
||||
|
||||
function resolvePackageEntry(packageName) {
|
||||
const bases = [process.cwd(), HERE, ...envNodeModulesDirs(), ...nodeModulesDirsFromPath()];
|
||||
const { rootName, subpath } = splitPackageSpecifier(packageName);
|
||||
|
||||
const seen = new Set();
|
||||
for (const base of bases) {
|
||||
const normalized = resolve(base);
|
||||
if (seen.has(normalized)) continue;
|
||||
seen.add(normalized);
|
||||
|
||||
try {
|
||||
return createRequire(join(normalized, "__hyperframes_skill_loader__.cjs")).resolve(
|
||||
packageName,
|
||||
);
|
||||
} catch {
|
||||
const packageDir = findPackageDir(normalized, rootName);
|
||||
const packageEntry = packageDir ? readPackageEntry(packageDir, subpath) : null;
|
||||
if (packageEntry) return packageEntry;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function splitPackageSpecifier(packageName) {
|
||||
const segments = packageName.split("/");
|
||||
const rootLength = packageName.startsWith("@") ? 2 : 1;
|
||||
return {
|
||||
rootName: segments.slice(0, rootLength).join("/"),
|
||||
subpath: segments.slice(rootLength).join("/"),
|
||||
};
|
||||
}
|
||||
|
||||
function readBundledHyperframesVersion() {
|
||||
for (const ancestor of ancestors(HERE)) {
|
||||
const directVersion = readPackageVersion(join(ancestor, "package.json"));
|
||||
if (directVersion) return directVersion;
|
||||
|
||||
const monorepoCliVersion = readPackageVersion(
|
||||
join(ancestor, "packages", "cli", "package.json"),
|
||||
);
|
||||
if (monorepoCliVersion) return monorepoCliVersion;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readPackageVersion(packageJsonPath) {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
||||
if (manifest.name === "hyperframes" || manifest.name === "@hyperframes/cli") {
|
||||
return typeof manifest.version === "string" ? manifest.version : null;
|
||||
}
|
||||
} catch {
|
||||
// Keep searching ancestor package manifests.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function envNodeModulesDirs() {
|
||||
return (process.env[NODE_MODULES_ENV] ?? "").split(delimiter).filter(Boolean);
|
||||
}
|
||||
|
||||
function nodeModulesDirsFromPath() {
|
||||
const dirs = [];
|
||||
for (const entry of (process.env.PATH ?? "").split(delimiter)) {
|
||||
if (!entry.endsWith(`${join("node_modules", ".bin")}`)) continue;
|
||||
dirs.push(dirname(entry));
|
||||
}
|
||||
return dirs;
|
||||
}
|
||||
|
||||
function findPackageDir(base, packageName) {
|
||||
const packageSegments = packageName.split("/");
|
||||
const roots =
|
||||
basename(base) === "node_modules"
|
||||
? [base]
|
||||
: ancestors(base).map((ancestor) => join(ancestor, "node_modules"));
|
||||
|
||||
for (const root of roots) {
|
||||
const packageDir = join(root, ...packageSegments);
|
||||
if (existsSync(join(packageDir, "package.json"))) return packageDir;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readPackageEntry(packageDir, subpath = "") {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
|
||||
const requestedExport = subpath ? manifest.exports?.[`./${subpath}`] : manifest.exports;
|
||||
const entry =
|
||||
exportEntry(requestedExport) ??
|
||||
(!subpath ? (manifest.module ?? manifest.main ?? "index.js") : null);
|
||||
if (!entry) return null;
|
||||
const entryPath = join(packageDir, entry);
|
||||
return existsSync(entryPath) ? entryPath : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function exportEntry(exports) {
|
||||
const root =
|
||||
typeof exports === "object" && exports !== null ? (exports["."] ?? exports) : exports;
|
||||
if (typeof root === "string") return root;
|
||||
if (typeof root !== "object" || root === null) return null;
|
||||
if (typeof root.import === "string") return root.import;
|
||||
if (typeof root.default === "string") return root.default;
|
||||
if (typeof root.node === "string") return root.node;
|
||||
if (typeof root.node === "object" && root.node !== null) {
|
||||
return root.node.import ?? root.node.default ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function assertPinnedPackageSpecs(packageSpecs) {
|
||||
const unpinned = packageSpecs.filter((spec) => !hasVersionSpec(spec));
|
||||
if (unpinned.length === 0) return;
|
||||
throw new Error(
|
||||
[
|
||||
`Refusing to bootstrap unpinned package spec(s): ${unpinned.join(", ")}`,
|
||||
"Pass pinned npm package specs, for example:",
|
||||
` ${packageSpecs.map((spec) => (hasVersionSpec(spec) ? spec : `${spec}@<version>`)).join(" ")}`,
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
function hasVersionSpec(packageSpec) {
|
||||
if (packageSpec.startsWith("@")) {
|
||||
const slash = packageSpec.indexOf("/");
|
||||
return slash !== -1 && packageSpec.indexOf("@", slash + 1) !== -1;
|
||||
}
|
||||
return packageSpec.includes("@");
|
||||
}
|
||||
|
||||
async function confirmBootstrap(packageSpecs) {
|
||||
if (process.env[BOOTSTRAP_CONFIRM_ENV] === "1") return;
|
||||
|
||||
const installLine = `npm install --ignore-scripts --no-save ${packageSpecs.map(shellQuote).join(" ")}`;
|
||||
if (!process.stdin.isTTY) {
|
||||
throw new Error(
|
||||
[
|
||||
"Required helper package(s) are missing.",
|
||||
"To allow a one-time temporary dependency bootstrap for this run, set:",
|
||||
` ${BOOTSTRAP_CONFIRM_ENV}=1`,
|
||||
"The bootstrap command will be:",
|
||||
` ${installLine}`,
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
||||
try {
|
||||
const answer = await rl.question(
|
||||
[
|
||||
"HyperFrames helper package(s) are missing.",
|
||||
`Run a temporary install with lifecycle scripts disabled?`,
|
||||
` ${installLine}`,
|
||||
"Proceed? [y/N] ",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!/^(y|yes)$/i.test(answer.trim())) {
|
||||
throw new Error("Dependency bootstrap cancelled.");
|
||||
}
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
|
||||
function ancestors(start) {
|
||||
const dirs = [];
|
||||
let current = resolve(start);
|
||||
const root = parse(current).root;
|
||||
while (current && current !== root) {
|
||||
dirs.push(current);
|
||||
current = dirname(current);
|
||||
}
|
||||
dirs.push(root);
|
||||
return dirs;
|
||||
}
|
||||
|
||||
export function resolveNpmSpawnCommand(
|
||||
args,
|
||||
platform = process.platform,
|
||||
env = process.env,
|
||||
nodeExecPath = process.execPath,
|
||||
pathExists = existsSync,
|
||||
) {
|
||||
if (platform !== "win32") {
|
||||
return { cmd: "npm", args, opts: { stdio: "inherit" } };
|
||||
}
|
||||
|
||||
const bundledNpmCli = win32Path.join(
|
||||
win32Path.dirname(nodeExecPath),
|
||||
"node_modules",
|
||||
"npm",
|
||||
"bin",
|
||||
"npm-cli.js",
|
||||
);
|
||||
const npmCli = [env.npm_execpath, bundledNpmCli].find(
|
||||
(candidate) => candidate && pathExists(candidate),
|
||||
);
|
||||
if (!npmCli) return null;
|
||||
return {
|
||||
cmd: env.npm_node_execpath || nodeExecPath,
|
||||
args: [npmCli, ...args],
|
||||
opts: { stdio: "inherit", windowsHide: true },
|
||||
};
|
||||
}
|
||||
|
||||
function bootstrapWithNpmInstall(packageNames) {
|
||||
const installRoot = mkdtempSync(join(tmpdir(), "hyperframes-skill-deps-"));
|
||||
const npmArgs = [
|
||||
"install",
|
||||
"--silent",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
"--ignore-scripts",
|
||||
"--no-save",
|
||||
"--prefix",
|
||||
installRoot,
|
||||
...packageNames,
|
||||
];
|
||||
const npmCommand = resolveNpmSpawnCommand(npmArgs);
|
||||
if (!npmCommand) {
|
||||
rmSync(installRoot, { recursive: true, force: true });
|
||||
throw new Error("Could not locate npm-cli.js for dependency bootstrap on Windows.");
|
||||
}
|
||||
const installResult = spawnSync(npmCommand.cmd, npmCommand.args, npmCommand.opts);
|
||||
|
||||
if (installResult.error) throw installResult.error;
|
||||
if (installResult.status !== 0) {
|
||||
rmSync(installRoot, { recursive: true, force: true });
|
||||
process.exit(installResult.status ?? 1);
|
||||
}
|
||||
|
||||
const args = [...process.argv.slice(1)];
|
||||
const result = spawnSync(process.execPath, args, {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
[BOOTSTRAP_ENV]: "1",
|
||||
[NODE_MODULES_ENV]: join(installRoot, "node_modules"),
|
||||
},
|
||||
});
|
||||
|
||||
rmSync(installRoot, { recursive: true, force: true });
|
||||
if (result.error) throw result.error;
|
||||
process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
function shellQuote(value) {
|
||||
if (/^[A-Za-z0-9_./:@=-]+$/.test(value)) return value;
|
||||
return `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolveNpmSpawnCommand } from "./package-loader.mjs";
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const ENV = "HYPERFRAMES_SKILL_PKG_VERSION";
|
||||
|
||||
test("resolveNpmSpawnCommand routes Windows npm through node and npm-cli.js", () => {
|
||||
const npmCli = "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js";
|
||||
const node = "C:\\Program Files\\nodejs\\node.exe";
|
||||
const resolved = resolveNpmSpawnCommand(
|
||||
["install", "@hyperframes/producer@0.7.55", "value & calc"],
|
||||
"win32",
|
||||
{ npm_execpath: npmCli, npm_node_execpath: node },
|
||||
node,
|
||||
(path) => path === npmCli,
|
||||
);
|
||||
|
||||
assert.deepEqual(resolved, {
|
||||
cmd: node,
|
||||
args: [npmCli, "install", "@hyperframes/producer@0.7.55", "value & calc"],
|
||||
opts: { stdio: "inherit", windowsHide: true },
|
||||
});
|
||||
assert.equal(resolved.opts.shell, undefined);
|
||||
});
|
||||
|
||||
test("resolveNpmSpawnCommand finds npm-cli.js beside node for direct Windows runs", () => {
|
||||
const node = "C:\\Program Files\\nodejs\\node.exe";
|
||||
const npmCli = "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js";
|
||||
const resolved = resolveNpmSpawnCommand(
|
||||
["install", "@hyperframes/producer@0.7.55"],
|
||||
"win32",
|
||||
{},
|
||||
node,
|
||||
(path) => path === npmCli,
|
||||
);
|
||||
|
||||
assert.equal(resolved?.cmd, node);
|
||||
assert.deepEqual(resolved?.args, [npmCli, "install", "@hyperframes/producer@0.7.55"]);
|
||||
});
|
||||
|
||||
test(
|
||||
"resolveNpmSpawnCommand launches the installed npm CLI on Windows",
|
||||
{ skip: process.platform !== "win32" },
|
||||
() => {
|
||||
const resolved = resolveNpmSpawnCommand(["--version"]);
|
||||
assert.ok(resolved);
|
||||
|
||||
const result = spawnSync(resolved.cmd, resolved.args, {
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout.trim(), /^\d+\./);
|
||||
},
|
||||
);
|
||||
|
||||
// (a) env override wins — no ancestor lookup, exact version echoed back.
|
||||
test("hyperframesPackageSpec: env override wins", async () => {
|
||||
const prev = process.env[ENV];
|
||||
process.env[ENV] = "9.9.9";
|
||||
try {
|
||||
const { hyperframesPackageSpec } = await import("./package-loader.mjs");
|
||||
assert.equal(hyperframesPackageSpec("@hyperframes/producer"), "@hyperframes/producer@9.9.9");
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env[ENV];
|
||||
else process.env[ENV] = prev;
|
||||
}
|
||||
});
|
||||
|
||||
// (b) resolvable version (in-repo) pins the bundled hyperframes/@hyperframes/cli version.
|
||||
test("hyperframesPackageSpec: resolvable in-repo version pins it", async () => {
|
||||
const prev = process.env[ENV];
|
||||
delete process.env[ENV];
|
||||
try {
|
||||
const { hyperframesPackageSpec } = await import("./package-loader.mjs");
|
||||
const spec = hyperframesPackageSpec("@hyperframes/producer");
|
||||
assert.match(spec, /^@hyperframes\/producer@\d+\.\d+\.\d+/);
|
||||
} finally {
|
||||
if (prev !== undefined) process.env[ENV] = prev;
|
||||
}
|
||||
});
|
||||
|
||||
// (c) unresolvable + no override -> @latest fallback, no throw (global-install case).
|
||||
// Copy the loader into an isolated temp dir whose ancestor chain has no hyperframes
|
||||
// package.json, and run node from there so cwd cannot resolve one either.
|
||||
test("hyperframesPackageSpec: unresolvable falls back to @latest without throwing", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-pkgloader-"));
|
||||
try {
|
||||
copyFileSync(join(HERE, "package-loader.mjs"), join(dir, "package-loader.mjs"));
|
||||
const probe = join(dir, "probe.mjs");
|
||||
writeFileSync(
|
||||
probe,
|
||||
[
|
||||
'import { hyperframesPackageSpec } from "./package-loader.mjs";',
|
||||
'process.stdout.write(hyperframesPackageSpec("@hyperframes/producer"));',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const res = spawnSync(process.execPath, [probe], { cwd: dir, encoding: "utf8" });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
assert.equal(res.stdout.trim(), "@hyperframes/producer@latest");
|
||||
assert.match(res.stderr, /using @latest/);
|
||||
assert.match(res.stderr, new RegExp(ENV));
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user