@fungi.computer/darkroom 0.11.11 → 0.11.12

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 +7 -1
  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,133 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
3
+ import { MediaExecutionError } from "../src/execution-error.js";
4
+ import { validateMediaGenerationSettings } from "../src/index.js";
5
+
6
+ afterEach(() => vi.restoreAllMocks());
7
+
8
+ const settings = validateMediaGenerationSettings({
9
+ model: "bytedance/seedance-2.0-mini",
10
+ prompt: "a mushroom knight waves",
11
+ width: 854,
12
+ height: 480,
13
+ durationSeconds: 4,
14
+ });
15
+
16
+ function failed(name: string, message: string) {
17
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
18
+ const error = new Error(message);
19
+ error.name = name;
20
+ const run = vi.fn<MediaAiPort["run"]>().mockRejectedValue(error);
21
+ return generate({ run }, settings, []).then(
22
+ () => {
23
+ throw new Error("expected a provider failure");
24
+ },
25
+ (cause: unknown) => {
26
+ if (!(cause instanceof MediaExecutionError)) throw cause;
27
+ return cause;
28
+ },
29
+ );
30
+ }
31
+
32
+ // Messages are the documented wording:
33
+ // https://developers.cloudflare.com/workers-ai/platform/errors/
34
+ // https://developers.cloudflare.com/ai-gateway/reference/troubleshooting/
35
+ it.each([
36
+ [
37
+ "AiGatewayError",
38
+ "7003: Model execution failed (User Input Error): image dimensions are too small",
39
+ {
40
+ code: 7003,
41
+ reason: "invalid_input",
42
+ detail: "image dimensions are too small",
43
+ },
44
+ ],
45
+ [
46
+ "AiGatewayError",
47
+ "7003: User Input Error",
48
+ { code: 7003, reason: "invalid_input", detail: "User Input Error" },
49
+ ],
50
+ [
51
+ "Error",
52
+ "3006: Request is too large",
53
+ { code: 3006, reason: "invalid_input" },
54
+ ],
55
+ [
56
+ "Error",
57
+ "3040: Capacity temporarily exceeded, please try again.",
58
+ { code: 3040, reason: "rate_limited" },
59
+ ],
60
+ [
61
+ "AiGatewayError",
62
+ "2018: Unified billing rate limit exceeded for this gateway. Please reduce request rate or use BYOK.",
63
+ { code: 2018, reason: "rate_limited" },
64
+ ],
65
+ ["Error", "3007: Request timeout", { code: 3007, reason: "timeout" }],
66
+ [
67
+ "TimeoutError",
68
+ "The operation timed out",
69
+ { code: null, reason: "timeout" },
70
+ ],
71
+ [
72
+ "Error",
73
+ "3036: You have used up your daily free allocation of 10,000 neurons.",
74
+ { code: 3036, reason: "spending_limit" },
75
+ ],
76
+ [
77
+ "AiGatewayError",
78
+ "2052: Insufficient unified billing balance for this request. Your available balance is $0.01.",
79
+ { code: 2052, reason: "credits_exhausted" },
80
+ ],
81
+ [
82
+ "AiGatewayError",
83
+ "2021: Insufficient AI Gateway credits",
84
+ { code: 2021, reason: "credits_exhausted" },
85
+ ],
86
+ [
87
+ "AiGatewayError",
88
+ "7005: Unified billing is temporarily unavailable for this provider; retry, or configure your own provider API key (BYOK).",
89
+ { code: 7005, reason: "provider_unavailable" },
90
+ ],
91
+ [
92
+ "AiGatewayError",
93
+ "2002: Model execution failed (Error)",
94
+ { code: 2002, reason: "provider_unavailable" },
95
+ ],
96
+ [
97
+ "AiGatewayError",
98
+ "2005: Failed to get response from provider",
99
+ { code: 2005, reason: "provider_unavailable" },
100
+ ],
101
+ [
102
+ "Error",
103
+ "3030: AiError: AiError: Your output has been flagged. Please choose another prompt / input image combination (5dbf4c51-d344-437d-b202-7bdd4310a043)",
104
+ { code: 3030, reason: "content_refused" },
105
+ ],
106
+ [
107
+ "AiGatewayError",
108
+ "7003: Model execution failed (User Input Error): The input image may violate our policies, so it might violate our policies",
109
+ { code: 7003, reason: "content_refused" },
110
+ ],
111
+ ] as const)("classifies %s %j", async (name, message, expected) => {
112
+ const cause = await failed(name, message);
113
+ expect(cause).toMatchObject({ stage: "provider", provider: expected });
114
+ });
115
+
116
+ it("keeps a short plain provider sentence for an unclassified error", async () => {
117
+ const cause = await failed("Error", "3999: The frame rate is not supported");
118
+ expect(cause).toMatchObject({
119
+ provider: { code: 3999, detail: "The frame rate is not supported" },
120
+ });
121
+ });
122
+
123
+ it.each([
124
+ `3999: {"error":{"message":"bad"}}`,
125
+ "3999: Bearer abcdefghijklmnopqrstuvwxyz0123456789",
126
+ "3999: key sk-live-abcdefghijklmnopqrstuvwxyz",
127
+ `3999: ${"x".repeat(200)}`,
128
+ "3999: see https://example.com/a",
129
+ ])("never keeps unsafe provider text %#", async (message) => {
130
+ const cause = await failed("Error", message);
131
+ expect(cause).toMatchObject({ provider: { code: 3999 } });
132
+ expect(JSON.stringify(cause.provider)).not.toContain("detail");
133
+ });
@@ -0,0 +1,166 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ MAX_AUDIO_REFERENCE_BYTES,
4
+ MAX_REFERENCE_BYTES,
5
+ MediaSettingsError,
6
+ type ReferenceImageFitter,
7
+ } from "../src/index.js";
8
+ import { mediaWrittenDigest } from "../src/media-written.js";
9
+ import {
10
+ createR2MediaDestination,
11
+ type MediaR2Bucket,
12
+ } from "../src/cloudflare/r2-destination.js";
13
+
14
+ const png = Uint8Array.from([
15
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1,
16
+ ]);
17
+
18
+ function fixture(authorize?: (key: string) => Promise<void> | void) {
19
+ const objects = new Map<string, { bytes: Uint8Array; size: number }>();
20
+ const put = vi.fn((key: string, bytes: Uint8Array) => {
21
+ objects.set(key, { bytes, size: bytes.byteLength });
22
+ return Promise.resolve(null);
23
+ });
24
+ const bucket: MediaR2Bucket = {
25
+ get: (key) => {
26
+ const object = objects.get(key);
27
+ return Promise.resolve(
28
+ object === undefined
29
+ ? null
30
+ : {
31
+ size: object.size,
32
+ arrayBuffer: () => Promise.resolve(object.bytes.slice().buffer),
33
+ },
34
+ );
35
+ },
36
+ put,
37
+ delete: (key) => {
38
+ objects.delete(key);
39
+ return Promise.resolve();
40
+ },
41
+ };
42
+ const fit = vi.fn<ReferenceImageFitter>((bytes) =>
43
+ Promise.resolve({ bytes, format: "png", width: 1, height: 1 }),
44
+ );
45
+ const destination = createR2MediaDestination({
46
+ bucket,
47
+ destinationId: "bucket-a",
48
+ fit,
49
+ authorize,
50
+ });
51
+ return { objects, put, fit, destination };
52
+ }
53
+ const reference = { computerId: "bucket-a", path: "refs/cat.png" };
54
+
55
+ describe("createR2MediaDestination", () => {
56
+ it("fits a stored reference and names it after the key", async () => {
57
+ const { objects, fit, destination } = fixture();
58
+ objects.set("refs/cat.png", { bytes: png, size: png.byteLength });
59
+ await expect(
60
+ destination.readReference(reference, "model-a"),
61
+ ).resolves.toEqual({
62
+ bytes: png,
63
+ format: "png",
64
+ width: 1,
65
+ height: 1,
66
+ filename: "cat.png",
67
+ });
68
+ expect(fit).toHaveBeenCalledExactlyOnceWith(png, "model-a");
69
+ });
70
+
71
+ it("refuses another destination, a missing key, an empty object and an oversized one", async () => {
72
+ const { objects, fit, destination } = fixture();
73
+ objects.set("refs/empty.png", { bytes: new Uint8Array(), size: 0 });
74
+ // Size is checked from object metadata, so the oversized body is never loaded.
75
+ objects.set("refs/big.png", {
76
+ bytes: png,
77
+ size: MAX_AUDIO_REFERENCE_BYTES + 1,
78
+ });
79
+ const refused = [
80
+ { ...reference, computerId: "bucket-b" },
81
+ { ...reference, path: "refs/absent.png" },
82
+ { ...reference, path: "refs/empty.png" },
83
+ { ...reference, path: "refs/big.png" },
84
+ ];
85
+ for (const item of refused) {
86
+ await expect(destination.readReference(item, "model-a")).rejects.toThrow(
87
+ MediaSettingsError,
88
+ );
89
+ await expect(destination.readAudioReference(item)).rejects.toThrow(
90
+ MediaSettingsError,
91
+ );
92
+ }
93
+ expect(fit).not.toHaveBeenCalled();
94
+ });
95
+
96
+ it("refuses an image just over the image limit but not an audio clip", async () => {
97
+ const { objects, fit, destination } = fixture();
98
+ objects.set("refs/mid", { bytes: png, size: MAX_REFERENCE_BYTES + 1 });
99
+ const mid = { ...reference, path: "refs/mid" };
100
+ await expect(destination.readReference(mid, "model-a")).rejects.toThrow(
101
+ MediaSettingsError,
102
+ );
103
+ await expect(destination.readAudioReference(mid)).resolves.toEqual(png);
104
+ expect(fit).not.toHaveBeenCalled();
105
+ });
106
+
107
+ it("reads audio bytes without fitting", async () => {
108
+ const { objects, fit, destination } = fixture();
109
+ objects.set("refs/clip.mp3", { bytes: png, size: png.byteLength });
110
+ await expect(
111
+ destination.readAudioReference({ ...reference, path: "refs/clip.mp3" }),
112
+ ).resolves.toEqual(png);
113
+ expect(fit).not.toHaveBeenCalled();
114
+ });
115
+
116
+ it("writes the exact bytes with a content type from the bytes", async () => {
117
+ const { put, destination } = fixture();
118
+ await destination.write("out/a.png", png);
119
+ expect(put).toHaveBeenCalledExactlyOnceWith("out/a.png", png, {
120
+ httpMetadata: { contentType: "image/png" },
121
+ });
122
+ });
123
+
124
+ it("refuses URLs-as-keys that are not valid paths and runs the host check first", async () => {
125
+ const authorize = vi.fn((key: string) => {
126
+ if (key.startsWith("private/")) throw new Error("denied");
127
+ });
128
+ const { put, destination } = fixture(authorize);
129
+ await expect(destination.authorize("")).rejects.toThrow(MediaSettingsError);
130
+ await expect(destination.authorize("a\0b")).rejects.toThrow(
131
+ MediaSettingsError,
132
+ );
133
+ await expect(destination.authorize("out/ok.png")).resolves.toBeUndefined();
134
+ await expect(destination.write("private/x.png", png)).rejects.toThrow(
135
+ "denied",
136
+ );
137
+ await expect(
138
+ destination.readReference(
139
+ { ...reference, path: "private/x.png" },
140
+ "model-a",
141
+ ),
142
+ ).rejects.toThrow("denied");
143
+ expect(put).not.toHaveBeenCalled();
144
+ expect(authorize).toHaveBeenCalledWith("out/ok.png");
145
+ });
146
+ });
147
+
148
+ describe("createR2MediaDestination remove", () => {
149
+ it("authorizes the key, then deletes only an object that still holds what was written", async () => {
150
+ const authorize = vi.fn();
151
+ const { objects, destination } = fixture(authorize);
152
+ objects.set("out/a.png", { bytes: png, size: png.byteLength });
153
+ objects.set("out/b.png", { bytes: png, size: png.byteLength });
154
+ const sha256 = await mediaWrittenDigest(png);
155
+ expect(await destination.remove("out/a.png", { sha256 })).toBe("removed");
156
+ expect(authorize).toHaveBeenCalledWith("out/a.png");
157
+ expect([...objects.keys()]).toEqual(["out/b.png"]);
158
+ expect(await destination.remove("out/a.png", { sha256 })).toBe("absent");
159
+ objects.set("out/b.png", { bytes: new Uint8Array([1]), size: 1 });
160
+ expect(await destination.remove("out/b.png", { sha256 })).toBe("not-ours");
161
+ expect([...objects.keys()]).toEqual(["out/b.png"]);
162
+ await expect(destination.remove("bad\0key", { sha256 })).rejects.toThrow(
163
+ MediaSettingsError,
164
+ );
165
+ });
166
+ });
@@ -0,0 +1,73 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ referenceImageSizeIsValid,
4
+ referenceImageTransform,
5
+ } from "../src/reference-image-size.js";
6
+
7
+ describe("model-specific reference image sizing", () => {
8
+ it.each([
9
+ {
10
+ model: "bytedance/seedance-2.0",
11
+ width: 1774,
12
+ height: 887,
13
+ expected: { width: 640, height: 320, fit: "contain" },
14
+ },
15
+ {
16
+ model: "bytedance/seedance-2.0",
17
+ width: 887,
18
+ height: 1774,
19
+ expected: { width: 320, height: 640, fit: "contain" },
20
+ },
21
+ {
22
+ model: "openai/gpt-image-2",
23
+ width: 2048,
24
+ height: 1024,
25
+ expected: { width: 1024, height: 512, fit: "scale-down" },
26
+ },
27
+ {
28
+ model: "openai/gpt-image-2",
29
+ width: 800,
30
+ height: 600,
31
+ expected: { width: 800, height: 600, fit: "scale-down" },
32
+ },
33
+ {
34
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
35
+ width: 1774,
36
+ height: 887,
37
+ expected: { width: 512, height: 256, fit: "scale-down" },
38
+ },
39
+ {
40
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
41
+ width: 887,
42
+ height: 1774,
43
+ expected: { width: 256, height: 512, fit: "scale-down" },
44
+ },
45
+ ])(
46
+ "fits $model $width×$height to its model-specific reference dimensions",
47
+ ({ model, width, height, expected }) => {
48
+ expect(referenceImageTransform(model, width, height)).toEqual(expected);
49
+ },
50
+ );
51
+
52
+ it("accepts 1024 px GPT Image 2 references and refuses 1025 px or 513 px elsewhere", () => {
53
+ expect(referenceImageSizeIsValid("openai/gpt-image-2", 1024, 768)).toBe(
54
+ true,
55
+ );
56
+ expect(referenceImageSizeIsValid("openai/gpt-image-2", 1025, 768)).toBe(
57
+ false,
58
+ );
59
+ expect(
60
+ referenceImageSizeIsValid(
61
+ "@cf/black-forest-labs/flux-2-klein-4b",
62
+ 513,
63
+ 1,
64
+ ),
65
+ ).toBe(false);
66
+ });
67
+
68
+ it("refuses a 512×256 video reference even though it fits the image long-edge cap", () => {
69
+ expect(referenceImageSizeIsValid("bytedance/seedance-2.0", 512, 256)).toBe(
70
+ false,
71
+ );
72
+ });
73
+ });
@@ -0,0 +1,40 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ createImagesReferenceFitter,
4
+ createImagesViewFitter,
5
+ imagesLegacyBillingMessage,
6
+ type MediaImagePort,
7
+ } from "../src/cloudflare/reference-images.js";
8
+
9
+ const legacy = Object.assign(
10
+ new Error(
11
+ "IMAGES_TRANSFORM_ERROR 9432: Images transforms are not available using legacy billing",
12
+ ),
13
+ { code: 9432 },
14
+ );
15
+ const refusing: MediaImagePort = {
16
+ info: () => Promise.reject(legacy),
17
+ input: () => {
18
+ throw legacy;
19
+ },
20
+ };
21
+ const model = "@cf/black-forest-labs/flux-2-klein-4b";
22
+
23
+ it("explains Cloudflare error 9432 instead of calling the reference unsupported", async () => {
24
+ await expect(
25
+ createImagesReferenceFitter(refusing)(new Uint8Array([1]), model),
26
+ ).rejects.toThrow(imagesLegacyBillingMessage);
27
+ await expect(
28
+ createImagesViewFitter(refusing)(new Uint8Array([1]), 512),
29
+ ).rejects.toThrow(imagesLegacyBillingMessage);
30
+ });
31
+
32
+ it("still calls undecodable bytes an unsupported image", async () => {
33
+ const broken: MediaImagePort = {
34
+ ...refusing,
35
+ info: () => Promise.reject(new Error("could not decode")),
36
+ };
37
+ await expect(
38
+ createImagesReferenceFitter(broken)(new Uint8Array([1]), model),
39
+ ).rejects.toThrow("reference image is not a supported image");
40
+ });