Open History to see the last commit
1// Builds a Rive CLI project to an unsigned .riv and extracts the timeline
2// metadata (artboards, animations, audio-event timing) the player needs.
3import { spawn } from 'node:child_process';
4import { readFile } from 'node:fs/promises';
5import path from 'node:path';
6
7function run(cmd, args, cwd) {
8 return new Promise((resolve) => {
9 const child = spawn(cmd, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
10 let stdout = '';
11 let stderr = '';
12 child.stdout.on('data', (d) => (stdout += d));
13 child.stderr.on('data', (d) => (stderr += d));
14 child.on('error', (err) => resolve({ code: -1, stdout, stderr: String(err) }));
15 child.on('close', (code) => resolve({ code, stdout, stderr }));
16 });
17}
18
19function parseJson(text) {
20 const start = text.indexOf('{');
21 if (start < 0) return null;
22 try {
23 return JSON.parse(text.slice(start));
24 } catch {
25 return null;
26 }
27}
28
29function formatProblems(list) {
30 return (list || [])
31 .map((p) => (typeof p === 'string' ? p : p.message ? `${p.file ?? ''}${p.line ? ':' + p.line : ''} ${p.message}`.trim() : JSON.stringify(p)))
32 .join('\n');
33}
34
35/** Build the project. Returns { ok, riv: Buffer, error, warnings, buildMs }. */
36export async function buildProject(dir) {
37 const t0 = Date.now();
38 const res = await run('rive', ['.', '--once', '--format=json'], dir);
39 const report = parseJson(res.stdout);
40 if (!report) {
41 return { ok: false, error: (res.stderr || res.stdout || `rive exited with ${res.code}`).trim() };
42 }
43 if (!report.success || !report.data?.riv) {
44 const msg = formatProblems(report.errors) || formatProblems(report.data?.problems) || res.stderr.trim() || 'build failed';
45 return { ok: false, error: msg };
46 }
47 const rivPath = path.resolve(dir, report.data.riv);
48 const riv = await readFile(rivPath);
49 return {
50 ok: true,
51 riv,
52 rivPath,
53 warnings: formatProblems(report.warnings),
54 buildMs: Date.now() - t0,
55 };
56}
57
58/** Run `rive inspect` and reduce it to what the player needs. */
59export async function inspectProject(dir) {
60 const res = await run('rive', ['inspect', '.', '--json'], dir);
61 const tree = parseJson(res.stdout);
62 if (!tree) return null;
63 return extractMeta(tree);
64}
65
66function walk(node, visit) {
67 if (Array.isArray(node)) {
68 for (const n of node) walk(n, visit);
69 return;
70 }
71 if (!node || typeof node !== 'object') return;
72 if (visit(node) === false) return;
73 for (const key in node) {
74 const v = node[key];
75 if (v && typeof v === 'object') walk(v, visit);
76 }
77}
78
79export function extractMeta(tree) {
80 const byId = new Map();
81 walk(tree, (n) => {
82 if (n.type && n.id != null) byId.set(n.id, n);
83 });
84
85 const artboards = (tree.artboards || []).map((ab) => {
86 const animations = [];
87 const stateMachines = [];
88 walk(ab.children, (n) => {
89 if (n.type === 'Artboard') return false; // don't descend into other artboards
90 if (n.type === 'LinearAnimation') animations.push(n);
91 if (n.type === 'StateMachine') stateMachines.push(n);
92 });
93
94 // The animation the default state machine plays first is the "main" one.
95 let defaultAnimationId = null;
96 const sm = stateMachines.find((s) => s.id === ab.defaultStateMachineId) || stateMachines[0];
97 if (sm) {
98 walk(sm, (n) => {
99 if (defaultAnimationId == null && n.type === 'AnimationState' && n.animationId != null) {
100 defaultAnimationId = n.animationId;
101 }
102 });
103 }
104
105 const anims = animations.map((a) => {
106 const fps = a.fps || 60;
107 const audio = [];
108 for (const ko of a.children || []) {
109 if (ko.type !== 'KeyedObject') continue;
110 const target = byId.get(ko.objectId);
111 if (!target || target.type !== 'AudioEvent') continue;
112 const asset = byId.get(target.assetId);
113 walk(ko.children, (n) => {
114 if (n.type === 'KeyFrameCallback') {
115 audio.push({
116 frame: n.frame,
117 time: n.frame / fps,
118 event: target.name,
119 asset: asset?.name ?? null,
120 volume: asset?.volume ?? 1,
121 });
122 }
123 });
124 }
125 audio.sort((x, y) => x.time - y.time);
126 const useWork = a.enableWorkArea && a.workStart !== 4294967295 && a.workEnd !== 4294967295;
127 return {
128 id: a.id,
129 name: a.name,
130 fps,
131 durationFrames: a.duration,
132 startFrame: useWork ? a.workStart : 0,
133 endFrame: useWork ? a.workEnd : a.duration,
134 loop: a.enums?.loopValue ?? a.loopValue,
135 audio,
136 };
137 });
138
139 const def = anims.find((a) => a.id === defaultAnimationId) || anims[0];
140 return {
141 name: ab.name,
142 width: ab.width,
143 height: ab.height,
144 defaultAnimation: def?.name ?? null,
145 animations: anims,
146 };
147 });
148
149 const defaultArtboard = tree.defaultArtboard?.name ?? artboards[0]?.name ?? null;
150 return { defaultArtboard, artboards, problems: tree.problems || [] };
151}