All files / src/image GeneratedImage.ts

100% Statements 22/22
100% Branches 8/8
100% Functions 10/10
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71          16x 16x       10x       18x       2x       2x       3x             8x 4x     4x 3x 3x 1x   2x 2x     1x             1x 1x             2x 2x 2x       3x      
import fs from "fs/promises";
import { Readable } from "stream";
import { ImageResponse } from "../providers/Provider.js";
 
export class GeneratedImage extends String {
  constructor(private readonly response: ImageResponse) {
    super(response.url || "");
  }
 
  get url(): string | undefined {
    return this.response.url;
  }
 
  get data(): string | undefined {
    return this.response.data;
  }
 
  get revisedPrompt(): string | undefined {
    return this.response.revised_prompt;
  }
 
  get mimeType(): string | undefined {
    return this.response.mime_type;
  }
 
  get isBase64(): boolean {
    return !!this.data;
  }
 
  /**
   * Returns the raw binary image data as a Buffer.
   */
  async toBuffer(): Promise<Buffer> {
    if (this.data) {
      return Buffer.from(this.data, "base64");
    }
 
    if (this.url) {
      const resp = await fetch(this.url);
      if (!resp.ok) {
        throw new Error(`Failed to download image from ${this.url}: ${resp.statusText}`);
      }
      const arrayBuffer = await resp.arrayBuffer();
      return Buffer.from(arrayBuffer);
    }
 
    throw new Error("No image data or URL available");
  }
 
  /**
   * Returns a Readable stream of the image data.
   */
  async toStream(): Promise<Readable> {
    const buffer = await this.toBuffer();
    return Readable.from(buffer);
  }
 
  /**
   * Saves the image to the specified local path.
   */
  async save(path: string): Promise<string> {
    const buffer = await this.toBuffer();
    await fs.writeFile(path, buffer);
    return path;
  }
 
  toString() {
    return this.valueOf();
  }
}