@fungi.computer/darkroom 0.11.11 → 0.11.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +8 -2
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
@@ -0,0 +1,712 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import * as z from "zod";
3
+ import {
4
+ getMediaModel,
5
+ listMediaModels,
6
+ validateMediaGenerationSettings,
7
+ } from "../src/index.js";
8
+ import {
9
+ estimateGatewayMilliunits,
10
+ gatewayInput,
11
+ mediaUnits,
12
+ } from "../src/gateway-models.js";
13
+ import { generate } from "../src/cloudflare/provider.js";
14
+
15
+ const png = Uint8Array.from([
16
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d, 0x49, 0x48,
17
+ 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0,
18
+ ]);
19
+ /** The first bytes of an MP4: a 24-byte `ftyp` box. */
20
+ const mp4 = Uint8Array.from([
21
+ 0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,
22
+ 0x69, 0x73, 0x6f, 0x6d, 0x6d, 0x70, 0x34, 0x31,
23
+ ]);
24
+
25
+ const image = (size = "1024x1536") => {
26
+ const [width, height] = size.split("x").map(Number);
27
+ return validateMediaGenerationSettings({
28
+ model: "openai/gpt-image-2",
29
+ prompt: "a seed catalogue cover",
30
+ width: width ?? 0,
31
+ height: height ?? 0,
32
+ });
33
+ };
34
+ const video = (durationSeconds?: number, size = "1280x720") => {
35
+ const [width, height] = size.split("x").map(Number);
36
+ const settings: Parameters<typeof validateMediaGenerationSettings>[0] = {
37
+ model: "bytedance/seedance-2.0",
38
+ prompt: "fern fronds unfurling",
39
+ width: width ?? 0,
40
+ height: height ?? 0,
41
+ };
42
+ if (durationSeconds !== undefined) settings.durationSeconds = durationSeconds;
43
+ return validateMediaGenerationSettings(settings);
44
+ };
45
+ const minimaxVideo = (durationSeconds?: number, size = "1366x768") => {
46
+ const [width, height] = size.split("x").map(Number);
47
+ const settings: Parameters<typeof validateMediaGenerationSettings>[0] = {
48
+ model: "minimax/h3-max",
49
+ prompt: "fern fronds unfurling",
50
+ width: width ?? 0,
51
+ height: height ?? 0,
52
+ };
53
+ if (durationSeconds !== undefined) settings.durationSeconds = durationSeconds;
54
+ return validateMediaGenerationSettings(settings);
55
+ };
56
+
57
+ describe("gateway Media models", () => {
58
+ it("accepts only each model's provider sizes and video bounds", () => {
59
+ expect(() => image("1024x768")).toThrow("accepts only these sizes");
60
+ expect(() => video(5, "1000x720")).toThrow("accepts only these sizes");
61
+ expect(video().durationSeconds).toBe(5);
62
+ expect(() => video(3)).toThrow("durationSeconds");
63
+ expect(() => video(13)).toThrow("durationSeconds");
64
+ expect(() =>
65
+ validateMediaGenerationSettings({
66
+ model: "openai/gpt-image-2",
67
+ prompt: "x",
68
+ width: 1024,
69
+ height: 1024,
70
+ durationSeconds: 5,
71
+ }),
72
+ ).toThrow("does not take a duration");
73
+ });
74
+
75
+ it("bills images as one unit and video per requested second", () => {
76
+ expect(mediaUnits(image())).toEqual({ unit: "image", units: 1 });
77
+ expect(mediaUnits(video(8))).toEqual({ unit: "video_second", units: 8 });
78
+ });
79
+
80
+ it("quotes published gateway rates in milliunits", () => {
81
+ // 1,584 output tokens at $30/M + 22 prompt characters bounded at $5/M.
82
+ expect(estimateGatewayMilliunits(image(), [])).toBe(
83
+ Math.ceil((1584 * 30 + 22 * 5) / 10),
84
+ );
85
+ // Seedance 2.0 at 720p is $0.15/s; 480p is $0.07/s.
86
+ expect(estimateGatewayMilliunits(video(5), [])).toBe(75_000);
87
+ expect(estimateGatewayMilliunits(video(4, "854x480"), [])).toBe(28_000);
88
+ });
89
+
90
+ it("passes each pinned image format to the gateway provider", () => {
91
+ for (const format of ["png", "jpeg", "webp"] as const)
92
+ expect(gatewayInput(image(), [], format)).toMatchObject({
93
+ output_format: format,
94
+ });
95
+ });
96
+
97
+ it("builds each provider body from its documented schema", () => {
98
+ expect(gatewayInput(image())).toEqual({
99
+ prompt: "a seed catalogue cover",
100
+ size: "1024x1536",
101
+ quality: "medium",
102
+ output_format: "png",
103
+ });
104
+ expect(gatewayInput(video(6, "720x1280"))).toEqual({
105
+ prompt: "fern fronds unfurling",
106
+ duration: 6,
107
+ resolution: "720p",
108
+ aspect_ratio: "9:16",
109
+ // Seedance sound defaults On (Botanical's choice; the provider has none).
110
+ generate_audio: true,
111
+ });
112
+ expect(
113
+ gatewayInput(
114
+ {
115
+ ...video(5, "720x720"),
116
+ references: [
117
+ { computerId: "pictures", path: "panel.png", role: "first-frame" },
118
+ ],
119
+ },
120
+ [
121
+ {
122
+ bytes: png,
123
+ format: "png",
124
+ width: 1,
125
+ height: 1,
126
+ },
127
+ ],
128
+ ),
129
+ ).toMatchObject({
130
+ image: `data:image/png;base64,${btoa(String.fromCharCode(...png))}`,
131
+ });
132
+ });
133
+
134
+ it("encodes a full panel reference across bounded base64 chunks", () => {
135
+ const bytes = new Uint8Array(114_619).map((_, index) => index % 251);
136
+ const input = gatewayInput(
137
+ {
138
+ ...video(5, "720x720"),
139
+ references: [
140
+ { computerId: "pictures", path: "panel.png", role: "first-frame" },
141
+ ],
142
+ },
143
+ [{ bytes, format: "png", width: 1024, height: 1024 }],
144
+ );
145
+ const { image } = z.object({ image: z.string() }).parse(input);
146
+ const encoded = image.split(",")[1];
147
+ expect(encoded).toBeDefined();
148
+ expect(
149
+ Uint8Array.from(atob(encoded ?? ""), (char) => char.charCodeAt(0)),
150
+ ).toEqual(bytes);
151
+ });
152
+
153
+ // Replayed provider fixtures: the documented gateway answer shape
154
+ // (`{ state, result: { image | video } }`), since no live key runs here.
155
+ it.each([
156
+ ["image", image(), "image", png, "png"],
157
+ ["video", video(5), "video", mp4, "mp4"],
158
+ ] as const)(
159
+ "fetches the %s result URL through the gateway route",
160
+ async (_label, settings, field, bytes, format) => {
161
+ const run = vi.fn(() =>
162
+ Promise.resolve({
163
+ state: "Completed",
164
+ result: { [field]: `https://results.example/${field}` },
165
+ }),
166
+ );
167
+ const fetchResult = vi.fn<typeof fetch>(() =>
168
+ Promise.resolve(new Response(bytes)),
169
+ );
170
+
171
+ const ai = { run };
172
+ await expect(
173
+ generate(
174
+ ai,
175
+ settings,
176
+ [],
177
+ undefined,
178
+ { gateway: { id: "fungi-hub" } },
179
+ fetchResult,
180
+ ),
181
+ ).resolves.toMatchObject({ format });
182
+ expect(run).toHaveBeenCalledWith(settings.model, gatewayInput(settings), {
183
+ gateway: { id: "fungi-hub" },
184
+ });
185
+ expect(fetchResult.mock.calls[0]?.[0]).toBe(
186
+ `https://results.example/${field}`,
187
+ );
188
+ },
189
+ );
190
+
191
+ // MiniMax answers with its documented `{task: {status, content: {url}}}`
192
+ // wrapper, not the Unified gateway's `{state, result}` shape.
193
+ it("dispatches MiniMax H3 Max's exact documented request and decodes its task wrapper", async () => {
194
+ const settings = minimaxVideo(5);
195
+ const run = vi.fn(() =>
196
+ Promise.resolve({
197
+ task: {
198
+ id: "441805798383681",
199
+ model: "MiniMax-H3-Max",
200
+ status: "succeeded",
201
+ created_at: 1_789_415_547,
202
+ updated_at: 1_789_415_554,
203
+ content: {
204
+ url: "https://examples.aig.cloudflare.com/minimax/h3-max/clip.mp4",
205
+ },
206
+ resolution: "768P",
207
+ duration: 5,
208
+ ratio: "16:9",
209
+ task_type: "generation",
210
+ },
211
+ }),
212
+ );
213
+ const fetchResult = vi.fn<typeof fetch>(() =>
214
+ Promise.resolve(new Response(mp4)),
215
+ );
216
+ const ai = { run };
217
+ await expect(
218
+ generate(ai, settings, [], undefined, undefined, fetchResult),
219
+ ).resolves.toEqual({ bytes: mp4, format: "mp4" });
220
+ expect(run).toHaveBeenCalledWith(
221
+ settings.model,
222
+ {
223
+ content: [{ type: "text", text: "fern fronds unfurling" }],
224
+ duration: 5,
225
+ resolution: "768P",
226
+ ratio: "16:9",
227
+ },
228
+ undefined,
229
+ );
230
+ expect(fetchResult.mock.calls[0]?.[0]).toBe(
231
+ "https://examples.aig.cloudflare.com/minimax/h3-max/clip.mp4",
232
+ );
233
+ });
234
+
235
+ it.each(["queued", "running", "failed", "cancelled"] as const)(
236
+ "refuses a MiniMax task that has not succeeded (%s)",
237
+ async (status) => {
238
+ const run = () => Promise.resolve({ task: { id: "1", status } });
239
+ await expect(
240
+ generate({ run }, minimaxVideo(5), []),
241
+ ).rejects.toMatchObject({ stage: "normalization" });
242
+ },
243
+ );
244
+
245
+ it("refuses a non-HTTPS or non-MP4 MiniMax result", async () => {
246
+ const plain = {
247
+ run: () =>
248
+ Promise.resolve({
249
+ task: { id: "1", status: "succeeded", content: { url: "http://x" } },
250
+ }),
251
+ };
252
+ await expect(generate(plain, minimaxVideo(5), [])).rejects.toMatchObject({
253
+ stage: "normalization",
254
+ });
255
+ const notMp4 = {
256
+ run: () =>
257
+ Promise.resolve({
258
+ task: {
259
+ id: "1",
260
+ status: "succeeded",
261
+ content: { url: "https://x.example/v" },
262
+ },
263
+ }),
264
+ };
265
+ await expect(
266
+ generate(notMp4, minimaxVideo(5), [], undefined, undefined, () =>
267
+ Promise.resolve(new Response(png)),
268
+ ),
269
+ ).rejects.toMatchObject({ stage: "normalization" });
270
+ });
271
+
272
+ it("refuses a non-HTTPS or non-MP4 result", async () => {
273
+ const plain = {
274
+ run: () => Promise.resolve({ result: { video: "http://x.example/v" } }),
275
+ };
276
+
277
+ await expect(generate(plain, video(5), [])).rejects.toMatchObject({
278
+ stage: "normalization",
279
+ });
280
+ const notMp4 = {
281
+ run: () => Promise.resolve({ result: { video: "https://x.example/v" } }),
282
+ };
283
+ await expect(
284
+ generate(notMp4, video(5), [], undefined, undefined, () =>
285
+ Promise.resolve(new Response(png)),
286
+ ),
287
+ ).rejects.toMatchObject({ stage: "normalization" });
288
+ });
289
+
290
+ describe("reference images", () => {
291
+ const withReferences = (count: number) =>
292
+ validateMediaGenerationSettings({
293
+ model: "openai/gpt-image-2",
294
+ prompt: "the same heroine at a bus stop",
295
+ width: 1024,
296
+ height: 1024,
297
+ references: Array.from({ length: count }, (_, index) => ({
298
+ computerId: "pictures",
299
+ path: `/refs/hero-${String(index)}.png`,
300
+ })),
301
+ });
302
+ const bytes = (count: number) =>
303
+ Array.from({ length: count }, () => ({
304
+ bytes: png,
305
+ format: "png" as const,
306
+ width: 1,
307
+ height: 1,
308
+ }));
309
+ const dataUri = `data:image/png;base64,${btoa(String.fromCharCode(...png))}`;
310
+
311
+ it("keeps image sizes and dimension ceilings to what Cloudflare documents", () => {
312
+ // https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-input.json:
313
+ // `size` is auto or WIDTHxHEIGHT, edges at most 3840 and multiples of 16,
314
+ // ratio between 1:3 and 3:1, 655,360 to 8,294,400 pixels (no enum).
315
+ const sizes = getMediaModel("openai/gpt-image-2")?.sizes ?? [];
316
+ expect(sizes).toHaveLength(16);
317
+ for (const size of ["1024x1024", "1024x1536", "1536x1024"])
318
+ expect(sizes).toContain(size);
319
+ for (const size of sizes) {
320
+ const [width = 0, height = 0] = size.split("x").map(Number);
321
+ expect(Math.max(width, height)).toBeLessThanOrEqual(3840);
322
+ expect(width % 16).toBe(0);
323
+ expect(height % 16).toBe(0);
324
+ expect(width / height).toBeGreaterThanOrEqual(1 / 3);
325
+ expect(width / height).toBeLessThanOrEqual(3);
326
+ expect(width * height).toBeGreaterThanOrEqual(655_360);
327
+ expect(width * height).toBeLessThanOrEqual(8_294_400);
328
+ }
329
+ // Every common ratio is there, exactly, at a standard and a largest size.
330
+ const proportions = new Set(
331
+ sizes.map((size) => {
332
+ const [width = 0, height = 0] = size.split("x").map(Number);
333
+ return (width / height).toFixed(4);
334
+ }),
335
+ );
336
+ for (const [across, down] of [
337
+ [1, 1],
338
+ [4, 3],
339
+ [3, 4],
340
+ [3, 2],
341
+ [2, 3],
342
+ [16, 9],
343
+ [9, 16],
344
+ [21, 9],
345
+ ] as const)
346
+ expect(proportions).toContain((across / down).toFixed(4));
347
+ // https://developers.cloudflare.com/workers-ai/models/lucid-origin/ width/height maximum 2500.
348
+ expect(
349
+ getMediaModel("@cf/leonardo/lucid-origin")?.input.maxDimension,
350
+ ).toBe(2500);
351
+ // https://developers.cloudflare.com/workers-ai/models/phoenix-1.0/ width/height range 0 to 2048.
352
+ expect(
353
+ getMediaModel("@cf/leonardo/phoenix-1.0")?.input.maxDimension,
354
+ ).toBe(2048);
355
+ });
356
+
357
+ it("declares each model's own reference limit from its provider docs", () => {
358
+ expect(getMediaModel("openai/gpt-image-2")?.input).toMatchObject({
359
+ maxReferences: 16,
360
+ referenceField: "images",
361
+ });
362
+ expect(getMediaModel("openai/gpt-image-2")?.input).toMatchObject({
363
+ referenceDimension: 1024,
364
+ referenceFormat: "webp",
365
+ });
366
+ expect(
367
+ getMediaModel("@cf/black-forest-labs/flux-2-klein-4b")?.input,
368
+ ).toMatchObject({ referenceDimension: 512, referenceFormat: "png" });
369
+ expect(
370
+ getMediaModel("@cf/black-forest-labs/flux-1-schnell")?.input
371
+ .maxReferences,
372
+ ).toBe(0);
373
+ expect(
374
+ getMediaModel("@cf/black-forest-labs/flux-2-klein-4b")?.input
375
+ .maxReferences,
376
+ ).toBe(4);
377
+ for (const model of listMediaModels())
378
+ expect(model.input.maxReferences > 0).toBe(
379
+ model.input.referenceField !== null,
380
+ );
381
+ });
382
+
383
+ it("builds GPT Image 2's documented images[] data-URI body for N references", () => {
384
+ const input = gatewayInput(withReferences(3), bytes(3));
385
+ expect(input).toEqual({
386
+ prompt: "the same heroine at a bus stop",
387
+ size: "1024x1024",
388
+ quality: "medium",
389
+ output_format: "png",
390
+ images: [dataUri, dataUri, dataUri],
391
+ });
392
+ });
393
+
394
+ it("sends sixteen references and refuses a seventeenth, never truncating", () => {
395
+ const sixteen = gatewayInput(withReferences(16), bytes(16));
396
+ expect(
397
+ z.object({ images: z.array(z.string()) }).parse(sixteen).images,
398
+ ).toHaveLength(16);
399
+ expect(() => withReferences(17)).toThrow(
400
+ "openai/gpt-image-2 accepts at most 16 reference images",
401
+ );
402
+ expect(() =>
403
+ validateMediaGenerationSettings({
404
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
405
+ prompt: "x",
406
+ width: 512,
407
+ height: 512,
408
+ references: Array.from({ length: 5 }, (_, index) => ({
409
+ computerId: "pictures",
410
+ path: `/refs/${String(index)}.png`,
411
+ })),
412
+ }),
413
+ ).toThrow("accepts at most 4 reference images");
414
+ });
415
+
416
+ it("refuses references the model does not take and mismatched bytes", () => {
417
+ expect(() =>
418
+ validateMediaGenerationSettings({
419
+ model: "@cf/black-forest-labs/flux-1-schnell",
420
+ prompt: "x",
421
+ width: 512,
422
+ height: 512,
423
+ references: [{ computerId: "pictures", path: "/a.png" }],
424
+ }),
425
+ ).toThrow("accepts at most 0 reference images");
426
+ expect(() => gatewayInput(withReferences(2), bytes(1))).toThrow(
427
+ "must match every admitted reference",
428
+ );
429
+ expect(() =>
430
+ gatewayInput(withReferences(1), [
431
+ { bytes: png, format: "gif", width: 1, height: 1 },
432
+ ]),
433
+ ).toThrow("not gif");
434
+ });
435
+
436
+ // Image inputs bypass the AI Gateway route (see routedOptions in cloudflare/provider.ts).
437
+ it("dispatches the references on the direct binding with a fake transport", async () => {
438
+ const settings = withReferences(2);
439
+ const run = vi.fn(() =>
440
+ Promise.resolve({
441
+ state: "Completed",
442
+ result: { image: "https://results.example/image" },
443
+ }),
444
+ );
445
+ await generate(
446
+ { run },
447
+ settings,
448
+ bytes(2),
449
+ undefined,
450
+ { gateway: { id: "fungi-hub" } },
451
+ () => Promise.resolve(new Response(png)),
452
+ );
453
+ expect(run).toHaveBeenCalledWith(
454
+ "openai/gpt-image-2",
455
+ expect.objectContaining({ images: [dataUri, dataUri] }),
456
+ {},
457
+ );
458
+ });
459
+
460
+ it("bills each reference at the image input rate with OpenAI's high-fidelity bound", () => {
461
+ const base = estimateGatewayMilliunits(withReferences(0), []);
462
+ // 512 square: 65 + 129 + 4,160 image tokens at $8/M, + 1 text token at $5/M.
463
+ expect(
464
+ estimateGatewayMilliunits(withReferences(1), [
465
+ { width: 512, height: 512 },
466
+ ]),
467
+ ).toBe(Math.ceil((1056 * 30 + 30 * 5 + 1 * 5 + 4354 * 8) / 10));
468
+ // 512 x 384: one tile, non-square adds 6,240.
469
+ expect(
470
+ estimateGatewayMilliunits(withReferences(1), [
471
+ { width: 512, height: 384 },
472
+ ]),
473
+ ).toBe(Math.ceil((1056 * 30 + 30 * 5 + 1 * 5 + 6434 * 8) / 10));
474
+ // 2048 x 1024 scales to 1024 x 512: two tiles.
475
+ expect(
476
+ estimateGatewayMilliunits(withReferences(1), [
477
+ { width: 2048, height: 1024 },
478
+ ]),
479
+ ).toBe(Math.ceil((1056 * 30 + 30 * 5 + 1 * 5 + 6563 * 8) / 10));
480
+ // 1024 x 1024 (a fitted GPT Image 2 reference) caps the short side at
481
+ // 512: one tile, the same bill as 512 square.
482
+ expect(
483
+ estimateGatewayMilliunits(withReferences(1), [
484
+ { width: 1024, height: 1024 },
485
+ ]),
486
+ ).toBe(Math.ceil((1056 * 30 + 30 * 5 + 1 * 5 + 4354 * 8) / 10));
487
+ // 1024 x 768 scales to 683 x 512: two tiles across, one down.
488
+ expect(
489
+ estimateGatewayMilliunits(withReferences(1), [
490
+ { width: 1024, height: 768 },
491
+ ]),
492
+ ).toBe(Math.ceil((1056 * 30 + 30 * 5 + 1 * 5 + 6563 * 8) / 10));
493
+ expect(base).toBe(Math.ceil((1056 * 30 + 30 * 5) / 10));
494
+ expect(() => estimateGatewayMilliunits(withReferences(2), [])).toThrow(
495
+ "must match every admitted reference",
496
+ );
497
+ });
498
+ });
499
+ });
500
+
501
+ describe("GPT Image 2 sizes", () => {
502
+ const sized = (size: string) => {
503
+ const [width, height] = size.split("x").map(Number);
504
+ return validateMediaGenerationSettings({
505
+ model: "openai/gpt-image-2",
506
+ prompt: "a seed catalogue cover",
507
+ width: width ?? 0,
508
+ height: height ?? 0,
509
+ });
510
+ };
511
+
512
+ it("sends each catalog size as the provider's WIDTHxHEIGHT", () => {
513
+ for (const size of getMediaModel("openai/gpt-image-2")?.sizes ?? [])
514
+ expect(gatewayInput(sized(size))).toMatchObject({ size });
515
+ expect(() => sized("1000x1000")).toThrow("accepts only these sizes");
516
+ });
517
+
518
+ it("quotes the table's sizes exactly and others by their pixels", () => {
519
+ // 22 prompt characters at $5/M, bounded as one token each.
520
+ const per = (size: string) => estimateGatewayMilliunits(sized(size), []);
521
+ const expected = (tokens: number) => Math.ceil((tokens * 30 + 22 * 5) / 10);
522
+ expect(per("1024x1024")).toBe(expected(1056));
523
+ expect(per("1536x1024")).toBe(expected(1568));
524
+ // 16:9 at 3840x2160 is 8,294,400 pixels: 8,354 tokens at $30/M.
525
+ expect(per("3840x2160")).toBe(expected(8_354));
526
+ expect(per("1280x720")).toBe(expected(929));
527
+ expect(per("3840x2160")).toBeGreaterThan(per("1280x720"));
528
+ });
529
+ });
530
+
531
+ describe("Seedream 5 Pro", () => {
532
+ const id = "bytedance/seedream-5-pro";
533
+ const sized = (size: string, prompt = "a mushroom knight") => {
534
+ const [width, height] = size.split("x").map(Number);
535
+ return validateMediaGenerationSettings({
536
+ model: id,
537
+ prompt,
538
+ width: width ?? 0,
539
+ height: height ?? 0,
540
+ });
541
+ };
542
+
543
+ it("lists the common ratios as exact sizes, with the documented example among them", () => {
544
+ // https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/
545
+ const model = getMediaModel(id);
546
+ expect(model?.kind).toBe("image");
547
+ expect(model?.sizes).toContain("1536x864");
548
+ expect(model?.sizes).toHaveLength(8);
549
+ expect(model?.input).toMatchObject({
550
+ maxReferences: 0,
551
+ referenceField: null,
552
+ });
553
+ for (const size of model?.sizes ?? []) {
554
+ const [width = 0, height = 0] = size.split("x").map(Number);
555
+ expect(width % 16).toBe(0);
556
+ expect(height % 16).toBe(0);
557
+ expect(Math.max(width, height)).toBeLessThanOrEqual(
558
+ model?.input.maxDimension ?? 0,
559
+ );
560
+ expect(sized(size).width).toBe(width);
561
+ }
562
+ });
563
+
564
+ it("refuses a size it does not list, a long prompt and any reference", () => {
565
+ expect(() => sized("1000x1000")).toThrow("accepts only these sizes");
566
+ expect(() => sized("1536x864", "x".repeat(2049))).toThrow(
567
+ "its limit is 2048",
568
+ );
569
+ expect(() =>
570
+ validateMediaGenerationSettings({
571
+ model: id,
572
+ prompt: "x",
573
+ width: 1536,
574
+ height: 864,
575
+ references: [{ computerId: "pictures", path: "/a.png" }],
576
+ }),
577
+ ).toThrow("accepts at most 0 reference images");
578
+ });
579
+
580
+ it("sends only the documented fields", () => {
581
+ expect(gatewayInput(sized("1536x864"))).toEqual({
582
+ prompt: "a mushroom knight",
583
+ size: "1536x864",
584
+ watermark: false,
585
+ });
586
+ });
587
+
588
+ it("bills the published $0.045 per image, whatever the size", () => {
589
+ expect(mediaUnits(sized("1536x864"))).toEqual({ unit: "image", units: 1 });
590
+ for (const size of getMediaModel(id)?.sizes ?? [])
591
+ expect(estimateGatewayMilliunits(sized(size), [])).toBe(4_500);
592
+ });
593
+
594
+ it("reads its list of result URLs through the gateway route", async () => {
595
+ const run = vi.fn(() =>
596
+ Promise.resolve({
597
+ state: "Completed",
598
+ result: { images: ["https://results.example/image.jpeg"] },
599
+ }),
600
+ );
601
+ const fetchResult = vi.fn<typeof fetch>(() =>
602
+ Promise.resolve(new Response(png)),
603
+ );
604
+ await expect(
605
+ generate(
606
+ { run },
607
+ sized("1536x864"),
608
+ [],
609
+ undefined,
610
+ undefined,
611
+ fetchResult,
612
+ ),
613
+ ).resolves.toMatchObject({ format: "png" });
614
+ expect(fetchResult).toHaveBeenCalledWith(
615
+ "https://results.example/image.jpeg",
616
+ expect.anything(),
617
+ );
618
+ expect(run).toHaveBeenCalledWith(
619
+ id,
620
+ { prompt: "a mushroom knight", size: "1536x864", watermark: false },
621
+ undefined,
622
+ );
623
+ });
624
+ });
625
+
626
+ describe("Seedance 2.5", () => {
627
+ const id = "bytedance/seedance-2.5";
628
+ const clip = (
629
+ durationSeconds: number,
630
+ size = "1280x720",
631
+ extra: Partial<Parameters<typeof validateMediaGenerationSettings>[0]> = {},
632
+ ) => {
633
+ const [width, height] = size.split("x").map(Number);
634
+ return validateMediaGenerationSettings({
635
+ model: id,
636
+ prompt: "fern fronds unfurling",
637
+ width: width ?? 0,
638
+ height: height ?? 0,
639
+ durationSeconds,
640
+ ...extra,
641
+ });
642
+ };
643
+
644
+ it("lists the plain name and the documented bounds", () => {
645
+ const model = getMediaModel(id);
646
+ expect(model?.label).toBe("Seedance 2.5");
647
+ expect(model?.maxPromptLength).toBe(25_000);
648
+ expect(model?.video).toMatchObject({
649
+ minSeconds: 4,
650
+ maxSeconds: 30,
651
+ defaultSeconds: 5,
652
+ provider: "seedance",
653
+ supportsAudio: true,
654
+ maxReferenceImages: 30,
655
+ });
656
+ expect(model?.video?.durations).toHaveLength(27);
657
+ const formats = model?.video?.formats ?? [];
658
+ expect(new Set(formats.map((format) => format.resolution))).toEqual(
659
+ new Set(["480p", "720p"]),
660
+ );
661
+ expect(formats.map((format) => format.aspectRatio)).not.toContain("9:21");
662
+ // Seedance 2.0 models stay listed.
663
+ for (const kept of ["", "-fast", "-mini"])
664
+ expect(getMediaModel(`bytedance/seedance-2.0${kept}`)).toBeDefined();
665
+ });
666
+
667
+ it("accepts 4 to 30 seconds and refuses the rest", () => {
668
+ expect(clip(30).durationSeconds).toBe(30);
669
+ expect(() => clip(3)).toThrow("durationSeconds");
670
+ expect(() => clip(31)).toThrow("durationSeconds");
671
+ expect(() => clip(5, "1000x720")).toThrow("accepts only these sizes");
672
+ });
673
+
674
+ it("builds the documented request body without inventing fields", () => {
675
+ expect(gatewayInput(clip(30, "720x1280", { generateAudio: true }))).toEqual(
676
+ {
677
+ prompt: "fern fronds unfurling",
678
+ duration: 30,
679
+ resolution: "720p",
680
+ aspect_ratio: "9:16",
681
+ generate_audio: true,
682
+ },
683
+ );
684
+ const framed = z
685
+ .object({ image: z.string(), last_frame_image: z.string() })
686
+ .parse(
687
+ gatewayInput(
688
+ clip(8, "1280x720", {
689
+ references: [
690
+ { computerId: "pictures", path: "a.png", role: "first-frame" },
691
+ { computerId: "pictures", path: "b.png", role: "last-frame" },
692
+ ],
693
+ }),
694
+ [
695
+ { bytes: png, format: "png", width: 1, height: 1 },
696
+ { bytes: png, format: "png", width: 1, height: 1 },
697
+ ],
698
+ ),
699
+ );
700
+ expect(framed.image.startsWith("data:image/png;base64,")).toBe(true);
701
+ expect(framed.last_frame_image.startsWith("data:image/png;base64,")).toBe(
702
+ true,
703
+ );
704
+ });
705
+
706
+ it("quotes a 5 second 720p clip at the dashboard rate", () => {
707
+ // $0.2312/s at 720p (non-video input), 1 USD = 100,000 milliunits.
708
+ expect(estimateGatewayMilliunits(clip(5), [])).toBe(115_600);
709
+ // $0.1028/s at 480p.
710
+ expect(estimateGatewayMilliunits(clip(5, "854x480"), [])).toBe(51_400);
711
+ });
712
+ });