578 lines · 23.0 KB · TypeScriptRaw
import { describe, it, expect } from "vitest";import { ASPECT_RATIOS, DEFAULT_MODEL, GenerationError, IMAGE_SIZES, KEY_FILE, KEY_VAR, MissingKeyError, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_SIZE, OPENAI_KEY_VAR, OPENAI_SIZES_BY_MODEL, PROVIDERS, REDACTED, USAGE, UsageError, buildRequest, exitCodeFor, extractGeminiImage, extractOpenAiImage, geminiErrorDetail, generateImage, openAiErrorDetail, openAiSizeFor, parseArgs, parseEnvFile, redact, resolveApiKey, resolveOutPath, type Args, type Provider,} from "../gen-asset";// Key-shaped strings that are not keys. Neither may reach a URL or an error.const FAKE_KEY = "AIza-not-a-real-key-0000";const FAKE_OPENAI_KEY = "sk-proj-not-a-real-key-0000";const REPO_ROOT = "/repo";/** A reader over a fixed file map — no test touches the real `.env.local`. */const reader = (files: Record<string, string>) => (path: string): string | null => Object.prototype.hasOwnProperty.call(files, path) ? files[path] : null;interface Call { url: string; headers: Record<string, string>; body: Record<string, unknown>;}/** A fetch stub that records the one call it is given. */const stub = (payload: unknown, calls: Call[], status = 200): typeof fetch => (async (url: string, init: RequestInit) => { calls.push({ url: String(url), headers: (init.headers ?? {}) as Record<string, string>, body: JSON.parse(String(init.body)) as Record<string, unknown>, }); return { status, text: async () => JSON.stringify(payload) }; }) as unknown as typeof fetch;const args = (over: Partial<Args> = {}): Args => ({ provider: "gemini", prompt: "a constellation C in amber french knots", out: "assets/brand/logo-master.png", model: DEFAULT_MODEL, ...over,});const openAiArgs = (over: Partial<Args> = {}): Args => args({ provider: "openai", model: OPENAI_DEFAULT_MODEL, ...over });const imageResponse = (b64: string, mimeType = "image/png") => ({ candidates: [{ content: { parts: [{ inlineData: { mimeType, data: b64 } }] }, finishReason: "STOP" }],});// ---------------------------------------------------------------- args ----describe("parseArgs", () => { it("takes the prompt positionally and requires --out", () => { const a = parseArgs(["an", "empty", "inbox", "illustration", "--out", "x/y.png"]); expect(a.prompt).toBe("an empty inbox illustration"); expect(a.out).toBe("x/y.png"); expect(a.provider).toBe("gemini"); expect(a.model).toBe(DEFAULT_MODEL); expect(a.aspect).toBeUndefined(); }); it("refuses a missing prompt or a missing --out rather than defaulting", () => { expect(() => parseArgs(["--out", "x.png"])).toThrow(UsageError); expect(() => parseArgs(["a prompt"])).toThrow(/--out/); expect(() => parseArgs(["a prompt", "--out"])).toThrow(UsageError); }); it("reads --aspect, --size and --model, and validates the enumerated ones", () => { const a = parseArgs(["p", "--out", "x.png", "--aspect", "16:9", "--size", "2K", "--model", "gemini-3-pro-image"]); expect(a).toEqual({ provider: "gemini", prompt: "p", out: "x.png", aspect: "16:9", size: "2K", model: "gemini-3-pro-image", }); expect(() => parseArgs(["p", "--out", "x.png", "--aspect", "7:3"])).toThrow(/not one of/); expect(() => parseArgs(["p", "--out", "x.png", "--size", "1024x1024"])).toThrow(/not one of/); for (const r of ASPECT_RATIOS) expect(parseArgs(["p", "--out", "x.png", "--aspect", r]).aspect).toBe(r); for (const s of IMAGE_SIZES) expect(parseArgs(["p", "--out", "x.png", "--size", s]).size).toBe(s); }); it("refuses the edge-function-era flags with a sentence instead of ignoring them", () => { // A flag that quietly stops applying is the silent fallback the repo bans: // the operator would get a differently-shaped image and no signal at all. for (const flag of ["--transparent", "--quality", "--format"]) { expect(() => parseArgs(["p", "--out", "x.png", flag, "high"])).toThrow(UsageError); expect(() => parseArgs(["p", "--out", "x.png", flag, "high"])).toThrow(/not a flag of gen:asset/); } expect(() => parseArgs(["p", "--out", "x.png", "--nope"])).toThrow(/unknown flag/); });});// ----------------------------------------------------- provider choice ----describe("parseArgs — the provider", () => { it("defaults to gemini and takes openai, each with its own default model", () => { expect(parseArgs(["p", "--out", "x.png"]).provider).toBe("gemini"); expect(parseArgs(["p", "--out", "x.png", "--provider", "gemini"]).model).toBe(DEFAULT_MODEL); const a = parseArgs(["p", "--out", "x.png", "--provider", "openai"]); expect(a.provider).toBe("openai"); expect(a.model).toBe(OPENAI_DEFAULT_MODEL); }); it("lets --model override in either order, and refuses an unknown provider by name", () => { expect(parseArgs(["p", "--out", "x.png", "--provider", "openai", "--model", "dall-e-3"]).model).toBe("dall-e-3"); expect(parseArgs(["p", "--out", "x.png", "--model", "dall-e-3", "--provider", "openai"]).model).toBe("dall-e-3"); expect(() => parseArgs(["p", "--out", "x.png", "--provider", "midjourney"])).toThrow(UsageError); expect(() => parseArgs(["p", "--out", "x.png", "--provider", "midjourney"])).toThrow( new RegExp(`not one of ${PROVIDERS.join(", ")}`), ); }); it("refuses an OpenAI model it has no size list for, before any key is read", () => { expect(() => parseArgs(["p", "--out", "x.png", "--provider", "openai", "--model", "gpt-image-9"])).toThrow( /not an OpenAI image model this tool knows/, ); }); it("refuses --size on openai instead of dropping it — the sizes are fixed there", () => { expect(() => parseArgs(["p", "--out", "x.png", "--provider", "openai", "--size", "2K"])).toThrow(UsageError); expect(() => parseArgs(["p", "--out", "x.png", "--provider", "openai", "--size", "2K"])).toThrow( /Drop --size and use --aspect/, ); }); it("validates the OpenAI shape at parse time, so an unmappable one costs no request", () => { expect(() => parseArgs(["p", "--out", "x.png", "--provider", "openai", "--aspect", "21:9"])).toThrow(UsageError); expect(parseArgs(["p", "--out", "x.png", "--provider", "openai", "--aspect", "16:9"]).aspect).toBe("16:9"); }); it("takes no key on the command line at all — a key in argv is shell history", () => { for (const flag of ["--key", "--api-key", "--token"]) { expect(() => parseArgs(["p", "--out", "x.png", flag, FAKE_KEY])).toThrow(/unknown flag/); } expect(USAGE).not.toContain("--key"); });});// ------------------------------------------------- aspect → OpenAI size ----describe("openAiSizeFor", () => { /** * The whole decision, written out. Every `--aspect` the tool accepts maps to * the nearest size of the SAME orientation, or is refused by name: `null` is * a written "no", not a gap. */ const EXPECTED: Record<string, Record<string, string | null>> = { "gpt-image-1": { "1:1": "1024x1024", "2:3": "1024x1536", "3:2": "1536x1024", "3:4": "1024x1536", "4:3": "1536x1024", "4:5": "1024x1536", "5:4": "1536x1024", "9:16": "1024x1536", "16:9": "1536x1024", "21:9": null, // 1.56× wider than 3:2 — a different picture, not a crop }, "dall-e-3": { "1:1": "1024x1024", "2:3": "1024x1792", "3:2": "1792x1024", "3:4": "1024x1792", "4:3": "1792x1024", "4:5": "1024x1792", "5:4": "1792x1024", "9:16": "1024x1792", "16:9": "1792x1024", "21:9": "1792x1024", }, }; it("decides every accepted aspect for every model it knows", () => { expect(Object.keys(EXPECTED).sort()).toEqual(Object.keys(OPENAI_SIZES_BY_MODEL).sort()); for (const [model, table] of Object.entries(EXPECTED)) { expect(Object.keys(table).sort()).toEqual([...ASPECT_RATIOS].sort()); for (const [aspect, size] of Object.entries(table)) { if (size === null) { expect(() => openAiSizeFor(model, aspect)).toThrow(UsageError); expect(() => openAiSizeFor(model, aspect)).toThrow(/has no gpt-image-1 size near it/); continue; } expect(openAiSizeFor(model, aspect)).toBe(size); expect(OPENAI_SIZES_BY_MODEL[model]).toContain(size); } } }); it("never turns a portrait request landscape, or the other way round", () => { const orientation = (wxh: string): string => { const [w, h] = wxh.split("x").map(Number); return w === h ? "square" : w > h ? "landscape" : "portrait"; }; const asked = (ratio: string): string => { const [w, h] = ratio.split(":").map(Number); return w === h ? "square" : w > h ? "landscape" : "portrait"; }; for (const [model, table] of Object.entries(EXPECTED)) { for (const [aspect, size] of Object.entries(table)) { if (size !== null) expect(orientation(size)).toBe(asked(aspect)); } } }); it("asks for the square when no shape was requested", () => { expect(openAiSizeFor(OPENAI_DEFAULT_MODEL, undefined)).toBe(OPENAI_DEFAULT_SIZE); expect(openAiSizeFor("dall-e-3", undefined)).toBe(OPENAI_DEFAULT_SIZE); }); it("names the sizes the model does have, and the provider that takes the shape itself", () => { expect(() => openAiSizeFor("gpt-image-1", "21:9")).toThrow(/1024x1024, 1536x1024, 1024x1536/); expect(() => openAiSizeFor("gpt-image-1", "21:9")).toThrow(/--provider gemini/); });});// ----------------------------------------------------------------- key ----describe("resolveApiKey", () => { it("prefers the environment", () => { const key = resolveApiKey({ env: { [KEY_VAR]: ` ${FAKE_KEY} ` }, repoRoot: REPO_ROOT, readText: reader({ [`${REPO_ROOT}/${KEY_FILE}`]: `${KEY_VAR}=from-file` }), }); expect(key).toBe(FAKE_KEY); }); it("falls back to .env.local at the repo root", () => { const key = resolveApiKey({ env: {}, repoRoot: REPO_ROOT, readText: reader({ [`${REPO_ROOT}/${KEY_FILE}`]: `# a comment\nexport ${KEY_VAR}="${FAKE_KEY}"\nOTHER=1\n` }), }); expect(key).toBe(FAKE_KEY); }); it("reads OPENAI_API_KEY for openai, from the same file and in the same order", () => { const files = { [`${REPO_ROOT}/${KEY_FILE}`]: `${KEY_VAR}=${FAKE_KEY}\n${OPENAI_KEY_VAR}="${FAKE_OPENAI_KEY}"\n`, }; // One file, both names: the provider decides which line is read. expect(resolveApiKey({ env: {}, repoRoot: REPO_ROOT, readText: reader(files) }, "openai")).toBe(FAKE_OPENAI_KEY); expect(resolveApiKey({ env: {}, repoRoot: REPO_ROOT, readText: reader(files) }, "gemini")).toBe(FAKE_KEY); // And the environment still wins over the file. expect( resolveApiKey( { env: { [OPENAI_KEY_VAR]: " sk-from-env " }, repoRoot: REPO_ROOT, readText: reader(files) }, "openai", ), ).toBe("sk-from-env"); }); it("never lets one provider's key stand in for the other's", () => { const files = { [`${REPO_ROOT}/${KEY_FILE}`]: `${KEY_VAR}=${FAKE_KEY}\n` }; expect(() => resolveApiKey({ env: {}, repoRoot: REPO_ROOT, readText: reader(files) }, "openai")).toThrow( MissingKeyError, ); }); it("refuses with one sentence naming that provider's variable and the file, and exits 2", () => { const sentences: string[] = []; for (const provider of PROVIDERS) { let thrown: unknown; try { resolveApiKey({ env: {}, repoRoot: REPO_ROOT, readText: reader({}) }, provider); } catch (e) { thrown = e; } expect(thrown).toBeInstanceOf(MissingKeyError); const message = (thrown as Error).message; expect(message).toContain(`${REPO_ROOT}/${KEY_FILE}`); // One sentence: no newline, and it never carries the other provider's name. expect(message).not.toContain("\n"); expect(exitCodeFor(thrown)).toBe(2); sentences.push(message); } const [gemini, openai] = sentences; expect(gemini).toContain(KEY_VAR); expect(gemini).toContain("aistudio.google.com"); expect(openai).toContain(OPENAI_KEY_VAR); expect(openai).toContain("platform.openai.com"); expect(exitCodeFor(new UsageError("bad flag"))).toBe(2); expect(exitCodeFor(new GenerationError("refused"))).toBe(1); }); it("ignores an empty or malformed assignment rather than passing it off as a key", () => { const files = { [`${REPO_ROOT}/${KEY_FILE}`]: `${KEY_VAR}=\n=orphan\n` }; expect(() => resolveApiKey({ env: { [KEY_VAR]: " " }, repoRoot: REPO_ROOT, readText: reader(files) })).toThrow( MissingKeyError, ); });});describe("parseEnvFile", () => { it("handles export prefixes, quotes, comments and blank lines", () => { expect(parseEnvFile(`\n# c\nexport A="one"\nB='two'\nC=three\nnot a pair\n`)).toEqual({ A: "one", B: "two", C: "three", }); }); it("reads both key names out of one file", () => { expect(parseEnvFile(`${KEY_VAR}=${FAKE_KEY}\n${OPENAI_KEY_VAR}=${FAKE_OPENAI_KEY}\n`)).toEqual({ [KEY_VAR]: FAKE_KEY, [OPENAI_KEY_VAR]: FAKE_OPENAI_KEY, }); });});describe("redact", () => { it("replaces every occurrence of the key and leaves text without one alone", () => { expect(redact(`Incorrect API key provided: ${FAKE_OPENAI_KEY}. ${FAKE_OPENAI_KEY}`, FAKE_OPENAI_KEY)).toBe( `Incorrect API key provided: ${REDACTED}. ${REDACTED}`, ); expect(redact("nothing to hide", FAKE_OPENAI_KEY)).toBe("nothing to hide"); });});// ------------------------------------------------------------- request ----describe("buildRequest — gemini", () => { it("asks for an image from the named model and carries the key in the header only", () => { const req = buildRequest(args({ aspect: "16:9", size: "2K" }), FAKE_KEY); expect(req.url).toBe( `https://generativelanguage.googleapis.com/v1/models/${DEFAULT_MODEL}:generateContent`, ); // The URL is logged by proxies and lands in shell history — never the key. expect(req.url).not.toContain(FAKE_KEY); expect(req.url).not.toContain("key="); expect(req.headers["x-goog-api-key"]).toBe(FAKE_KEY); expect(req.body).toMatchObject({ contents: [{ parts: [{ text: args().prompt }] }], generationConfig: { responseModalities: ["IMAGE"], imageConfig: { aspectRatio: "16:9", imageSize: "2K" } }, }); }); it("omits imageConfig entirely when neither shape nor size was asked for", () => { const req = buildRequest(args(), FAKE_KEY); expect(req.body.generationConfig).toEqual({ responseModalities: ["IMAGE"] }); });});describe("buildRequest — openai", () => { it("POSTs images/generations with one image, the mapped size and a png", () => { const req = buildRequest(openAiArgs({ aspect: "3:2" }), FAKE_OPENAI_KEY); expect(req.url).toBe("https://api.openai.com/v1/images/generations"); expect(req.body).toEqual({ model: OPENAI_DEFAULT_MODEL, prompt: openAiArgs().prompt, n: 1, size: "1536x1024", output_format: "png", }); }); it("carries the key in Authorization: Bearer and nowhere else", () => { const req = buildRequest(openAiArgs(), FAKE_OPENAI_KEY); expect(req.headers.authorization).toBe(`Bearer ${FAKE_OPENAI_KEY}`); expect(req.url).not.toContain(FAKE_OPENAI_KEY); expect(JSON.stringify(req.body)).not.toContain(FAKE_OPENAI_KEY); }); it("asks dall-e-3 for base64 instead, because a url expires before it is read", () => { const req = buildRequest(openAiArgs({ model: "dall-e-3", aspect: "16:9" }), FAKE_OPENAI_KEY); expect(req.body).toMatchObject({ model: "dall-e-3", size: "1792x1024", response_format: "b64_json" }); expect(req.body.output_format).toBeUndefined(); }); it("defaults to the square when no shape was asked for", () => { expect(buildRequest(openAiArgs(), FAKE_OPENAI_KEY).body.size).toBe(OPENAI_DEFAULT_SIZE); });});describe("generateImage — gemini", () => { it("POSTs the prompt and the key, and hands back the decoded bytes", async () => { const calls: Call[] = []; const b64 = Buffer.from("PNGBYTES").toString("base64"); const image = await generateImage(args({ aspect: "1:1" }), FAKE_KEY, { fetchImpl: stub(imageResponse(b64), calls) }); expect(calls).toHaveLength(1); expect(calls[0].url).toContain(`${DEFAULT_MODEL}:generateContent`); expect(calls[0].url).not.toContain(FAKE_KEY); expect(calls[0].headers["x-goog-api-key"]).toBe(FAKE_KEY); expect(JSON.stringify(calls[0].body)).toContain(args().prompt); expect(image.bytes.toString()).toBe("PNGBYTES"); expect(image.mimeType).toBe("image/png"); }); it("surfaces an HTTP refusal with the API's own reason, and never the key", async () => { const calls: Call[] = []; const payload = { error: { code: 400, status: "INVALID_ARGUMENT", message: "Image generation is not available in your country" }, }; const call = generateImage(args(), FAKE_KEY, { fetchImpl: stub(payload, calls, 400) }); await expect(call).rejects.toThrow(GenerationError); await expect(call).rejects.toThrow(/HTTP 400 INVALID_ARGUMENT: Image generation is not available/); await expect(call).rejects.not.toThrow(new RegExp(FAKE_KEY)); }); it("surfaces a 200 that carries no image rather than writing an empty file", async () => { const calls: Call[] = []; const blocked = { promptFeedback: { blockReason: "SAFETY" } }; await expect(generateImage(args(), FAKE_KEY, { fetchImpl: stub(blocked, calls) })).rejects.toThrow( /blocked \(SAFETY\)/, ); }); it("reports a non-JSON body instead of throwing a parse error at the operator", async () => { const fetchImpl = (async () => ({ status: 502, text: async () => "<html>bad gateway</html>" })) as unknown as typeof fetch; await expect(generateImage(args(), FAKE_KEY, { fetchImpl })).rejects.toThrow(/HTTP 502 with a non-JSON body/); });});describe("generateImage — openai", () => { const b64Image = (b64: string) => ({ created: 1, data: [{ b64_json: b64 }] }); it("POSTs the prompt to OpenAI and hands back the decoded bytes", async () => { const calls: Call[] = []; const b64 = Buffer.from("PNGBYTES").toString("base64"); const image = await generateImage(openAiArgs({ aspect: "1:1" }), FAKE_OPENAI_KEY, { fetchImpl: stub(b64Image(b64), calls), }); expect(calls).toHaveLength(1); expect(calls[0].url).toBe("https://api.openai.com/v1/images/generations"); expect(calls[0].url).not.toContain(FAKE_OPENAI_KEY); expect(calls[0].headers.authorization).toBe(`Bearer ${FAKE_OPENAI_KEY}`); expect(calls[0].body).toEqual({ model: OPENAI_DEFAULT_MODEL, prompt: openAiArgs().prompt, n: 1, size: "1024x1024", output_format: "png", }); expect(JSON.stringify(calls[0].body)).not.toContain(FAKE_OPENAI_KEY); expect(image.bytes.toString()).toBe("PNGBYTES"); expect(image.mimeType).toBe("image/png"); }); it("surfaces OpenAI's own sentence, with the key redacted where it echoed it back", async () => { const calls: Call[] = []; const payload = { error: { message: `Incorrect API key provided: ${FAKE_OPENAI_KEY}. You can find your API key at https://platform.openai.com/account/api-keys.`, type: "invalid_request_error", code: "invalid_api_key", }, }; const call = generateImage(openAiArgs(), FAKE_OPENAI_KEY, { fetchImpl: stub(payload, calls, 401) }); await expect(call).rejects.toThrow(GenerationError); await expect(call).rejects.toThrow(/HTTP 401 invalid_request_error: Incorrect API key provided/); await expect(call).rejects.toThrow(new RegExp(REDACTED.replace(/[[\]]/g, "\\$&"))); await expect(call).rejects.not.toThrow(new RegExp(FAKE_OPENAI_KEY)); }); it("surfaces a 200 that carries no bytes rather than writing an empty file", async () => { const calls: Call[] = []; await expect( generateImage(openAiArgs(), FAKE_OPENAI_KEY, { fetchImpl: stub({ data: [{ url: "https://x/y.png" }] }, calls) }), ).rejects.toThrow(/no image — it answered a url, not bytes/); await expect( generateImage(openAiArgs(), FAKE_OPENAI_KEY, { fetchImpl: stub({ data: [] }, calls) }), ).rejects.toThrow(/no data/); });});// ------------------------------------------------------------ response ----describe("extractGeminiImage", () => { it("reads either wire spelling of the inline data part", () => { const b64 = Buffer.from("x").toString("base64"); expect( extractGeminiImage({ candidates: [{ content: { parts: [{ inline_data: { mime_type: "image/webp", data: b64 } }] } }], }), ).toEqual({ bytes: Buffer.from("x"), mimeType: "image/webp" }); }); it("explains a text-only answer with the model's own words", () => { const payload = { candidates: [ { content: { parts: [{ text: "I can't create that image." }] }, finishReason: "IMAGE_SAFETY" }, ], }; expect(() => extractGeminiImage(payload)).toThrow(/no image.*finishReason IMAGE_SAFETY.*I can't create that image/s); }); it("refuses an empty envelope", () => { expect(() => extractGeminiImage({})).toThrow(/no candidates/); });});describe("extractOpenAiImage", () => { it("decodes data[0].b64_json as a png", () => { const b64 = Buffer.from("x").toString("base64"); expect(extractOpenAiImage({ data: [{ b64_json: b64 }] })).toEqual({ bytes: Buffer.from("x"), mimeType: "image/png", }); }); it("refuses an empty envelope", () => { expect(() => extractOpenAiImage({})).toThrow(/no data/); });});describe("apiErrorDetail", () => { it("names Google's status and message, and degrades to the code alone", () => { expect(geminiErrorDetail({ error: { status: "PERMISSION_DENIED", message: "API key not valid" } }, 403)).toBe( "HTTP 403 PERMISSION_DENIED: API key not valid", ); expect(geminiErrorDetail({ nope: 1 }, 500)).toBe("HTTP 500"); }); it("names OpenAI's type and message, and degrades to the code alone", () => { expect( openAiErrorDetail({ error: { type: "image_generation_user_error", message: "Your request was rejected" } }, 400), ).toBe("HTTP 400 image_generation_user_error: Your request was rejected"); expect(openAiErrorDetail({ error: { message: "Rate limit reached" } }, 429)).toBe("HTTP 429: Rate limit reached"); expect(openAiErrorDetail({ nope: 1 }, 500)).toBe("HTTP 500"); });});// ---------------------------------------------------------------- file ----describe("resolveOutPath", () => { it("resolves relative to the cwd and keeps a matching extension", () => { expect(resolveOutPath("a/b.png", "image/png", "/w")).toBe("/w/a/b.png"); expect(resolveOutPath("/abs/b.jpeg", "image/jpeg", "/w")).toBe("/abs/b.jpeg"); }); it("corrects the extension when the model answered with another type", () => { expect(resolveOutPath("a/b.png", "image/webp", "/w")).toBe("/w/a/b.webp"); });});// The provider list is the one place a third provider would be declared.describe("PROVIDERS", () => { it("is exactly the two this tool speaks", () => { const expected: readonly Provider[] = ["gemini", "openai"]; expect([...PROVIDERS]).toEqual([...expected]); });});