@skyphusion/create-prism 0.1.0

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 (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,184 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { parseDiscordExport, chunkDiscordMessages } from "../src/discord";
3
+
4
+ // Synthetic DCE-shaped fixture covering the cases most likely to break a
5
+ // naive parser: multi-author bursts, a >15-min gap that should split a unit,
6
+ // an empty-content attachment-only message, a reply, a bot message, a system
7
+ // message (join) that should be skipped, a custom emoji in content, and a
8
+ // migrated username (discriminator "0", no nickname).
9
+ function makeExport() {
10
+ return {
11
+ guild: { id: "1", name: "MUDD" },
12
+ channel: { id: "10", type: "GuildTextChat", category: "world", name: "lore-discussion", topic: "worldbuilding" },
13
+ dateRange: { after: null, before: null },
14
+ exportedAt: "2024-01-15T13:00:00.000Z",
15
+ messages: [
16
+ {
17
+ id: "100", type: "GuildMemberJoin", timestamp: "2024-01-15T11:59:00.000Z",
18
+ content: "", author: { id: "a", name: "alice", discriminator: "0", nickname: null, isBot: false },
19
+ },
20
+ {
21
+ id: "101", type: "Default", timestamp: "2024-01-15T12:00:00.000Z",
22
+ content: "what's at the bottom of the shaft?",
23
+ author: { id: "a", name: "alice", discriminator: "0", nickname: "Alice", isBot: false },
24
+ },
25
+ {
26
+ id: "102", type: "Default", timestamp: "2024-01-15T12:01:00.000Z",
27
+ content: "an old transit hub, mostly flooded :map:",
28
+ author: { id: "b", name: "bob_the_dm", discriminator: "0", nickname: null, isBot: false },
29
+ },
30
+ {
31
+ id: "103", type: "Reply", timestamp: "2024-01-15T12:02:00.000Z",
32
+ content: "can we drain it?",
33
+ author: { id: "a", name: "alice", discriminator: "0", nickname: "Alice", isBot: false },
34
+ reference: { messageId: "102", channelId: "10", guildId: "1" },
35
+ },
36
+ {
37
+ id: "104", type: "Default", timestamp: "2024-01-15T12:02:30.000Z",
38
+ content: "", // attachment-only, no text -> dropped
39
+ author: { id: "a", name: "alice", discriminator: "0", nickname: "Alice", isBot: false },
40
+ attachments: [{ id: "x", url: "https://cdn/map.png", fileName: "map.png", fileSizeBytes: 1234 }],
41
+ },
42
+ {
43
+ id: "105", type: "Default", timestamp: "2024-01-15T12:03:00.000Z",
44
+ content: "Rolling for flood depth: 14",
45
+ author: { id: "z", name: "DiceBot", discriminator: "0000", nickname: null, isBot: true },
46
+ },
47
+ // >15 min gap -> new conversation unit
48
+ {
49
+ id: "106", type: "Default", timestamp: "2024-01-15T12:45:00.000Z",
50
+ content: "back. so the hub connects to the old rail line",
51
+ author: { id: "b", name: "bob_the_dm", discriminator: "0", nickname: null, isBot: false },
52
+ },
53
+ ],
54
+ messageCount: 7,
55
+ };
56
+ }
57
+
58
+ describe("parseDiscordExport", () => {
59
+ it("parses channel name with category", () => {
60
+ const parsed = parseDiscordExport(makeExport());
61
+ expect(parsed.channel).toBe("world / lore-discussion");
62
+ expect(parsed.guild).toBe("MUDD");
63
+ });
64
+
65
+ it("skips system messages and empty-content messages", () => {
66
+ const parsed = parseDiscordExport(makeExport());
67
+ // 7 raw, minus the join (system) and the attachment-only empty message = 5
68
+ expect(parsed.rawCount).toBe(7);
69
+ expect(parsed.parsedCount).toBe(5);
70
+ expect(parsed.messages.map((m) => m.messageId)).toEqual(["101", "102", "103", "105", "106"]);
71
+ });
72
+
73
+ it("uses nickname when present, else name", () => {
74
+ const parsed = parseDiscordExport(makeExport());
75
+ const byId = Object.fromEntries(parsed.messages.map((m) => [m.messageId, m]));
76
+ expect(byId["101"].author).toBe("Alice"); // nickname
77
+ expect(byId["102"].author).toBe("bob_the_dm"); // no nickname -> name
78
+ });
79
+
80
+ it("marks bot messages", () => {
81
+ const parsed = parseDiscordExport(makeExport());
82
+ const bot = parsed.messages.find((m) => m.messageId === "105");
83
+ expect(bot?.isBot).toBe(true);
84
+ });
85
+
86
+ it("keeps reply messages as normal content", () => {
87
+ const parsed = parseDiscordExport(makeExport());
88
+ const reply = parsed.messages.find((m) => m.messageId === "103");
89
+ expect(reply?.content).toBe("can we drain it?");
90
+ });
91
+
92
+ it("throws on non-object input", () => {
93
+ expect(() => parseDiscordExport(null)).toThrow(/not a JSON object/);
94
+ expect(() => parseDiscordExport("nope")).toThrow(/not a JSON object/);
95
+ });
96
+
97
+ it("throws on missing messages array with a diagnostic message", () => {
98
+ expect(() => parseDiscordExport({ guild: { name: "x" } })).toThrow(/missing 'messages' array/);
99
+ });
100
+
101
+ it("handles a channel with no category", () => {
102
+ const exp = makeExport();
103
+ exp.channel = { id: "10", type: "GuildTextChat", category: "", name: "general", topic: "" } as never;
104
+ expect(parseDiscordExport(exp).channel).toBe("general");
105
+ });
106
+ });
107
+
108
+ describe("chunkDiscordMessages", () => {
109
+ it("groups within-gap same-channel messages into one chunk", () => {
110
+ const parsed = parseDiscordExport(makeExport());
111
+ const chunks = chunkDiscordMessages(parsed.messages);
112
+ // First unit: 101,102,103,105 (all within 15 min). Second unit: 106.
113
+ expect(chunks.length).toBe(2);
114
+ expect(chunks[0].messageIds).toEqual(["101", "102", "103", "105"]);
115
+ expect(chunks[1].messageIds).toEqual(["106"]);
116
+ });
117
+
118
+ it("includes a channel header and author:timestamp lines", () => {
119
+ const parsed = parseDiscordExport(makeExport());
120
+ const chunks = chunkDiscordMessages(parsed.messages);
121
+ expect(chunks[0].text).toContain("[#world / lore-discussion]");
122
+ expect(chunks[0].text).toContain("Alice (2024-01-15 12:00): what's at the bottom of the shaft?");
123
+ expect(chunks[0].text).toContain("bob_the_dm (2024-01-15 12:01): an old transit hub");
124
+ });
125
+
126
+ it("records distinct authors in first-seen order", () => {
127
+ const parsed = parseDiscordExport(makeExport());
128
+ const chunks = chunkDiscordMessages(parsed.messages);
129
+ expect(chunks[0].authors).toEqual(["Alice", "bob_the_dm", "DiceBot"]);
130
+ });
131
+
132
+ it("records the time range of the chunk", () => {
133
+ const parsed = parseDiscordExport(makeExport());
134
+ const chunks = chunkDiscordMessages(parsed.messages);
135
+ expect(chunks[0].sentAtStart).toBe("2024-01-15T12:00:00.000Z");
136
+ expect(chunks[0].sentAtEnd).toBe("2024-01-15T12:03:00.000Z");
137
+ });
138
+
139
+ it("excludes bot messages when includeBots is false", () => {
140
+ const parsed = parseDiscordExport(makeExport());
141
+ const chunks = chunkDiscordMessages(parsed.messages, { includeBots: false });
142
+ const allIds = chunks.flatMap((c) => c.messageIds);
143
+ expect(allIds).not.toContain("105"); // DiceBot
144
+ expect(allIds).toContain("101");
145
+ });
146
+
147
+ it("splits a unit when the gap exceeds the configured threshold", () => {
148
+ const parsed = parseDiscordExport(makeExport());
149
+ // Messages 101,102,103,105 are each 1 min apart; 106 is 42 min later.
150
+ // With the default 15-min threshold they form 2 units. With a sub-minute
151
+ // threshold (0.5 min = 30s), every 1-min gap splits, so each message
152
+ // becomes its own unit: 5 messages -> 5 chunks.
153
+ const chunks = chunkDiscordMessages(parsed.messages, { gapMinutes: 0.5 });
154
+ expect(chunks.length).toBe(5);
155
+ });
156
+
157
+ it("never merges across channels", () => {
158
+ const msgs = [
159
+ { messageId: "1", channel: "a", author: "X", authorId: "1", isBot: false, sentAt: "2024-01-15T12:00:00.000Z", content: "hi" },
160
+ { messageId: "2", channel: "b", author: "X", authorId: "1", isBot: false, sentAt: "2024-01-15T12:00:30.000Z", content: "yo" },
161
+ ];
162
+ const chunks = chunkDiscordMessages(msgs);
163
+ expect(chunks.length).toBe(2);
164
+ expect(chunks[0].channel).toBe("a");
165
+ expect(chunks[1].channel).toBe("b");
166
+ });
167
+
168
+ it("splits an oversized single message, repeating the header", () => {
169
+ const long = "word ".repeat(500).trim(); // ~2500 chars
170
+ const msgs = [
171
+ { messageId: "1", channel: "c", author: "X", authorId: "1", isBot: false, sentAt: "2024-01-15T12:00:00.000Z", content: long },
172
+ ];
173
+ const chunks = chunkDiscordMessages(msgs, { targetChars: 500 });
174
+ expect(chunks.length).toBeGreaterThan(1);
175
+ for (const c of chunks) {
176
+ expect(c.text.startsWith("[#c]")).toBe(true);
177
+ expect(c.text.length).toBeLessThanOrEqual(560); // target + header + prefix slack
178
+ }
179
+ });
180
+
181
+ it("returns empty array for empty input", () => {
182
+ expect(chunkDiscordMessages([])).toEqual([]);
183
+ });
184
+ });
@@ -0,0 +1,65 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ gatewaySource,
4
+ maskSecret,
5
+ resolveGatewayFromParts,
6
+ } from "../src/gateway-credentials";
7
+ import type { Env } from "../src/env";
8
+
9
+ function env(partial: Partial<Env> = {}): Env {
10
+ return partial as Env;
11
+ }
12
+
13
+ describe("resolveGatewayFromParts", () => {
14
+ it("returns null when no gateway id is available", () => {
15
+ expect(resolveGatewayFromParts(null, env())).toBeNull();
16
+ expect(resolveGatewayFromParts({ gateway_id: " " }, env())).toBeNull();
17
+ });
18
+
19
+ it("merges user prefs over worker secrets field-by-field", () => {
20
+ const resolved = resolveGatewayFromParts(
21
+ { gateway_id: "user-gw", cf_aig_token: "user-token" },
22
+ env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
23
+ );
24
+ expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "user-token" });
25
+ });
26
+
27
+ it("falls back to worker secrets for unset user fields", () => {
28
+ const resolved = resolveGatewayFromParts(
29
+ { gateway_id: "user-gw" },
30
+ env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
31
+ );
32
+ expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "worker-token" });
33
+ });
34
+ });
35
+
36
+ describe("gatewaySource", () => {
37
+ it("labels pure user credentials", () => {
38
+ expect(gatewaySource(
39
+ { gateway_id: "gw", cf_aig_token: "tok" },
40
+ env(),
41
+ )).toBe("user");
42
+ });
43
+
44
+ it("labels worker-only credentials", () => {
45
+ expect(gatewaySource(null, env({ GATEWAY_ID: "gw" }))).toBe("worker");
46
+ });
47
+
48
+ it("labels mixed overrides", () => {
49
+ expect(gatewaySource(
50
+ { gateway_id: "user-gw" },
51
+ env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
52
+ )).toBe("mixed");
53
+ });
54
+ });
55
+
56
+ describe("maskSecret", () => {
57
+ it("masks long secrets with trailing preview", () => {
58
+ expect(maskSecret("abcdefghijklmnop")).toBe("••••••••••••mnop");
59
+ });
60
+
61
+ it("returns null for empty values", () => {
62
+ expect(maskSecret(undefined)).toBeNull();
63
+ expect(maskSecret(" ")).toBeNull();
64
+ });
65
+ });
@@ -0,0 +1,75 @@
1
+ // Tests for the Gemini SSE interpreter + delta reconciler (v0.21.4).
2
+ //
3
+ // The interpreter is stateless (frame text + usage). The reconciler is the
4
+ // load-bearing piece: it must yield correct non-repeating deltas whether the
5
+ // binding streams incremental pieces or cumulative full-text-so-far chunks,
6
+ // since we don't probe which mode is in use.
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import { interpretGeminiSSEFrame, makeGeminiDeltaReconciler } from "../src/parsers/gemini-sse";
10
+
11
+ describe("interpretGeminiSSEFrame", () => {
12
+ it("extracts candidate part text", () => {
13
+ const frame = { candidates: [{ content: { parts: [{ text: "Hello" }] } }] };
14
+ expect(interpretGeminiSSEFrame(frame)).toEqual([{ type: "text", text: "Hello" }]);
15
+ });
16
+
17
+ it("joins multiple parts in a frame", () => {
18
+ const frame = { candidates: [{ content: { parts: [{ text: "a" }, { text: "b" }] } }] };
19
+ expect(interpretGeminiSSEFrame(frame)).toEqual([{ type: "text", text: "ab" }]);
20
+ });
21
+
22
+ it("drops an empty-text frame", () => {
23
+ expect(interpretGeminiSSEFrame({ candidates: [{ content: { parts: [{ text: "" }] } }] })).toEqual([]);
24
+ expect(interpretGeminiSSEFrame({ candidates: [{ content: { parts: [] } }] })).toEqual([]);
25
+ });
26
+
27
+ it("reads usageMetadata into a usage event", () => {
28
+ const frame = { usageMetadata: { promptTokenCount: 8, candidatesTokenCount: 22, thoughtsTokenCount: 5 } };
29
+ expect(interpretGeminiSSEFrame(frame)).toEqual([{ type: "usage", in_: 8, out_: 22 }]);
30
+ });
31
+
32
+ it("yields text then usage when a frame carries both", () => {
33
+ const frame = {
34
+ candidates: [{ content: { parts: [{ text: "done" }] } }],
35
+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 2 },
36
+ };
37
+ expect(interpretGeminiSSEFrame(frame)).toEqual([
38
+ { type: "text", text: "done" },
39
+ { type: "usage", in_: 1, out_: 2 },
40
+ ]);
41
+ });
42
+
43
+ it("does not throw on null / undefined / string", () => {
44
+ expect(interpretGeminiSSEFrame(null)).toEqual([]);
45
+ expect(interpretGeminiSSEFrame(undefined)).toEqual([]);
46
+ expect(interpretGeminiSSEFrame("[DONE]")).toEqual([]);
47
+ });
48
+ });
49
+
50
+ describe("makeGeminiDeltaReconciler", () => {
51
+ it("passes incremental chunks through unchanged", () => {
52
+ const r = makeGeminiDeltaReconciler();
53
+ const frames = ["one", "\n", "two", "\n", "three"];
54
+ expect(frames.map(r).join("")).toBe("one\ntwo\nthree");
55
+ // each delta is exactly the incremental piece
56
+ const r2 = makeGeminiDeltaReconciler();
57
+ expect(frames.map(r2)).toEqual(["one", "\n", "two", "\n", "three"]);
58
+ });
59
+
60
+ it("diffs cumulative chunks down to the new suffix", () => {
61
+ const r = makeGeminiDeltaReconciler();
62
+ const frames = ["one", "one\n", "one\ntwo", "one\ntwo\n", "one\ntwo\nthree"];
63
+ expect(frames.map(r)).toEqual(["one", "\n", "two", "\n", "three"]);
64
+ expect(frames.map(makeGeminiDeltaReconciler())).not.toContain("one\ntwo"); // no repetition
65
+ });
66
+
67
+ it("reconstructs the same final text in both modes", () => {
68
+ const incremental = ["The ", "quick ", "brown ", "fox"];
69
+ const cumulative = ["The ", "The quick ", "The quick brown ", "The quick brown fox"];
70
+ const ri = makeGeminiDeltaReconciler();
71
+ const rc = makeGeminiDeltaReconciler();
72
+ expect(incremental.map(ri).join("")).toBe("The quick brown fox");
73
+ expect(cumulative.map(rc).join("")).toBe("The quick brown fox");
74
+ });
75
+ });
@@ -0,0 +1,65 @@
1
+ // Tests for the Gemini message transform (v0.21.3).
2
+ //
3
+ // The load-bearing bits: assistant -> model role mapping (Gemini has no
4
+ // "assistant"), system turns dropped (hoisted to systemInstruction), and
5
+ // defensive text coercion so a stray array/multimodal turn degrades to text
6
+ // rather than throwing.
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import { geminiContentsFromMessages, prepareGeminiRequest } from "../src/providers/google";
10
+
11
+ describe("geminiContentsFromMessages", () => {
12
+ it("maps user -> user and assistant -> model", () => {
13
+ const out = geminiContentsFromMessages([
14
+ { role: "user", content: "hi" },
15
+ { role: "assistant", content: "hello" },
16
+ { role: "user", content: "bye" },
17
+ ]);
18
+ expect(out).toEqual([
19
+ { role: "user", parts: [{ text: "hi" }] },
20
+ { role: "model", parts: [{ text: "hello" }] },
21
+ { role: "user", parts: [{ text: "bye" }] },
22
+ ]);
23
+ });
24
+
25
+ it("drops system-role turns (hoisted to systemInstruction)", () => {
26
+ const out = geminiContentsFromMessages([
27
+ { role: "system", content: "be terse" },
28
+ { role: "user", content: "hi" },
29
+ ]);
30
+ expect(out).toEqual([{ role: "user", parts: [{ text: "hi" }] }]);
31
+ });
32
+
33
+ it("coerces array content to joined text parts", () => {
34
+ const out = geminiContentsFromMessages([
35
+ { role: "user", content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] },
36
+ ]);
37
+ expect(out).toEqual([{ role: "user", parts: [{ text: "ab" }] }]);
38
+ });
39
+
40
+ it("treats an unknown role as user", () => {
41
+ expect(geminiContentsFromMessages([{ role: "tool", content: "x" }]))
42
+ .toEqual([{ role: "user", parts: [{ text: "x" }] }]);
43
+ });
44
+ });
45
+
46
+ describe("prepareGeminiRequest", () => {
47
+ it("includes systemInstruction when a system prompt is given", () => {
48
+ const body = prepareGeminiRequest("you are terse", [{ role: "user", content: "hi" }]);
49
+ expect(body).toEqual({
50
+ contents: [{ role: "user", parts: [{ text: "hi" }] }],
51
+ systemInstruction: { parts: [{ text: "you are terse" }] },
52
+ });
53
+ });
54
+
55
+ it("omits systemInstruction when no system prompt", () => {
56
+ const body = prepareGeminiRequest(undefined, [{ role: "user", content: "hi" }]);
57
+ expect(body).toEqual({ contents: [{ role: "user", parts: [{ text: "hi" }] }] });
58
+ expect("systemInstruction" in body).toBe(false);
59
+ });
60
+
61
+ it("omits systemInstruction for a blank system prompt", () => {
62
+ const body = prepareGeminiRequest(" ", [{ role: "user", content: "hi" }]);
63
+ expect("systemInstruction" in body).toBe(false);
64
+ });
65
+ });
@@ -0,0 +1,35 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { probeD1Schema, REQUIRED_D1_TABLES } from "../src/health-schema";
3
+
4
+ describe("probeD1Schema", () => {
5
+ it("reports ok when every required table exists", async () => {
6
+ const db = {
7
+ prepare: vi.fn(() => ({
8
+ bind: (...names: string[]) => ({
9
+ all: async () => ({
10
+ results: names.map((name) => ({ name })),
11
+ }),
12
+ }),
13
+ })),
14
+ } as unknown as D1Database;
15
+
16
+ const result = await probeD1Schema(db);
17
+ expect(result.ok).toBe(true);
18
+ expect(result.missing).toEqual([]);
19
+ expect(REQUIRED_D1_TABLES).toContain("user_prefs");
20
+ });
21
+
22
+ it("lists missing tables", async () => {
23
+ const db = {
24
+ prepare: vi.fn(() => ({
25
+ bind: () => ({
26
+ all: async () => ({ results: [{ name: "chats" }] }),
27
+ }),
28
+ })),
29
+ } as unknown as D1Database;
30
+
31
+ const result = await probeD1Schema(db);
32
+ expect(result.ok).toBe(false);
33
+ expect(result.missing).toContain("user_prefs");
34
+ });
35
+ });
@@ -0,0 +1,128 @@
1
+ // Tests for buildGenParams (v0.21.5).
2
+ //
3
+ // The point of these is that hh1-i2v's param shape differs from the
4
+ // text-to-video shape and getting it wrong means a rejected upstream call:
5
+ // i2v needs `image` + integer `duration` + "720P", and must NOT carry the
6
+ // t2v fields (aspect_ratio, generate_audio, string duration), which hh1-i2v's
7
+ // additionalProperties:false would reject.
8
+
9
+ import { describe, it, expect } from "vitest";
10
+ import { buildGenParams } from "../src/longrun-params";
11
+
12
+ describe("buildGenParams", () => {
13
+ it("builds the text-to-video shape when no imageUrl", () => {
14
+ expect(buildGenParams("video", { prompt: "a dragon flying" })).toEqual({
15
+ prompt: "a dragon flying",
16
+ duration: "8s",
17
+ aspect_ratio: "16:9",
18
+ resolution: "720p",
19
+ generate_audio: true,
20
+ });
21
+ });
22
+
23
+ it("builds the image-to-video shape when imageUrl is present", () => {
24
+ const p = buildGenParams("video", { prompt: "slow push-in", imageUrl: "https://x/cat.png" });
25
+ expect(p).toEqual({
26
+ image: "https://x/cat.png",
27
+ resolution: "720P",
28
+ duration: 5,
29
+ prompt: "slow push-in",
30
+ });
31
+ });
32
+
33
+ it("i2v does NOT carry any text-to-video fields", () => {
34
+ const p = buildGenParams("video", { prompt: "x", imageUrl: "https://x/y.png" });
35
+ expect(p).not.toHaveProperty("aspect_ratio");
36
+ expect(p).not.toHaveProperty("generate_audio");
37
+ expect(p.duration).toBe(5); // integer, not "8s"
38
+ expect(p.resolution).toBe("720P"); // capital P
39
+ });
40
+
41
+ it("i2v omits an empty prompt (it's optional)", () => {
42
+ const p = buildGenParams("video", { prompt: " ", imageUrl: "https://x/y.png" });
43
+ expect(p).not.toHaveProperty("prompt");
44
+ expect(p).toEqual({ image: "https://x/y.png", resolution: "720P", duration: 5 });
45
+ });
46
+
47
+ it("Seedance 2.0 i2v shape: `image` field, integer duration, lowercase 720p", () => {
48
+ const p = buildGenParams("video", {
49
+ modelId: "bytedance/seedance-2.0",
50
+ prompt: "rain falls",
51
+ imageUrl: "https://x/k.png",
52
+ });
53
+ expect(p).toEqual({
54
+ image: "https://x/k.png",
55
+ prompt: "rain falls",
56
+ aspect_ratio: "16:9",
57
+ duration: 5,
58
+ resolution: "720p",
59
+ fps: 24,
60
+ camera_fixed: false,
61
+ watermark: false,
62
+ generate_audio: false,
63
+ });
64
+ expect(p).not.toHaveProperty("first_frame_image");
65
+ expect(p).not.toHaveProperty("image_input");
66
+ });
67
+
68
+ it("Hailuo 2.3 i2v shape: `first_frame_image` field, 768P resolution", () => {
69
+ const p = buildGenParams("video", {
70
+ modelId: "minimax/hailuo-2.3-fast",
71
+ prompt: "she turns",
72
+ imageUrl: "https://x/k.png",
73
+ });
74
+ expect(p).toEqual({
75
+ first_frame_image: "https://x/k.png",
76
+ prompt: "she turns",
77
+ duration: 6,
78
+ resolution: "768P",
79
+ fast_pretreatment: false,
80
+ prompt_optimizer: true,
81
+ });
82
+ expect(p).not.toHaveProperty("image");
83
+ });
84
+
85
+ it("Runway Gen-4.5 i2v shape: `image_input` field, `ratio` not resolution", () => {
86
+ const p = buildGenParams("video", {
87
+ modelId: "runwayml/gen-4.5",
88
+ prompt: "drift",
89
+ imageUrl: "https://x/k.png",
90
+ });
91
+ expect(p).toEqual({
92
+ image_input: "https://x/k.png",
93
+ prompt: "drift",
94
+ duration: 5,
95
+ ratio: "1280:720",
96
+ content_moderation: { public_figure_threshold: "low" },
97
+ });
98
+ expect(p).not.toHaveProperty("resolution");
99
+ });
100
+
101
+ it("prompt-required i2v models get a default motion prompt when none is given", () => {
102
+ const p = buildGenParams("video", {
103
+ modelId: "bytedance/seedance-2.0",
104
+ prompt: " ",
105
+ imageUrl: "https://x/k.png",
106
+ });
107
+ expect(typeof p.prompt).toBe("string");
108
+ expect((p.prompt as string).length).toBeGreaterThan(0);
109
+ });
110
+
111
+ it("explicit hh1-i2v modelId yields the hh1 shape (same as the default)", () => {
112
+ const explicit = buildGenParams("video", {
113
+ modelId: "alibaba/hh1-i2v",
114
+ prompt: "p",
115
+ imageUrl: "https://x/k.png",
116
+ });
117
+ const dflt = buildGenParams("video", { prompt: "p", imageUrl: "https://x/k.png" });
118
+ expect(explicit).toEqual(dflt);
119
+ expect(explicit).toEqual({ image: "https://x/k.png", resolution: "720P", duration: 5, prompt: "p" });
120
+ });
121
+
122
+ it("builds the music shape, with lyrics only when non-empty", () => {
123
+ expect(buildGenParams("music", { prompt: "lofi beat" })).toEqual({ prompt: "lofi beat" });
124
+ expect(buildGenParams("music", { prompt: "ballad", lyrics: "la la" }))
125
+ .toEqual({ prompt: "ballad", lyrics: "la la" });
126
+ expect(buildGenParams("music", { prompt: "x", lyrics: " " })).toEqual({ prompt: "x" });
127
+ });
128
+ });
@@ -0,0 +1,71 @@
1
+ // Tests for interpretOpenAISSEFrame (v0.21.0).
2
+ //
3
+ // The interpreter must handle both shapes env.AI.run can emit for a streamed
4
+ // proxied OpenAI model: the OpenAI-native delta shape and the CF-normalized
5
+ // flat `response` shape. Whichever the proxy actually uses, streaming should
6
+ // produce the same normalized text/usage events. `data: [DONE]` is stripped
7
+ // by the SSE framer upstream, so it never reaches the interpreter.
8
+
9
+ import { describe, it, expect } from "vitest";
10
+ import { interpretOpenAISSEFrame } from "../src/parsers/openai-sse";
11
+
12
+ describe("interpretOpenAISSEFrame", () => {
13
+ // --- Shape 1: OpenAI-native delta ---
14
+
15
+ it("extracts a content delta from the OpenAI-native shape", () => {
16
+ const frame = {
17
+ id: "chatcmpl-x",
18
+ object: "chat.completion.chunk",
19
+ choices: [{ index: 0, delta: { content: "Hello" } }],
20
+ };
21
+ expect(interpretOpenAISSEFrame(frame)).toEqual([{ type: "text", text: "Hello" }]);
22
+ });
23
+
24
+ it("drops an empty-string delta (normal on role/usage frames)", () => {
25
+ expect(interpretOpenAISSEFrame({ choices: [{ delta: { content: "" } }] })).toEqual([]);
26
+ expect(interpretOpenAISSEFrame({ choices: [{ delta: {} }] })).toEqual([]);
27
+ });
28
+
29
+ it("reads the usage frame from the OpenAI-native shape", () => {
30
+ const frame = { choices: [{ delta: {} }], usage: { prompt_tokens: 11, completion_tokens: 22 } };
31
+ expect(interpretOpenAISSEFrame(frame)).toEqual([{ type: "usage", in_: 11, out_: 22 }]);
32
+ });
33
+
34
+ // --- Shape 2: CF-normalized flat `response` ---
35
+
36
+ it("extracts text from the flat response shape", () => {
37
+ expect(interpretOpenAISSEFrame({ response: "world" })).toEqual([{ type: "text", text: "world" }]);
38
+ });
39
+
40
+ it("drops an empty flat response", () => {
41
+ expect(interpretOpenAISSEFrame({ response: "" })).toEqual([]);
42
+ });
43
+
44
+ it("reads usage from the flat shape, accepting OpenAI or Anthropic naming", () => {
45
+ expect(interpretOpenAISSEFrame({ response: "", usage: { prompt_tokens: 3, completion_tokens: 4 } }))
46
+ .toEqual([{ type: "usage", in_: 3, out_: 4 }]);
47
+ expect(interpretOpenAISSEFrame({ response: "", usage: { input_tokens: 5, output_tokens: 6 } }))
48
+ .toEqual([{ type: "usage", in_: 5, out_: 6 }]);
49
+ });
50
+
51
+ // --- Robustness ---
52
+
53
+ it("yields text then usage when a single frame carries both", () => {
54
+ const frame = { choices: [{ delta: { content: "done" } }], usage: { prompt_tokens: 1, completion_tokens: 2 } };
55
+ expect(interpretOpenAISSEFrame(frame)).toEqual([
56
+ { type: "text", text: "done" },
57
+ { type: "usage", in_: 1, out_: 2 },
58
+ ]);
59
+ });
60
+
61
+ it("returns no events for an unrelated frame", () => {
62
+ expect(interpretOpenAISSEFrame({ id: "x", object: "chat.completion.chunk", choices: [{}] })).toEqual([]);
63
+ });
64
+
65
+ it("does not throw on null / undefined / string", () => {
66
+ expect(() => interpretOpenAISSEFrame(null)).not.toThrow();
67
+ expect(() => interpretOpenAISSEFrame(undefined)).not.toThrow();
68
+ expect(() => interpretOpenAISSEFrame("[DONE]")).not.toThrow();
69
+ expect(interpretOpenAISSEFrame(null)).toEqual([]);
70
+ });
71
+ });