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

registry.mjs

42 lines1.7 KB

1// Registry of running players, one state file per target.
2// Shared by the CLI (reuse / --stop / --status) and the MCP server (seek, project lookup).
3// It lives under the home dir rather than os.tmpdir(): MCP clients start servers with a
4// trimmed environment (no TMPDIR on macOS), which would point them at a different temp dir.
5import { createHash } from 'node:crypto';
6import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
7import os from 'node:os';
8import path from 'node:path';
9​
10export const STATE_DIR = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), 'rive-video-preview');
11export const stateFile = (target) => path.join(STATE_DIR, createHash('sha1').update(target).digest('hex').slice(0, 16) + '.json');
12​
13async function probe(file) {
14 try {
15 const st = JSON.parse(readFileSync(file, 'utf8'));
16 process.kill(st.pid, 0);
17 const res = await fetch(`http://127.0.0.1:${st.port}/api/ping`, { signal: AbortSignal.timeout(1000) });
18 const info = await res.json();
19 if (info.app === 'rive-video-preview' && info.target === st.target) return { ...st, ...info };
20 } catch {}
21 rmSync(file, { force: true });
22 return null;
24​
25/** The player running for `target`, or null (stale state files are removed). */
26export async function findRunning(target) {
27 const file = stateFile(target);
28 if (!existsSync(file)) return null;
29 return probe(file);
31​
32/** Every live player. */
33export async function listRunning() {
34 let names = [];
35 try {
36 names = readdirSync(STATE_DIR).filter((n) => n.endsWith('.json'));
37 } catch {
38 return [];
39 }
40 const found = await Promise.all(names.map((n) => probe(path.join(STATE_DIR, n))));
41 return found.filter(Boolean);