Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

server.mjs

374 lines13.9 KB

1// HTTP server: serves the player, the latest .riv build and its metadata,
2// and pushes rebuild / seek notifications over Server-Sent Events.
3import http from 'node:http';
4import { createReadStream, watch, existsSync, readFileSync } from 'node:fs';
5import { readFile, stat } from 'node:fs/promises';
6import { createRequire } from 'node:module';
7import path from 'node:path';
8import { fileURLToPath } from 'node:url';
9import { buildProject, inspectProject } from './build.mjs';
10import { FeedbackStore } from './feedback.mjs';
11import { listListeners } from './listeners.mjs';
12import { MixStore } from './mix.mjs';
13import { rivMeta } from './riv-audio.mjs';
14​
15const HERE = path.dirname(fileURLToPath(import.meta.url));
16const PLAYER_DIR = path.join(HERE, '..', 'player');
17​
18function riveRuntimeDir() {
19 const require = createRequire(import.meta.url);
20 try {
21 return path.dirname(require.resolve('@rive-app/webgl2-advanced'));
22 } catch {
23 return path.join(HERE, '..', 'node_modules', '@rive-app', 'webgl2-advanced');
24 }
26​
27const MIME = {
28 '.html': 'text/html; charset=utf-8',
29 '.js': 'text/javascript; charset=utf-8',
30 '.mjs': 'text/javascript; charset=utf-8',
31 '.css': 'text/css; charset=utf-8',
32 '.wasm': 'application/wasm',
33 '.json': 'application/json; charset=utf-8',
34 '.svg': 'image/svg+xml',
35 '.png': 'image/png',
36};
37​
38const MAX_BODY = 64 * 1024 * 1024;
39​
40function readBody(req) {
41 return new Promise((resolve, reject) => {
42 const chunks = [];
43 let size = 0;
44 req.on('data', (d) => {
45 size += d.length;
46 if (size > MAX_BODY) {
47 reject(new Error('request too large'));
48 req.destroy();
49 } else chunks.push(d);
50 });
51 req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
52 req.on('error', reject);
53 });
55​
56async function readJson(req) {
57 const body = await readBody(req);
58 return body ? JSON.parse(body) : {};
60​
61function sendJson(res, data, status = 200) {
62 res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
63 res.end(JSON.stringify(data));
65​
66const IGNORED_DIRS = new Set(['build', 'node_modules', '.git']);
67const IGNORED_EXT = new Set(['.log', '.riv', '.rev', '.png.tmp', '.swp']);
68​
69function isIgnored(rel) {
70 if (!rel) return true;
71 const parts = rel.split(path.sep);
72 if (parts.some((p) => IGNORED_DIRS.has(p) || (p.startsWith('.') && p.length > 1))) return true;
73 const base = parts[parts.length - 1];
74 if (base.endsWith('~') || base.startsWith('#')) return true;
75 return IGNORED_EXT.has(path.extname(base).toLowerCase());
77​
78function projectName(dir) {
79 try {
80 const m = readFileSync(path.join(dir, 'rive.yaml'), 'utf8').match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
81 if (m) return m[1];
82 } catch {}
83 return path.basename(dir);
85​
86export class PreviewServer {
87 constructor({ target, mode, watch = true, log = console.log, feedbackDays = null }) {
88 this.target = target; // project dir, or a .riv file
89 this.mode = mode; // 'project' | 'riv'
90 this.watchEnabled = watch;
91 this.log = log;
92 this.clients = new Set();
93 this.version = 0;
94 this.riv = null;
95 this.meta = null;
96 this.lastError = null;
97 this.building = false;
98 this.pending = false;
99 this.runtimeDir = riveRuntimeDir();
100 this.name = mode === 'project' ? projectName(target) : path.basename(target, '.riv');
101 this.feedback = new FeedbackStore(target, { project: this.name });
102 this.mix = new MixStore(target);
103 this.feedbackDays = feedbackDays; // prune bundles read this many days ago; null = keep all
104 }
105​
106 /** Remove old read feedback bundles. Never throws: a failure is logged and ignored. */
107 async pruneFeedback() {
108 const days = this.feedbackDays;
109 if (days == null) return;
110 try {
111 const removed = await this.feedback.prune({ olderThanDays: days });
112 if (removed.length) this.log(`removed ${removed.length} feedback bundle${removed.length === 1 ? '' : 's'} read over ${days} day${days === 1 ? '' : 's'} ago`);
113 } catch (err) {
114 this.log(`could not prune old feedback bundles: ${err?.message || err}`);
115 }
116 }
117​
118 async handleFeedback(req, res, p) {
119 const fb = this.feedback;
120 const withUrl = (s) => ({ ...s, url: `/shots/${s.id}.png` });
121 let m;
122 if (p === '/api/shots' && req.method === 'GET') return sendJson(res, { shots: (await fb.listDrafts()).map(withUrl) });
123 if (p === '/api/shots' && req.method === 'POST') {
124 const { image, ...meta } = await readJson(req);
125 const b64 = String(image || '').replace(/^data:image\/png;base64,/, '');
126 if (!b64) return sendJson(res, { error: 'missing image' }, 400);
127 const shot = await fb.addDraft({ png: Buffer.from(b64, 'base64'), ...meta });
128 this.log(`screenshot ${shot.timecode}${shot.artboard ? ` · ${shot.artboard}` : ''}`);
129 this.broadcast({ type: 'shots' });
130 return sendJson(res, withUrl(shot));
131 }
132 if ((m = p.match(/^\/api\/shots\/([a-z0-9-]+)$/))) {
133 if (req.method === 'PATCH') {
134 const shot = await fb.updateDraft(m[1], await readJson(req));
135 if (!shot) return sendJson(res, { error: 'not found' }, 404);
136 this.broadcast({ type: 'shots', from: req.headers['x-client'] });
137 return sendJson(res, withUrl(shot));
138 }
139 if (req.method === 'DELETE') {
140 await fb.deleteDraft(m[1]);
141 this.broadcast({ type: 'shots' });
142 return sendJson(res, { ok: true });
143 }
144 }
145 if ((m = p.match(/^\/shots\/([a-z0-9-]+)\.png$/))) return this.serveFile(res, fb.draftPng(m[1]));
146 if (p === '/api/share' && req.method === 'POST') {
147 const { message } = await readJson(req);
148 let bundle;
149 try {
150 bundle = await fb.share({ message: message || '' });
151 } catch (err) {
152 return sendJson(res, { error: err.message }, 400);
153 }
154 this.log(`sent ${bundle.shots.length} screenshot(s) to the agent: ${bundle.markdown}`);
155 this.pruneFeedback();
156 this.broadcast({ type: 'shots' });
157 return sendJson(res, { ...bundle, ...this.listening() });
158 }
159 if (p === '/api/feedback' && req.method === 'GET') {
160 const bundles = await fb.listBundles();
161 return sendJson(res, { root: fb.root, ...this.listening(), bundles: bundles.slice(-10).map(({ id, createdAt, markdown, consumed, shots }) => ({ id, createdAt, markdown, consumed, count: shots.length })) });
162 }
163 return false;
164 }
165​
166 /** Whether an agent is waiting for feedback right now (`wait-feedback` or MCP wait_for_feedback). */
167 listening() {
168 const listeners = listListeners(this.target);
169 return { listening: listeners.length > 0, listeners: listeners.map(({ kind, startedAt }) => ({ kind, startedAt })) };
170 }
171​
172 async rebuild(reason) {
173 if (this.building) {
174 this.pending = true;
175 return;
176 }
177 this.building = true;
178 this.broadcast({ type: 'building', reason });
179 try {
180 if (this.mode === 'riv') {
181 this.riv = await readFile(this.target);
182 try {
183 this.meta = rivMeta(this.riv);
184 } catch (err) {
185 this.meta = null; // the player falls back to measuring the animation, without audio timing
186 this.log(`could not read the timeline from ${path.basename(this.target)}: ${err.message}`);
187 }
188 this.lastError = null;
189 this.version++;
190 this.log(`loaded ${path.basename(this.target)} (${(this.riv.length / 1024).toFixed(0)} KB)`);
191 } else {
192 const res = await buildProject(this.target);
193 if (!res.ok) {
194 this.lastError = res.error;
195 this.log(`build failed:\n${res.error}`);
196 } else {
197 const meta = await inspectProject(this.target);
198 this.riv = res.riv;
199 this.meta = meta;
200 this.lastError = null;
201 this.version++;
202 this.log(`built ${path.basename(res.rivPath)} in ${res.buildMs}ms${reason ? ` (${reason})` : ''}`);
203 if (res.warnings) this.log(`warnings:\n${res.warnings}`);
204 }
205 }
206 } catch (err) {
207 this.lastError = String(err?.stack || err);
208 this.log(`build failed: ${this.lastError}`);
209 } finally {
210 this.building = false;
211 }
212 this.broadcast(this.statusMessage());
213 if (this.pending) {
214 this.pending = false;
215 await this.rebuild('changed during build');
216 }
217 }
218​
219 statusMessage() {
220 return { type: 'build', version: this.version, error: this.lastError, name: this.name };
221 }
222​
223 broadcast(msg) {
224 const data = `data: ${JSON.stringify(msg)}\n\n`;
225 for (const res of this.clients) res.write(data);
226 }
227​
228 startWatching() {
229 if (!this.watchEnabled) return;
230 let timer = null;
231 let changed = new Set();
232 const trigger = (rel) => {
233 changed.add(rel);
234 clearTimeout(timer);
235 timer = setTimeout(() => {
236 const files = [...changed];
237 changed = new Set();
238 this.rebuild(files.slice(0, 3).join(', ') + (files.length > 3 ? ` +${files.length - 3}` : ''));
239 }, 150);
240 };
241 if (this.mode === 'riv') {
242 watch(path.dirname(this.target), (_ev, file) => {
243 if (file && path.basename(file) === path.basename(this.target)) trigger(file);
244 });
245 } else {
246 watch(this.target, { recursive: true }, (_ev, file) => {
247 if (file && !isIgnored(file)) trigger(file);
248 });
249 }
250 }
251​
252 async serveFile(res, file) {
253 try {
254 const st = await stat(file);
255 res.writeHead(200, {
256 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream',
257 'Content-Length': st.size,
258 'Cache-Control': 'no-cache',
259 });
260 createReadStream(file).pipe(res);
261 } catch {
262 res.writeHead(404).end('not found');
263 }
264 }
265​
266 async handle(req, res) {
267 const url = new URL(req.url, 'http://localhost');
268 const p = url.pathname;
269​
270 // Only this machine's own pages and tools may talk to the player. A site open in the
271 // browser can send requests to 127.0.0.1 (and a rebound DNS name can reach it), so
272 // reject other Host names and any cross-origin request.
273 const host = String(req.headers.host || '');
274 if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host)) return res.writeHead(403).end('forbidden host');
275 const origin = req.headers.origin;
276 if (origin && origin !== `http://${host}`) return res.writeHead(403).end('forbidden origin');
277​
278 if (p === '/favicon.ico') return this.serveFile(res, path.join(PLAYER_DIR, 'icon-32.png'));
279 if (p === '/' || p === '/index.html') return this.serveFile(res, path.join(PLAYER_DIR, 'index.html'));
280 if (p === '/app.js' || p === '/style.css' || p === '/icon-32.png' || p === '/icon-192.png') return this.serveFile(res, path.join(PLAYER_DIR, p.slice(1)));
281 if (p.startsWith('/vendor/rive/')) {
282 const name = path.basename(p);
283 if (!/^[\w.-]+\.(mjs|wasm)$/.test(name)) return res.writeHead(404).end();
284 return this.serveFile(res, path.join(this.runtimeDir, name));
285 }
286 if (p === '/project.riv') {
287 if (!this.riv) return res.writeHead(404).end('no build yet');
288 res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'no-store' });
289 return res.end(this.riv);
290 }
291 if (p === '/meta.json') {
292 res.writeHead(200, { 'Content-Type': MIME['.json'], 'Cache-Control': 'no-store' });
293 return res.end(JSON.stringify({ name: this.name, mode: this.mode, version: this.version, error: this.lastError, meta: this.meta }));
294 }
295 if (p === '/events') {
296 res.writeHead(200, {
297 'Content-Type': 'text/event-stream',
298 'Cache-Control': 'no-store',
299 Connection: 'keep-alive',
300 });
301 res.write(`data: ${JSON.stringify(this.statusMessage())}\n\n`);
302 this.clients.add(res);
303 const ping = setInterval(() => res.write(': ping\n\n'), 15000);
304 req.on('close', () => {
305 clearInterval(ping);
306 this.clients.delete(res);
307 });
308 return;
309 }
310 if (p === '/api/mix') {
311 if (req.method === 'GET') return sendJson(res, await this.mix.read());
312 if (req.method === 'PUT') {
313 let body;
314 try {
315 body = await readJson(req);
316 } catch {
317 return sendJson(res, { error: 'bad json' }, 400);
318 }
319 const mix = await this.mix.write(body);
320 this.broadcast({ type: 'mix', from: req.headers['x-client'] });
321 return sendJson(res, mix);
322 }
323 }
324 if (p.startsWith('/api/shots') || p.startsWith('/shots/') || p === '/api/share' || p === '/api/feedback') {
325 if ((await this.handleFeedback(req, res, p)) !== false) return;
326 }
327 if (p === '/api/ping') {
328 res.writeHead(200, { 'Content-Type': MIME['.json'] });
329 return res.end(JSON.stringify({ app: 'rive-video-preview', target: this.target, clients: this.clients.size, version: this.version, pid: process.pid }));
330 }
331 if (p === '/api/seek' && req.method === 'POST') {
332 let body = '';
333 req.on('data', (d) => (body += d));
334 req.on('end', () => {
335 let msg = {};
336 try {
337 msg = JSON.parse(body || '{}');
338 } catch {}
339 this.broadcast({ type: 'seek', at: msg.at });
340 res.writeHead(200, { 'Content-Type': MIME['.json'] }).end(JSON.stringify({ clients: this.clients.size }));
341 });
342 return;
343 }
344 if (p === '/api/log' && req.method === 'POST') {
345 // The player reports copied timecodes so they also show up in the terminal.
346 let body = '';
347 req.on('data', (d) => (body += d));
348 req.on('end', () => {
349 try {
350 const msg = JSON.parse(body);
351 if (msg.copied) this.log(`copied: ${msg.copied}`);
352 } catch {}
353 res.writeHead(204).end();
354 });
355 return;
356 }
357 res.writeHead(404).end('not found');
358 }
359​
360 listen(port) {
361 if (!existsSync(path.join(this.runtimeDir, 'webgl2_advanced.mjs'))) {
362 throw new Error(`Rive runtime not found in ${this.runtimeDir}; run pnpm install in the rive-video-preview package`);
363 }
364 return new Promise((resolve, reject) => {
365 const server = http.createServer((req, res) => {
366 this.handle(req, res).catch((err) => {
367 res.writeHead(500).end(String(err));
368 });
369 });
370 server.once('error', reject);
371 server.listen(port, '127.0.0.1', () => resolve(server));
372 });
373 }