#!/usr/bin/env node // Image API example client (Node.js 22+, no packages). // // Submits one image job, polls it to a final state and saves the results. // POST spends API credits; polling and downloads do not. // // node image_job.cjs background-removal IMAGE OUT_DIR [model=bria] [output_format=webp] // node image_job.cjs upscale IMAGE OUT_DIR [model=print] [scale=4] [content=text] [output_format=png] // node image_job.cjs generation PROMPT_FILE OUT_DIR [width=1280] [height=768] [num_images=2] [seed=7] // // Environment: ARTWORK_API_KEY (the same ip_art_ key as artwork checks), // ARTWORK_API_BASE_URL (HTTPS origin, no path) and ARTWORK_IDEMPOTENCY_KEY // (persist it before running; reuse the same value and inputs after a timeout). // // Bounded: at most 5 attempts per request, a shared 15-minute budget, waits // capped at 10 seconds unless Retry-After asks for longer, no redirects. // Exit codes: 0 completed, 2 job failed, 1 request or usage error. Prints only // the job ID, status, credits, error codes, request IDs and saved file paths. "use strict"; const fs = require("node:fs"); const path = require("node:path"); const ROUTES = { "background-removal": "background-removals", upscale: "upscales", generation: "generations" }; const INTEGER_FIELDS = new Set(["width", "height", "num_images", "seed"]); const EXTENSIONS = { "image/png": "png", "image/webp": "webp", "image/jpeg": "jpg" }; const BUDGET_MS = 15 * 60 * 1000; const MAX_DOWNLOAD = 64 * 1024 * 1024; const USAGE = "node image_job.cjs background-removal|upscale|generation INPUT OUT_DIR [field=value ...]"; class Stop extends Error {} const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function settings() { const key = process.env.ARTWORK_API_KEY || ""; const base = process.env.ARTWORK_API_BASE_URL || ""; const idem = process.env.ARTWORK_IDEMPOTENCY_KEY || ""; if (!/^ip_art_[A-Za-z0-9_-]{8,}$/.test(key)) throw new Stop("Set ARTWORK_API_KEY to your ip_art_ API key"); let url; try { url = new URL(base); } catch { throw new Stop("ARTWORK_API_BASE_URL must be an https:// origin with no path"); } const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname); if (!(url.protocol === "https:" || (url.protocol === "http:" && loopback)) || url.pathname !== "/" || url.search || url.hash || url.username) throw new Stop("ARTWORK_API_BASE_URL must be an https:// origin with no path"); if (!/^[\x21-\x7e]{1,200}$/.test(idem)) throw new Stop("Set ARTWORK_IDEMPOTENCY_KEY to 1-200 visible ASCII characters and keep it for retries"); return { key, base: url.origin, idem }; } function retryAfter(response, attempt) { const value = response?.headers.get("retry-after"); if (value && /^\d+$/.test(value)) return Number(value) * 1000; if (value && Number.isFinite(Date.parse(value))) return Math.max(0, Date.parse(value) - Date.now()); return Math.min(10, 2 ** attempt) * 1000; } // One logical request with bounded retries on connection loss, 429 and 5xx. async function request(method, url, deadline, { key, body, headers = {}, raw = false } = {}) { for (let attempt = 0; attempt < 5; attempt++) { let wait; let response; try { response = await fetch(url, { method, body, redirect: "manual", signal: AbortSignal.timeout(20000), headers: { ...headers, ...(key ? { Authorization: "Bearer " + key } : {}) }, }); } catch { response = null; // response lost: retry with the SAME idempotency key } if (response) { if (response.status >= 300 && response.status < 400) throw new Stop("Redirect refused"); if (response.ok) { const data = Buffer.from(await response.arrayBuffer()); if (data.length > MAX_DOWNLOAD) throw new Stop("Response too large"); if (raw) return { data, type: response.headers.get("content-type") || "" }; try { return JSON.parse(data.toString("utf8")); } catch { response = null; } } else if (response.status !== 429 && response.status < 500) { let code = "http_" + response.status; let requestId = ""; try { const payload = await response.json(); if (/^[a-z_]{1,64}$/.test(payload.error.code)) code = payload.error.code; if (/^[0-9a-f-]{36}$/.test(payload.request_id)) requestId = " request_id=" + payload.request_id; } catch {} throw new Stop(`HTTP ${response.status} ${code}${requestId}`); } } wait = response ? retryAfter(response, attempt) : Math.min(10, 2 ** attempt) * 1000; if (attempt === 4 || Date.now() + wait > deadline) throw new Stop("Gave up retrying; rerun later with the same ARTWORK_IDEMPOTENCY_KEY"); await sleep(wait); } } async function main(argv) { const [command, input, outDir, ...extras] = argv; if (!ROUTES[command] || !input || !outDir || extras.some((e) => !e.includes("="))) throw new Stop(USAGE); const { key, base, idem } = settings(); const fields = Object.fromEntries(extras.map((e) => [e.slice(0, e.indexOf("=")), e.slice(e.indexOf("=") + 1)])); fs.mkdirSync(outDir, { recursive: true }); const deadline = Date.now() + BUDGET_MS; let body; const headers = { "Idempotency-Key": idem }; if (command === "generation") { const json = Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, INTEGER_FIELDS.has(k) ? Number(v) : v])); json.prompt = fs.readFileSync(input, "utf8").trim(); body = JSON.stringify(json); headers["Content-Type"] = "application/json"; } else { body = new FormData(); for (const [name, value] of Object.entries(fields)) body.append(name, value); body.append("file", new Blob([fs.readFileSync(input)]), "image"); } const job = await request("POST", `${base}/api/v1/images/${ROUTES[command]}`, deadline, { key, body, headers }); if (!/^[0-9a-f-]{36}$/.test(job.id)) throw new Stop("Unexpected response"); console.log(JSON.stringify({ id: job.id, reserved_credits: job.reserved_credits })); let delay = 2000; let detail; for (;;) { detail = await request("GET", `${base}/api/v1/images/jobs/${job.id}`, deadline, { key }); if (["completed", "failed"].includes(detail.processing_status)) break; if (Date.now() + delay > deadline) throw new Stop(`Still ${detail.processing_status}; resume polling job ${job.id} later`); await sleep(delay); delay = Math.min(10000, delay * 2); } if (detail.processing_status === "failed") { console.log(JSON.stringify({ id: job.id, processing_status: "failed", error_code: detail.error_code })); return 2; } const saved = []; for (const output of (detail.outputs || []).slice(0, 8)) { if (typeof output.url !== "string" || !output.url.startsWith("/api/v1/images/outputs/")) throw new Stop("Unexpected output link"); const { data, type } = await request("GET", base + output.url, deadline, { raw: true }); // signed link: no API key sent const extension = EXTENSIONS[type.split(";")[0].trim()]; if (!extension || !Number.isInteger(output.index)) throw new Stop("Unexpected output type"); const target = path.join(outDir, `${job.id}-${output.index}.${extension}`); fs.writeFileSync(target, data); saved.push(target); } console.log(JSON.stringify({ id: job.id, processing_status: "completed", charged_credits: detail.charged_credits, saved })); return 0; } main(process.argv.slice(2)).then( (code) => process.exit(code), (error) => { console.error(error instanceof Stop ? error.message : "Error: " + (error?.name || "unknown")); process.exit(1); }, );