const baseUrl = "https://apis.viggle.ai/v1";
const headers = { Authorization: `Bearer ${process.env.VIGGLE_API_KEY}` };
const TERMINAL = new Set(["ready", "failed", "cancelled"]);
async function createVideo() {
const form = new FormData();
form.append("prompt", "a paper airplane gliding through a sunlit office");
form.append("quality", "low");
form.append("duration_s", "5");
const response = await fetch(`${baseUrl}/videos`, {
method: "POST",
headers,
body: form,
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(`HTTP ${response.status}: ${JSON.stringify(body.error ?? body)}`);
}
return response.json();
}
async function waitForVideo(id) {
for (let attempt = 0; attempt < 60; attempt++) {
const response = await fetch(`${baseUrl}/videos/${id}`, { headers });
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(`HTTP ${response.status}: ${JSON.stringify(body.error ?? body)}`);
}
const video = await response.json();
if (TERMINAL.has(video.status)) return video;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
throw new Error(`Timed out waiting for video ${id}`);
}
const created = await createVideo();
const video = await waitForVideo(created.id);
if (video.status !== "ready") {
throw new Error(`Video ${video.status}: ${JSON.stringify(video.error)}`);
}
console.log(video.video_url);