-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathstudioServer.ts
More file actions
447 lines (405 loc) · 15.5 KB
/
Copy pathstudioServer.ts
File metadata and controls
447 lines (405 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/**
* Embedded studio server for `hyperframes preview` outside the monorepo.
*
* Uses the shared studio API module from @hyperframes/core/studio-api,
* providing a CLI-specific adapter for single-project, in-process rendering.
*/
import { Hono, type Context } from "hono";
import { streamSSE } from "hono/streaming";
import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
import { resolve, join, basename } from "node:path";
import { createProjectWatcher, type ProjectWatcher } from "./fileWatcher.js";
import { loadRuntimeSource } from "./runtimeSource.js";
import { VERSION as version } from "../version.js";
import {
createStudioApi,
createProjectSignature,
getMimeType,
type StudioApiAdapter,
type ResolvedProject,
type RenderJobState,
} from "@hyperframes/core/studio-api";
import { getElementScreenshotClip } from "@hyperframes/core/studio-api/screenshot-clip";
import type { ScreenshotClip } from "@hyperframes/core/studio-api/screenshot-clip";
// ── Path resolution ─────────────────────────────────────────────────────────
function resolveDistDir(): string {
return resolveStudioBundle().dir;
}
export interface StudioBundleResolution {
dir: string;
indexPath: string;
available: boolean;
checkedPaths: string[];
}
export function resolveStudioBundle(): StudioBundleResolution {
const builtPath = resolve(__dirname, "studio");
const builtIndex = resolve(builtPath, "index.html");
if (existsSync(builtIndex)) {
return { dir: builtPath, indexPath: builtIndex, available: true, checkedPaths: [builtIndex] };
}
const devPath = resolve(__dirname, "..", "..", "..", "studio", "dist");
const devIndex = resolve(devPath, "index.html");
if (existsSync(devIndex)) {
return {
dir: devPath,
indexPath: devIndex,
available: true,
checkedPaths: [builtIndex, devIndex],
};
}
return {
dir: builtPath,
indexPath: builtIndex,
available: false,
checkedPaths: [builtIndex, devIndex],
};
}
function resolveRuntimePath(): string {
const builtPath = resolve(__dirname, "hyperframe-runtime.js");
if (existsSync(builtPath)) return builtPath;
const iifePath = resolve(__dirname, "hyperframe.runtime.iife.js");
if (existsSync(iifePath)) return iifePath;
const devPath = resolve(
__dirname,
"..",
"..",
"..",
"core",
"dist",
"hyperframe.runtime.iife.js",
);
if (existsSync(devPath)) return devPath;
return builtPath;
}
// ── Shared thumbnail browser (singleton per process) ────────────────────────
// One browser instance is reused across all composition thumbnail requests.
// Spawning a new Puppeteer process per request adds 2-5s overhead and causes
// contention when the sidebar requests multiple thumbnails simultaneously.
let _thumbnailBrowser: import("puppeteer-core").Browser | null = null;
let _thumbnailBrowserInitializing: Promise<import("puppeteer-core").Browser | null> | null = null;
async function getThumbnailBrowser(): Promise<import("puppeteer-core").Browser | null> {
if (_thumbnailBrowser?.connected) return _thumbnailBrowser;
if (_thumbnailBrowserInitializing) return _thumbnailBrowserInitializing;
_thumbnailBrowserInitializing = (async () => {
try {
const { ensureBrowser } = await import("../browser/manager.js");
const { acquireBrowser, buildChromeArgs } = await import("@hyperframes/engine");
try {
const b = await ensureBrowser();
if (b.executablePath && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {
process.env.PRODUCER_HEADLESS_SHELL_PATH = b.executablePath;
}
} catch {
/* continue — acquireBrowser will try its own resolution */
}
const acquired = await acquireBrowser(buildChromeArgs({ width: 1920, height: 1080 }), {
enableBrowserPool: false,
});
_thumbnailBrowser = acquired.browser;
_thumbnailBrowser.on("disconnected", () => {
_thumbnailBrowser = null;
_thumbnailBrowserInitializing = null;
});
return _thumbnailBrowser;
} catch {
_thumbnailBrowserInitializing = null;
return null;
}
})();
return _thumbnailBrowserInitializing;
}
// ── Server factory ──────────────────────────────────────────────────────────
export interface StudioServerOptions {
projectDir: string;
/** Display name for the project. Defaults to basename of projectDir. */
projectName?: string;
}
export interface StudioServer {
app: Hono;
watcher: ProjectWatcher;
}
export function createStudioServer(options: StudioServerOptions): StudioServer {
const { projectDir, projectName } = options;
const projectId = projectName || basename(projectDir);
const studioDir = resolveDistDir();
const runtimePath = resolveRuntimePath();
const watcher = createProjectWatcher(projectDir);
// ── CLI adapter for the shared studio API ──────────────────────────────
const project: ResolvedProject = { id: projectId, dir: projectDir, title: projectId };
let cachedProjectSignature: string | null = null;
watcher.addListener(() => {
cachedProjectSignature = null;
});
const adapter: StudioApiAdapter = {
listProjects: () => [project],
resolveProject: (id: string) => (id === projectId ? project : null),
async bundle(dir: string): Promise<string | null> {
try {
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
// Studio dev server: ask the bundler for an empty `src=""` placeholder so
// we can point it at our hot-reloadable local runtime endpoint. Inlining
// ~150 KB of runtime body on every preview render would defeat browser
// caching across composition edits.
let html = await bundleToSingleHtml(dir, { runtime: "placeholder" });
html = html.replace(
'data-hyperframes-preview-runtime="1" src=""',
'data-hyperframes-preview-runtime="1" src="/api/runtime.js"',
);
return html;
} catch (err) {
console.error("[studio] Bundle failed:", err);
return null;
}
},
async transformPreviewHtml({ html }) {
const { injectDeterministicFontFaces } =
await import("../../../producer/src/services/deterministicFonts.js");
return injectDeterministicFontFaces(html);
},
getProjectSignature(dir: string): string {
if (resolve(dir) !== resolve(projectDir)) return createProjectSignature(dir);
cachedProjectSignature ??= createProjectSignature(projectDir);
return cachedProjectSignature;
},
async lint(html: string, opts?: { filePath?: string }) {
const { lintHyperframeHtml } = await import("@hyperframes/core/lint");
return lintHyperframeHtml(html, opts);
},
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(projectDir, "renders"),
startRender(opts): RenderJobState {
const state: RenderJobState = {
id: opts.jobId,
status: "rendering",
progress: 0,
outputPath: opts.outputPath,
};
// Run render asynchronously, mutating the state object
(async () => {
try {
const { createRenderJob, executeRenderJob } = await import("@hyperframes/producer");
const { ensureBrowser } = await import("../browser/manager.js");
try {
const browser = await ensureBrowser();
if (browser.executablePath && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {
process.env.PRODUCER_HEADLESS_SHELL_PATH = browser.executablePath;
}
} catch {
// Continue without — acquireBrowser will try its own resolution
}
const job = createRenderJob({
// opts.fps is already an Fps rational — see vite-config-studio
// adapter for the same convention.
fps: opts.fps,
quality: opts.quality as "draft" | "standard" | "high",
format: opts.format,
outputResolution: opts.outputResolution,
});
const startTime = Date.now();
const onProgress = (j: { progress: number; currentStage?: string }) => {
state.progress = j.progress;
if (j.currentStage) state.stage = j.currentStage;
};
await executeRenderJob(job, opts.project.dir, opts.outputPath, onProgress);
state.status = "complete";
state.progress = 100;
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
writeFileSync(
metaPath,
JSON.stringify({ status: "complete", durationMs: Date.now() - startTime }),
);
} catch (err) {
state.status = "failed";
state.error = err instanceof Error ? err.message : String(err);
try {
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
writeFileSync(metaPath, JSON.stringify({ status: "failed" }));
} catch {
/* ignore */
}
}
})();
return state;
},
async generateThumbnail(opts): Promise<Buffer | null> {
// Reuse a single browser across all thumbnail requests for this server
// instance — avoids paying the ~2s Puppeteer startup cost per composition.
// The browser is created lazily and kept alive until the process exits.
const browser = await getThumbnailBrowser();
if (!browser) return null;
let page: import("puppeteer-core").Page | null = null;
try {
page = await browser.newPage();
await page.setViewport({ width: opts.width || 1920, height: opts.height || 1080 });
// domcontentloaded instead of networkidle2 — CDN scripts (GSAP, Lottie,
// fonts) never reach "idle" and cause a 15s timeout per thumbnail.
await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 });
// Wait for the runtime to register timelines (up to 5s, non-fatal).
await page
.waitForFunction(() => !!(window as any).__timelines || !!(window as any).__playerReady, {
timeout: 5000,
})
.catch(() => {});
await page.evaluate((t: number) => {
const win = window as any;
if (win.__player?.seek) win.__player.seek(t);
else if (win.__timeline?.seek) {
win.__timeline.pause();
win.__timeline.seek(t);
}
}, opts.seekTime);
// Let the seek render settle.
await new Promise((r) => setTimeout(r, 200));
let clip: ScreenshotClip | undefined;
if (opts.selector) {
clip = await page.evaluate(getElementScreenshotClip, opts.selector, opts.selectorIndex);
}
const screenshot = (await page.screenshot(
opts.format === "png"
? {
type: "png",
...(clip ? { clip } : {}),
}
: {
type: "jpeg",
quality: 80,
...(clip ? { clip } : {}),
},
)) as Buffer;
return screenshot;
} catch {
return null;
} finally {
await page?.close().catch(() => {});
}
},
};
// ── Build the Hono app ─────────────────────────────────────────────────
const app = new Hono();
// Config probe endpoint — used by port detection to identify existing
// HyperFrames instances and reuse them instead of spawning duplicates.
// See portUtils.ts detectHyperframesServer() for the consumer.
app.get("/__hyperframes_config", (c) => {
return c.json({
isHyperframes: true,
projectName: projectId,
projectDir: projectDir,
version,
});
});
// CLI-specific routes (before shared API)
app.get("/api/runtime.js", (c) => {
const serve = async () => {
const runtimeSource =
(await loadRuntimeSource()) ??
(existsSync(runtimePath) ? readFileSync(runtimePath, "utf-8") : null);
if (!runtimeSource) return c.text("runtime not available", 404);
return c.body(runtimeSource, 200, {
"Content-Type": "text/javascript",
"Cache-Control": "no-store",
});
};
return serve();
});
app.get("/api/events", (c) => {
return streamSSE(c, async (stream) => {
const listener = (path: string) => {
stream.writeSSE({ event: "file-change", data: JSON.stringify({ path }) }).catch(() => {});
};
watcher.addListener(listener);
while (true) {
await stream.sleep(30000);
}
});
});
// Mount the shared studio API at /api.
// Use fetch() forwarding (not .route()) so the sub-app sees paths without
// the /api prefix — the shared module's path extraction uses c.req.path.
const api = createStudioApi(adapter);
app.all("/api/*", async (c) => {
const url = new URL(c.req.url);
url.pathname = url.pathname.slice(4); // Strip "/api" prefix
const forwardReq = new Request(url.toString(), {
method: c.req.method,
headers: c.req.raw.headers,
body: c.req.raw.body,
// @ts-expect-error -- Node needs duplex for streaming bodies
duplex: "half",
});
return api.fetch(forwardReq);
});
// Studio SPA static files
const serveStudioStaticFile = (c: Context) => {
const filePath = resolve(studioDir, c.req.path.slice(1));
if (!existsSync(filePath) || !statSync(filePath).isFile()) return c.text("not found", 404);
const content = readFileSync(filePath);
return new Response(content, {
headers: { "Content-Type": getMimeType(filePath), "Cache-Control": "no-store" },
});
};
app.get("/assets/*", serveStudioStaticFile);
app.get("/icons/*", serveStudioStaticFile);
app.get("/favicon.svg", serveStudioStaticFile);
// SPA fallback
app.get("*", (c) => {
const indexPath = resolve(studioDir, "index.html");
if (!existsSync(indexPath)) {
return c.html(
`<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>HyperFrames Studio unavailable</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
background: #0d0f14;
color: #eef2f7;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
main {
width: min(560px, calc(100vw - 48px));
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 8px;
padding: 28px;
background: #151923;
}
h1 {
margin: 0 0 12px;
font-size: 22px;
line-height: 1.2;
}
p {
margin: 0 0 18px;
color: #aab3c2;
line-height: 1.5;
}
code {
display: block;
padding: 12px 14px;
border-radius: 6px;
background: #090b10;
color: #8ff0c2;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<h1>Studio bundle missing</h1>
<p>The preview server started, but this CLI build does not contain the Studio assets.</p>
<code>bun run build</code>
</main>
</body>
</html>`,
500,
);
}
return c.html(readFileSync(indexPath, "utf-8"));
});
return { app, watcher };
}