Skip to content

Commit 3e45ee9

Browse files
fix(studio): allow a local GSAP dependency mirror
1 parent fcec26e commit 3e45ee9

9 files changed

Lines changed: 421 additions & 33 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,11 @@ The server picks one of three modes by itself: **embedded** (the default for
874874
**monorepo** (the studio dev server, when you run from the source repo).
875875
`--background` works with the embedded server only.
876876

877+
To load the GSAP dependencies Studio adds from a local or private mirror, set
878+
`HYPERFRAMES_GSAP_BASE_URL` before starting the server. See
879+
[Serve GSAP from your own mirror](/packages/studio-server#serve-gsap-from-your-own-mirror)
880+
for the directory layout, restart requirements, and authored-resource scope.
881+
877882
<Note>
878883
Preview plays in real time, so paint-heavy compositions can stutter on your
879884
machine. Render seeks and captures one frame at a time, so the same work usually

‎docs/packages/studio-server.mdx‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,48 @@ the bundler inlines can be served with ids that a later save does not mint.
6666
bundle: (dir, options) => bundleToSingleHtml(dir, { runtime: "inline", ...options }),
6767
```
6868

69+
## Serve GSAP from your own mirror
70+
71+
Studio can load the GSAP dependencies it adds from a local or private mirror
72+
when jsDelivr is unavailable. Set `HYPERFRAMES_GSAP_BASE_URL` before starting
73+
the preview server or creating the Studio API:
74+
75+
```bash
76+
HYPERFRAMES_GSAP_BASE_URL=http://127.0.0.1:8080/vendor/npm \
77+
npx hyperframes preview ./my-video
78+
```
79+
80+
Serve the GSAP distribution files under that URL with this layout, using the
81+
versions your compositions need:
82+
83+
```text
84+
<mirror-root>/[email protected]/dist/gsap.min.js
85+
<mirror-root>/[email protected]/dist/CustomEase.min.js
86+
<mirror-root>/[email protected]/dist/MotionPathPlugin.min.js
87+
```
88+
89+
Studio uses the mirror for the GSAP, CustomEase, and MotionPathPlugin scripts
90+
it adds to previews, including dependencies loaded when you edit motion.
91+
Keep `gsap@<version>` in authored GSAP URLs so the server can infer which
92+
plugin version to add. When it cannot infer a version, it uses the framework's
93+
default, currently `3.15.0`.
94+
95+
The base must be an absolute HTTP(S) URL without credentials, a query string,
96+
or a fragment. Surrounding whitespace and trailing slashes are removed.
97+
An unset or empty value uses `https://cdn.jsdelivr.net/npm`; an invalid
98+
nonempty value stops API startup with a configuration error.
99+
100+
The server reads this setting once at startup. Restart it after changing the
101+
value. For a managed CLI preview, run `npx hyperframes preview ./my-video --stop`
102+
before starting it again with the new setting. Cached preview HTML is keyed
103+
by the normalized mirror URL, so a different mirror takes effect after restart
104+
without deleting the preview cache.
105+
106+
This setting changes only dependencies Studio adds. Your composition's own
107+
script, font, image, and media URLs stay as authored; serve those locally too
108+
for an offline project. If the selected mirror is unavailable or lacks a
109+
requested file, Studio does not retry that dependency through jsDelivr.
110+
69111
## Other entry points
70112

71113
| Import | Purpose |

‎packages/core/src/gsapCdn.test.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { gsapCdnDist, motionPathPluginUrl } from "./gsapCdn";
2+
import { gsapCdnDist, motionPathPluginUrl, normalizeGsapBaseUrl } from "./gsapCdn";
33

44
describe("gsapCdnDist", () => {
55
it("serves the composition's gsap version", () => {
@@ -16,3 +16,36 @@ describe("gsapCdnDist", () => {
1616
);
1717
});
1818
});
19+
20+
describe("GSAP mirrors", () => {
21+
it("uses a normalized npm mirror root while retaining numeric versions", () => {
22+
expect(gsapCdnDist("3.14.2", " https://mirror.example/vendor/npm/// ")).toBe(
23+
"https://mirror.example/vendor/npm/[email protected]/dist/",
24+
);
25+
expect(motionPathPluginUrl("3", "http://localhost:8080/npm")).toBe(
26+
"http://localhost:8080/npm/gsap@3/dist/MotionPathPlugin.min.js",
27+
);
28+
expect(gsapCdnDist("latest", "https://mirror.example/npm")).toBe(
29+
"https://mirror.example/npm/[email protected]/dist/",
30+
);
31+
});
32+
33+
it.each([undefined, "", " "])("keeps the default root for %j", (base) => {
34+
expect(normalizeGsapBaseUrl(base)).toBe("https://cdn.jsdelivr.net/npm");
35+
});
36+
37+
it.each([
38+
"/vendor/npm",
39+
"file:///vendor/npm",
40+
"https:mirror.example",
41+
"not a URL",
42+
"https://user:[email protected]/npm",
43+
"https://mirror.example/npm?token=x",
44+
"https://mirror.example/npm#section",
45+
"https://mirror.example/npm?",
46+
"https://mirror.example/npm#",
47+
])("rejects an invalid mirror instead of using the public CDN: %s", (base) => {
48+
expect(() => normalizeGsapBaseUrl(base)).toThrow();
49+
expect(() => motionPathPluginUrl("3.15.0", base)).toThrow();
50+
});
51+
});

‎packages/core/src/gsapCdn.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,27 @@
11
const GSAP_CDN_VERSION = "3.15.0";
2+
const GSAP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm";
3+
export const GSAP_BASE_URL_META = "hyperframes-gsap-base-url";
24

3-
export function gsapCdnDist(gsapVersion?: string): string {
5+
/** An npm-style mirror root; callers choose configuration without coupling this helper to a host. */
6+
export function normalizeGsapBaseUrl(baseUrl?: string): string {
7+
const value = baseUrl?.trim();
8+
if (!value) return GSAP_CDN_BASE_URL;
9+
if (!/^https?:\/\//i.test(value) || !URL.canParse(value) || /[?#]/.test(value)) {
10+
throw new Error("GSAP base URL must be an absolute HTTP(S) URL without a query or fragment");
11+
}
12+
const url = new URL(value);
13+
if (url.username || url.password) {
14+
throw new Error("GSAP base URL must not contain credentials");
15+
}
16+
return url.href.replace(/\/+$/, "");
17+
}
18+
19+
export function gsapCdnDist(gsapVersion?: string, baseUrl?: string): string {
420
const version = gsapVersion && /^\d+(\.\d+)*$/.test(gsapVersion) ? gsapVersion : GSAP_CDN_VERSION;
5-
return `https://cdn.jsdelivr.net/npm/gsap@${version}/dist/`;
21+
return `${normalizeGsapBaseUrl(baseUrl)}/gsap@${version}/dist/`;
622
}
723

824
/** MotionPathPlugin at the composition's own gsap version; a skew registers with a GSAP warning. */
9-
export function motionPathPluginUrl(gsapVersion?: string): string {
10-
return `${gsapCdnDist(gsapVersion)}MotionPathPlugin.min.js`;
25+
export function motionPathPluginUrl(gsapVersion?: string, baseUrl?: string): string {
26+
return `${gsapCdnDist(gsapVersion, baseUrl)}MotionPathPlugin.min.js`;
1127
}

‎packages/studio-server/src/helpers/subComposition.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ export function buildSubCompositionHtml(
269269
runtimeUrl: string,
270270
baseHref?: string,
271271
rawOverride?: string,
272+
gsapBaseUrl?: string,
272273
): string | null {
273274
const compFile = join(projectDir, compPath);
274275
if (!existsSync(compFile)) return null;
@@ -353,7 +354,7 @@ export function buildSubCompositionHtml(
353354

354355
// Fallback: if no index.html head was found, add minimal deps
355356
if (!headContent.includes("gsap")) {
356-
headContent += `\n<script src="${gsapCdnDist()}gsap.min.js"></script>`;
357+
headContent += `\n<script src="${gsapCdnDist(undefined, gsapBaseUrl).replace(/&/g, "&amp;")}gsap.min.js"></script>`;
357358
}
358359

359360
const htmlOpen = htmlAttrs ? `<html ${htmlAttrs}>` : "<html>";

‎packages/studio-server/src/routes/preview.test.ts‎

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const tempDirs: string[] = [];
4242

4343
afterEach(() => {
4444
vi.useRealTimers();
45+
vi.unstubAllEnvs();
4546
for (const dir of tempDirs.splice(0)) {
4647
rmSync(dir, { recursive: true, force: true });
4748
}
@@ -2431,3 +2432,203 @@ describe("the desktop app's private folder", () => {
24312432
expect(res.status).toBe(200);
24322433
});
24332434
});
2435+
2436+
describe("GSAP mirror configuration", () => {
2437+
const mirror = "http://localhost:8080/vendor/npm";
2438+
const metaName = "hyperframes-gsap-base-url";
2439+
const previewUrl = "http://localhost/projects/demo/preview";
2440+
2441+
function appForMirror(
2442+
projectDir: string,
2443+
base: string,
2444+
overrides: Partial<StudioApiAdapter> = {},
2445+
) {
2446+
vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", base);
2447+
const app = new Hono();
2448+
registerPreviewRoutes(app, createAdapter(projectDir, overrides));
2449+
return app;
2450+
}
2451+
2452+
it.each(["/relative/npm", "https://mirror.example/npm?token=1", "file:///npm"])(
2453+
"rejects invalid configuration before registering routes: %s",
2454+
(base) => {
2455+
expect(() => appForMirror(createProjectDir(), base)).toThrow("HYPERFRAMES_GSAP_BASE_URL");
2456+
},
2457+
);
2458+
2459+
it.each(["bundle", "disk fallback", "capture", "subcomposition"])(
2460+
"uses server metadata and the configured plugin in the %s document",
2461+
async (mode) => {
2462+
const projectDir = createProjectDir();
2463+
const authored = "https://authored.example/[email protected]/dist/gsap.min.js";
2464+
const source = `<html><head><meta name="${metaName}" content="https://authored.example/npm"><script src="${authored}"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
2465+
writeFileSync(join(projectDir, "index.html"), source);
2466+
writeFileSync(join(projectDir, "scene.html"), source);
2467+
const app = appForMirror(projectDir, mirror, {
2468+
bundle: async () => {
2469+
if (mode === "disk fallback") throw new Error("test bundle failure");
2470+
return source;
2471+
},
2472+
});
2473+
const suffix =
2474+
mode === "subcomposition" ? "/comp/scene.html" : mode === "capture" ? "?hf-capture=1" : "";
2475+
const response = await app.request(previewUrl + suffix);
2476+
expect(response.status).toBe(200);
2477+
const html = await response.text();
2478+
const doc = parseHTML(html).document;
2479+
expect(doc.querySelector(`meta[name="${metaName}"]`)?.getAttribute("content")).toBe(mirror);
2480+
expect(doc.querySelector(`script[src="${authored}"]`)).not.toBeNull();
2481+
expect(doc.querySelector('script[src*="MotionPathPlugin"]')?.getAttribute("src")).toBe(
2482+
`${mirror}/[email protected]/dist/MotionPathPlugin.min.js`,
2483+
);
2484+
expect(html).not.toContain("cdn.jsdelivr.net");
2485+
},
2486+
);
2487+
2488+
it("uses the mirror for generated GSAP, CustomEase, and standalone GSAP", async () => {
2489+
const projectDir = createProjectDir();
2490+
mkdirSync(join(projectDir, ".hyperframes"));
2491+
writeFileSync(
2492+
join(projectDir, ".hyperframes", "studio-motion.json"),
2493+
JSON.stringify({
2494+
version: 1,
2495+
motions: [
2496+
{
2497+
kind: "gsap-motion",
2498+
target: { sourceFile: "index.html", id: "card" },
2499+
start: 0,
2500+
duration: 1,
2501+
customEase: { id: "custom", data: "M0,0 C0.18,0.9 0.32,1 1,1" },
2502+
from: { y: 32 },
2503+
to: { y: 0 },
2504+
},
2505+
],
2506+
}),
2507+
);
2508+
writeFileSync(join(projectDir, "scene.html"), "<template><section>Scene</section></template>");
2509+
const app = appForMirror(projectDir, mirror);
2510+
const root = parseHTML(await (await app.request(previewUrl)).text()).document;
2511+
const urls = [...root.querySelectorAll("script[src]")].map((script) =>
2512+
script.getAttribute("src"),
2513+
);
2514+
expect(urls).toContain(`${mirror}/[email protected]/dist/gsap.min.js`);
2515+
expect(urls).toContain(`${mirror}/[email protected]/dist/CustomEase.min.js`);
2516+
const scene = parseHTML(
2517+
await (await app.request(previewUrl + "/comp/scene.html")).text(),
2518+
).document;
2519+
expect(scene.querySelector('script[src$="/gsap.min.js"]')?.getAttribute("src")).toBe(
2520+
`${mirror}/[email protected]/dist/gsap.min.js`,
2521+
);
2522+
});
2523+
2524+
it("preserves authored plugins and the default CDN when the override is unset", async () => {
2525+
const projectDir = createProjectDir();
2526+
const plugin = "https://authored.example/MotionPathPlugin.min.js";
2527+
writeFileSync(
2528+
join(projectDir, "index.html"),
2529+
`<html><head><script src="${plugin}"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
2530+
);
2531+
const configured = await (await appForMirror(projectDir, mirror).request(previewUrl)).text();
2532+
expect(
2533+
parseHTML(configured).document.querySelectorAll('script[src*="MotionPathPlugin"]'),
2534+
).toHaveLength(1);
2535+
expect(configured).toContain(`src="${plugin}"`);
2536+
const defaults = await (await appForMirror(projectDir, "").request(previewUrl)).text();
2537+
expect(
2538+
parseHTML(defaults)
2539+
.document.querySelector(`meta[name="${metaName}"]`)
2540+
?.getAttribute("content"),
2541+
).toBe("https://cdn.jsdelivr.net/npm");
2542+
expect(defaults).toContain('var cdnBase="https://cdn.jsdelivr.net/npm/[email protected]/dist/"');
2543+
});
2544+
2545+
it("normalizes and escapes metadata without letting authored metadata override it", async () => {
2546+
const projectDir = createProjectDir();
2547+
writeFileSync(
2548+
join(projectDir, "index.html"),
2549+
`<html><head><meta name="${metaName}" content="https://authored.example/npm"></head><body></body></html>`,
2550+
);
2551+
const app = appForMirror(projectDir, " https://mirror.example/a&copy;/npm/// ");
2552+
const html = await (await app.request(previewUrl)).text();
2553+
expect(html).toContain('content="https://mirror.example/a&amp;copy;/npm"');
2554+
expect(
2555+
parseHTML(html).document.querySelector(`meta[name="${metaName}"]`)?.getAttribute("content"),
2556+
).toBe("https://mirror.example/a&copy;/npm");
2557+
});
2558+
2559+
it("invalidates root, subcomposition, and persistent preview caches when the mirror changes", async () => {
2560+
const projectDir = createProjectDir();
2561+
writeFileSync(join(projectDir, "scene.html"), "<template><section>Scene</section></template>");
2562+
const bundle = vi.fn(
2563+
async () =>
2564+
'<html><head></head><body><div data-hf-scene="a">Cached preview</div></body></html>',
2565+
);
2566+
const overrides = {
2567+
bundle,
2568+
previewDocuments: createPreviewDocumentStore(projectDir, "same-build"),
2569+
};
2570+
const first = appForMirror(projectDir, mirror, overrides);
2571+
const root = await first.request(previewUrl);
2572+
const scene = await first.request(previewUrl + "/comp/scene.html");
2573+
const secondBase = "https://other.example/npm";
2574+
const second = appForMirror(projectDir, secondBase, overrides);
2575+
const rootNext = await second.request(previewUrl, {
2576+
headers: { "If-None-Match": root.headers.get("ETag")! },
2577+
});
2578+
const sceneNext = await second.request(previewUrl + "/comp/scene.html", {
2579+
headers: { "If-None-Match": scene.headers.get("ETag")! },
2580+
});
2581+
expect(rootNext.status).toBe(200);
2582+
expect(sceneNext.status).toBe(200);
2583+
expect(rootNext.headers.get("ETag")).not.toBe(root.headers.get("ETag"));
2584+
expect(sceneNext.headers.get("ETag")).not.toBe(scene.headers.get("ETag"));
2585+
expect(bundle).toHaveBeenCalledTimes(2);
2586+
const firstHtml = parseHTML(await root.text()).document;
2587+
const nextHtml = parseHTML(await rootNext.text()).document;
2588+
expect(nextHtml.querySelector(`meta[name="${metaName}"]`)?.getAttribute("content")).toBe(
2589+
secondBase,
2590+
);
2591+
expect(nextHtml.querySelector('meta[name="hf-scene-parts"]')?.getAttribute("content")).not.toBe(
2592+
firstHtml.querySelector('meta[name="hf-scene-parts"]')?.getAttribute("content"),
2593+
);
2594+
const normalized = appForMirror(projectDir, ` ${secondBase}/// `, overrides);
2595+
expect(
2596+
(
2597+
await normalized.request(previewUrl, {
2598+
headers: { "If-None-Match": rootNext.headers.get("ETag")! },
2599+
})
2600+
).status,
2601+
).toBe(304);
2602+
vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", mirror);
2603+
expect((await second.request(previewUrl)).headers.get("ETag")).toBe(
2604+
rootNext.headers.get("ETag"),
2605+
);
2606+
});
2607+
2608+
it("retries an authored GSAP failure only on the selected mirror and reports mirror failure", async () => {
2609+
const app = appForMirror(createProjectDir(), mirror);
2610+
const html = await (await app.request(previewUrl)).text();
2611+
const fallback = /<script data-hf-gsap-fallback>([\s\S]*?)<\/script>/.exec(html)?.[1] ?? "";
2612+
let onError: (event: { target: unknown }) => void = () => undefined;
2613+
const scripts: { tagName: string; src: string; onerror?: (event: Event) => void }[] = [];
2614+
const doc = {
2615+
addEventListener: (_type: string, listener: typeof onError) => {
2616+
onError = listener;
2617+
},
2618+
createElement: () => ({ tagName: "SCRIPT", src: "" }),
2619+
head: { appendChild: (script: (typeof scripts)[number]) => scripts.push(script) },
2620+
};
2621+
const reported = vi.fn();
2622+
new Function("document", "reportError", fallback)(doc, reported);
2623+
onError({
2624+
target: { tagName: "SCRIPT", src: "https://authored.example/[email protected]/dist/gsap.min.js" },
2625+
});
2626+
expect(scripts).toHaveLength(1);
2627+
expect(scripts[0]?.src).toBe(`${mirror}/[email protected]/dist/gsap.min.js`);
2628+
onError({ target: scripts[0] });
2629+
scripts[0]?.onerror?.(new Event("error"));
2630+
await vi.waitFor(() => expect(reported).toHaveBeenCalledTimes(1));
2631+
expect(scripts).toHaveLength(1);
2632+
expect(html).not.toContain("cdn.jsdelivr.net");
2633+
});
2634+
});

0 commit comments

Comments
 (0)