Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Serve the API at api.rallly.co/v1 and group poll options under options.kind (#3261)

Luke Vella34b6c377deb7
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index fb075df02..a59938f34 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -50,14 +50,18 @@ const nextConfig: NextConfig = {
typescript: {
ignoreBuildErrors: true,
},
+ // The public API host (https://api.rallly.co) serves the versioned API
+ // without the app's `/api` prefix. Only `/v1` is exposed there: the rest of
+ // `/api` stays app-host only, so a standalone API project can take over the
+ // host later without inheriting them.
async rewrites() {
if (!process.env.API_BASE_URL) return [];
const host = new URL(process.env.API_BASE_URL).host;
return [
{
- source: "/:path*",
+ source: "/v1/:path*",
has: [{ type: "host", value: host }],
- destination: "/api/:path*",
+ destination: "/api/v1/:path*",
},
];
},
diff --git a/apps/web/src/app/api/middleware/openapi.ts b/apps/web/src/app/api/middleware/openapi.ts
index 94d3b084f..c00c66ddc 100644
--- a/apps/web/src/app/api/middleware/openapi.ts
+++ b/apps/web/src/app/api/middleware/openapi.ts
@@ -11,6 +11,23 @@ type OpenApiSchema = Awaited<ReturnType<ToOpenApiSchema>>;
const DEFS_PREFIX = "#/$defs/";
const COMPONENTS_PREFIX = "#/components/schemas/";
+// Formats whose syntax JSON Schema itself defines. Zod emits a regex beside
+// each of these (its ISO date pattern is 200 characters) that says nothing
+// the format does not, so it is dropped for readability. Any other pattern
+// is a real constraint and stays.
+const FORMATS_WITH_DEFINED_SYNTAX = new Set([
+ "date",
+ "date-time",
+ "time",
+ "duration",
+ "email",
+ "uri",
+ "uuid",
+ "ipv4",
+ "ipv6",
+]);
+
+// Rewrites `$defs` refs to `components.schemas` and drops redundant patterns.
function rewriteRefs(node: unknown): unknown {
if (Array.isArray(node)) {
return node.map(rewriteRefs);
@@ -18,13 +35,19 @@ function rewriteRefs(node: unknown): unknown {
if (!node || typeof node !== "object") {
return node;
}
+ const redundantPattern =
+ "format" in node &&
+ typeof node.format === "string" &&
+ FORMATS_WITH_DEFINED_SYNTAX.has(node.format);
return Object.fromEntries(
- Object.entries(node).map(([key, value]) => [
- key,
- key === "$ref" && typeof value === "string"
- ? value.replace(DEFS_PREFIX, COMPONENTS_PREFIX)
- : rewriteRefs(value),
- ]),
+ Object.entries(node)
+ .filter(([key]) => !(redundantPattern && key === "pattern"))
+ .map(([key, value]) => [
+ key,
+ key === "$ref" && typeof value === "string"
+ ? value.replace(DEFS_PREFIX, COMPONENTS_PREFIX)
+ : rewriteRefs(value),
+ ]),
);
}
diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.ts
index 802411579..588a25136 100644
--- a/apps/web/src/app/api/v1/[...route]/route.test.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts
@@ -95,7 +95,7 @@ import {
listPollsSuccessResponseSchema,
pollResponseSchema,
} from "../schemas";
-import { app } from "./route";
+import { app, GET, POST } from "./route";
const expectMatchesContract = (
schema: {
@@ -191,12 +191,12 @@ describe("API v1 - /polls", () => {
describe("Authentication", () => {
it("should return 401 without authorization header", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -207,7 +207,7 @@ describe("API v1 - /polls", () => {
it("should return 401 with invalid API key", async () => {
vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -215,7 +215,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -227,7 +227,7 @@ describe("API v1 - /polls", () => {
// Revoked keys are filtered out by the database query
vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -235,7 +235,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -247,7 +247,7 @@ describe("API v1 - /polls", () => {
// Expired keys are filtered out by the database query
vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -255,7 +255,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -272,7 +272,7 @@ describe("API v1 - /polls", () => {
};
vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([hobbyApiKey]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -280,7 +280,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -298,7 +298,7 @@ describe("API v1 - /polls", () => {
};
vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([hobbyApiKey]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -306,7 +306,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -315,7 +315,7 @@ describe("API v1 - /polls", () => {
});
it("should return 200 with a valid key when the space is pro", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -323,7 +323,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -341,7 +341,7 @@ describe("API v1 - /polls", () => {
},
]);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -361,7 +361,7 @@ describe("API v1 - /polls", () => {
},
]);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -381,7 +381,7 @@ describe("API v1 - /polls", () => {
},
]);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -400,7 +400,7 @@ describe("API v1 - /polls", () => {
},
]);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -422,7 +422,7 @@ describe("API v1 - /polls", () => {
};
it("should authenticate a legacy scrypt-hashed key and re-hash it to sha256", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -430,7 +430,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -455,7 +455,7 @@ describe("API v1 - /polls", () => {
{ ...mockApiKey, hashedKey: hashApiKey(testApiKey) },
]);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -463,7 +463,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -479,7 +479,7 @@ describe("API v1 - /polls", () => {
describe("Create poll with dates", () => {
it("should create a poll with date options", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -487,7 +487,10 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team offsite",
- dates: ["2025-01-15", "2025-01-16", "2025-01-17"],
+ options: {
+ kind: "date",
+ dates: ["2025-01-15", "2025-01-16", "2025-01-17"],
+ },
}),
});
@@ -547,7 +550,7 @@ describe("API v1 - /polls", () => {
options: [],
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -555,7 +558,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team offsite",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
requireEmail: true,
hideParticipants: true,
hideScores: true,
@@ -619,7 +622,7 @@ describe("API v1 - /polls", () => {
options: [],
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -627,7 +630,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team offsite",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
allowTentativeVotes: false,
}),
});
@@ -642,7 +645,7 @@ describe("API v1 - /polls", () => {
});
it("should track poll creation with source api and kind date", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -650,7 +653,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team offsite",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -676,7 +679,7 @@ describe("API v1 - /polls", () => {
});
it("should save location when provided", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -685,7 +688,7 @@ describe("API v1 - /polls", () => {
body: JSON.stringify({
title: "Team offsite",
location: "Conference Room A",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -704,7 +707,7 @@ describe("API v1 - /polls", () => {
return date.toISOString().split("T")[0];
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -712,7 +715,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates,
+ options: { kind: "date", dates },
}),
});
@@ -722,7 +725,7 @@ describe("API v1 - /polls", () => {
});
it("should return error when duplicate dates are provided", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -730,7 +733,10 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15", "2025-01-16", "2025-01-15", "2025-01-17"],
+ options: {
+ kind: "date",
+ dates: ["2025-01-15", "2025-01-16", "2025-01-15", "2025-01-17"],
+ },
}),
});
@@ -741,9 +747,9 @@ describe("API v1 - /polls", () => {
});
});
- describe("Create poll with slots", () => {
+ describe("Create poll with time options", () => {
it("should create a poll with time slot options", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -751,9 +757,10 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team sync",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
+ timeZone: "Europe/London",
times: ["2025-01-15T09:00:00Z", "2025-01-15T10:00:00Z"],
},
}),
@@ -804,7 +811,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -812,9 +819,10 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team sync",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
+ timeZone: "Europe/London",
times: ["2025-01-15T09:00:00Z"],
},
}),
@@ -839,7 +847,7 @@ describe("API v1 - /polls", () => {
});
it("should create poll without timezone when not provided in request", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -847,7 +855,8 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team sync",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
times: ["2025-01-15T09:00:00Z"],
},
@@ -863,7 +872,7 @@ describe("API v1 - /polls", () => {
});
it("should return error for invalid timezone", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -871,9 +880,10 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Team sync",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Invalid/Timezone",
+ timeZone: "Invalid/Timezone",
times: ["2025-01-15T09:00:00Z"],
},
}),
@@ -883,7 +893,7 @@ describe("API v1 - /polls", () => {
});
it("should create poll with slot generator", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -891,10 +901,11 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Weekly standup",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
- times: [
+ timeZone: "Europe/London",
+ generators: [
{
startDate: "2025-01-20",
endDate: "2025-01-22",
@@ -916,7 +927,7 @@ describe("API v1 - /polls", () => {
// under MAX_POLL_OPTIONS so TOO_MANY_OPTIONS can't mask it: only the
// range check rejects this. The old code silently truncated to ~52 slots
// and returned them as a successful poll.
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -924,10 +935,11 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Way too long",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
- times: [
+ timeZone: "Europe/London",
+ generators: [
{
startDate: "2025-01-01",
endDate: "2026-06-01",
@@ -954,7 +966,7 @@ describe("API v1 - /polls", () => {
});
it("should reject a slot generator range where endDate precedes startDate", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -962,10 +974,11 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Reversed range",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
- times: [
+ timeZone: "Europe/London",
+ generators: [
{
startDate: "2025-06-01",
endDate: "2025-01-01",
@@ -994,7 +1007,7 @@ describe("API v1 - /polls", () => {
const end = new Date(start);
end.setUTCDate(end.getUTCDate() + MAX_SLOT_GENERATION_DAYS);
const toIsoDate = (d: Date) => d.toISOString().slice(0, 10);
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1002,10 +1015,11 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Boundary range",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "Europe/London",
- times: [
+ timeZone: "Europe/London",
+ generators: [
{
startDate: toIsoDate(start),
endDate: toIsoDate(end),
@@ -1024,8 +1038,8 @@ describe("API v1 - /polls", () => {
});
describe("Validation", () => {
- it("should return error when neither dates nor slots provided", async () => {
- const res = await app.request("/api/v1/polls", {
+ it("should return error when options are missing", async () => {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1039,8 +1053,8 @@ describe("API v1 - /polls", () => {
expect(res.status).toBe(400);
});
- it("should return error when both dates and slots provided", async () => {
- const res = await app.request("/api/v1/polls", {
+ it("should return error when a date poll carries time fields", async () => {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1048,10 +1062,9 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
- slots: {
- duration: 30,
- timezone: "Europe/London",
+ options: {
+ kind: "date",
+ options: { kind: "date", dates: ["2025-01-15"] },
times: ["2025-01-15T09:00:00Z"],
},
}),
@@ -1061,14 +1074,14 @@ describe("API v1 - /polls", () => {
});
it("should return error when title is missing", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${testApiKey}`,
},
body: JSON.stringify({
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -1076,7 +1089,7 @@ describe("API v1 - /polls", () => {
});
it("should reject unknown fields such as spaceId instead of ignoring them", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1084,7 +1097,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
spaceId: "some-other-space",
}),
});
@@ -1102,30 +1115,32 @@ describe("API v1 - /polls", () => {
level: "organizer",
body: {
title: "Test Poll",
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
organizer: { email: "[email protected]", name: "Ann" },
},
message: 'organizer: Unrecognized key: "name"',
},
{
- level: "slots",
+ level: "options",
body: {
title: "Test Poll",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
times: ["2025-01-15T09:00:00Z"],
- timeZone: "Europe/London",
+ timezone: "Europe/London",
},
},
- message: 'slots: Unrecognized key: "timeZone"',
+ message: 'options: Unrecognized key: "timezone"',
},
{
level: "slot generator",
body: {
title: "Test Poll",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- times: [
+ generators: [
{
startDate: "2025-01-13",
endDate: "2025-01-17",
@@ -1137,15 +1152,13 @@ describe("API v1 - /polls", () => {
],
},
},
- // The generator sits in a union with the datetime string, so zod
- // reports the failing entry rather than the offending key.
- message: "slots.times.0: Invalid input",
+ message: 'options.generators.0: Unrecognized key: "step"',
},
])("should reject unknown fields nested in the $level object", async ({
body,
message,
}) => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1163,7 +1176,7 @@ describe("API v1 - /polls", () => {
});
it("should reject a title longer than the maximum length", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1171,7 +1184,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "x".repeat(MAX_POLL_TITLE_LENGTH + 1),
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -1184,7 +1197,7 @@ describe("API v1 - /polls", () => {
});
it("should accept a title at the maximum length", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1192,7 +1205,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "x".repeat(MAX_POLL_TITLE_LENGTH),
- dates: ["2025-01-15"],
+ options: { kind: "date", dates: ["2025-01-15"] },
}),
});
@@ -1200,7 +1213,7 @@ describe("API v1 - /polls", () => {
});
it("should return error when dates array is empty", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1208,7 +1221,7 @@ describe("API v1 - /polls", () => {
},
body: JSON.stringify({
title: "Test Poll",
- dates: [],
+ options: { kind: "date", dates: [] },
}),
});
@@ -1216,9 +1229,48 @@ describe("API v1 - /polls", () => {
});
});
+ describe("Route handler path prefix", () => {
+ it("should serve /v1 as delivered by the API host rewrite", async () => {
+ const res = await GET(new Request("https://api.example.com/v1/openapi"));
+
+ expect(res.status).toBe(200);
+ expect((await res.json()).info.title).toBe("Rallly API");
+ });
+
+ it("should serve /api/v1 on the app host by stripping the prefix", async () => {
+ const res = await GET(new Request("https://example.com/api/v1/openapi"));
+
+ expect(res.status).toBe(200);
+ expect((await res.json()).info.title).toBe("Rallly API");
+ });
+
+ it("should keep the method and body when stripping the prefix", async () => {
+ const res = await POST(
+ new Request("https://example.com/api/v1/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Forwarded through the prefix handler",
+ options: { kind: "date", dates: ["2027-03-01"] },
+ }),
+ }),
+ );
+
+ expect(res.status).toBe(201);
+ expect(mockCreatePoll).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Forwarded through the prefix handler",
+ }),
+ );
+ });
+ });
+
describe("OpenAPI endpoints", () => {
it("should return OpenAPI spec", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
@@ -1226,25 +1278,23 @@ describe("API v1 - /polls", () => {
expect(json.info.version).toBe("1.0.0");
});
- it("should state the versioning policy and point the playground at this origin", async () => {
- const res = await app.request("/api/v1/openapi");
+ it("should state the versioning policy and point the playground at this origin's /api prefix when there is no API host", async () => {
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
expect(json.info.description).toContain("## Versioning");
expect(json.info.description).toContain("new version prefix");
- expect(json.servers).toEqual([{ url: "https://example.com" }]);
+ expect(json.servers).toEqual([{ url: "https://example.com/api" }]);
});
it("should include create poll request examples that match the input schema", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
const media =
- json.paths["/api/v1/polls"].post.requestBody.content[
- "application/json"
- ];
+ json.paths["/v1/polls"].post.requestBody.content["application/json"];
expect(Object.keys(media.examples)).toEqual(
Object.keys(createPollRequestExamples),
);
@@ -1257,11 +1307,11 @@ describe("API v1 - /polls", () => {
});
it("should document the close poll transition on PATCH /polls/{pollId}", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
- const operation = json.paths["/api/v1/polls/{pollId}"].patch;
+ const operation = json.paths["/v1/polls/{pollId}"].patch;
expect(operation.summary).toBeDefined();
expect(operation.description).toContain("closed");
@@ -1276,7 +1326,7 @@ describe("API v1 - /polls", () => {
});
it("should emit schema descriptions, examples and named components", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
@@ -1285,7 +1335,8 @@ describe("API v1 - /polls", () => {
expect(Object.keys(schemas)).toEqual(
expect.arrayContaining([
"CreatePollInput",
- "SlotsInput",
+ "DateOptions",
+ "TimeOptions",
"SlotGenerator",
"Poll",
"PollStatus",
@@ -1306,10 +1357,17 @@ describe("API v1 - /polls", () => {
expect(schemas.DateOptionResult.properties.date.format).toBe("date");
expect(schemas.Poll.properties.title.example).toBe("Team sync");
expect(
- json.paths["/api/v1/polls"].post.requestBody.content["application/json"]
+ json.paths["/v1/polls"].post.requestBody.content["application/json"]
.schema,
).toEqual({ $ref: "#/components/schemas/CreatePollInput" });
- expect(schemas.SlotsInput.properties.times.items.anyOf).toContainEqual({
+ expect(schemas.CreatePollInput.properties.options).toMatchObject({
+ oneOf: [
+ { $ref: "#/components/schemas/DateOptions" },
+ { $ref: "#/components/schemas/TimeOptions" },
+ ],
+ discriminator: { propertyName: "kind" },
+ });
+ expect(schemas.TimeOptions.properties.generators.items).toEqual({
$ref: "#/components/schemas/SlotGenerator",
});
@@ -1325,7 +1383,7 @@ describe("API v1 - /polls", () => {
$ref: pollStatusRef,
example: "closed",
});
- expect(json.paths["/api/v1/polls"].get.parameters).toContainEqual(
+ expect(json.paths["/v1/polls"].get.parameters).toContainEqual(
expect.objectContaining({
name: "status",
schema: expect.objectContaining({ $ref: pollStatusRef }),
@@ -1349,12 +1407,12 @@ describe("API v1 - /polls", () => {
});
it("should document 201 for create, strict inputs and realistic ID examples", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
const json = await res.json();
const schemas = json.components.schemas;
- const createResponses = json.paths["/api/v1/polls"].post.responses;
+ const createResponses = json.paths["/v1/polls"].post.responses;
expect(createResponses["201"]).toBeDefined();
expect(createResponses["200"]).toBeUndefined();
@@ -1410,14 +1468,14 @@ describe("API v1 - /polls", () => {
});
it("should serve the spec without a no-store header", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
expect(res.status).toBe(200);
expect(res.headers.get("Cache-Control")).toBeNull();
});
it("should not serve a docs page (the reference lives in the docs site)", async () => {
- const res = await app.request("/api/v1/docs");
+ const res = await app.request("/v1/docs");
expect(res.status).toBe(404);
});
@@ -1452,7 +1510,7 @@ describe("API v1 - /polls", () => {
it("should close an open poll", async () => {
mockClosePoll.mockResolvedValue(closedPoll);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1476,7 +1534,7 @@ describe("API v1 - /polls", () => {
it("should be idempotent when the poll is already closed", async () => {
mockClosePoll.mockResolvedValue(closedPoll);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1493,7 +1551,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when the poll is not found", async () => {
mockClosePoll.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/nonexistent-poll", {
+ const res = await app.request("/v1/polls/nonexistent-poll", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1513,7 +1571,7 @@ describe("API v1 - /polls", () => {
"scheduled",
"canceled",
])("should return 422 when transitioning to %s", async (status) => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1529,7 +1587,7 @@ describe("API v1 - /polls", () => {
});
it("should reject unknown fields in the patch body", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1547,7 +1605,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 for an unknown status value", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1561,7 +1619,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: {
"Content-Type": "application/json",
@@ -1578,7 +1636,7 @@ describe("API v1 - /polls", () => {
it("should delete a poll", async () => {
mockDeletePoll.mockResolvedValue({ id: "test-poll-id" });
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "DELETE",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1600,7 +1658,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll not found", async () => {
mockDeletePoll.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/nonexistent-poll", {
+ const res = await app.request("/v1/polls/nonexistent-poll", {
method: "DELETE",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1615,7 +1673,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll belongs to different space", async () => {
mockDeletePoll.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/other-space-poll", {
+ const res = await app.request("/v1/polls/other-space-poll", {
method: "DELETE",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1628,7 +1686,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "DELETE",
});
@@ -1638,7 +1696,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll is already deleted", async () => {
mockDeletePoll.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/deleted-poll-id", {
+ const res = await app.request("/v1/polls/deleted-poll-id", {
method: "DELETE",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1691,7 +1749,7 @@ describe("API v1 - /polls", () => {
it("should return poll data", async () => {
mockGetPollWithOptions.mockResolvedValue(mockPoll);
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1705,7 +1763,7 @@ describe("API v1 - /polls", () => {
expect(json.data.title).toBe("Team sync");
expect(json.data.description).toBe("Weekly team meeting");
expect(json.data.location).toBe("Zoom");
- expect(json.data.timezone).toBe("Europe/London");
+ expect(json.data.timeZone).toBe("Europe/London");
expect(json.data.status).toBe("open");
expect(json.data.kind).toBe("time");
expect(json.data.createdAt).toBe("2025-01-10T12:00:00.000Z");
@@ -1758,7 +1816,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1781,7 +1839,7 @@ describe("API v1 - /polls", () => {
user: null,
});
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1796,7 +1854,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll not found", async () => {
mockGetPollWithOptions.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/nonexistent-poll", {
+ const res = await app.request("/v1/polls/nonexistent-poll", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1811,7 +1869,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll belongs to different space", async () => {
mockGetPollWithOptions.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/other-space-poll", {
+ const res = await app.request("/v1/polls/other-space-poll", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1824,7 +1882,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
});
@@ -1870,7 +1928,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1932,7 +1990,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1954,7 +2012,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1974,7 +2032,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls?status=open", {
+ const res = await app.request("/v1/polls?status=open", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -1991,7 +2049,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 for an invalid status", async () => {
- const res = await app.request("/api/v1/polls?status=finalized", {
+ const res = await app.request("/v1/polls?status=finalized", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2008,15 +2066,12 @@ describe("API v1 - /polls", () => {
nextCursor: "test-poll-id",
});
- const res = await app.request(
- "/api/v1/polls?cursor=prev-poll-id&limit=1",
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${testApiKey}`,
- },
+ const res = await app.request("/v1/polls?cursor=prev-poll-id&limit=1", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
},
- );
+ });
expect(res.status).toBe(200);
const json = await res.json();
@@ -2032,7 +2087,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 when limit exceeds the maximum", async () => {
- const res = await app.request("/api/v1/polls?limit=101", {
+ const res = await app.request("/v1/polls?limit=101", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2044,7 +2099,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "GET",
});
@@ -2100,7 +2155,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2165,7 +2220,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2212,7 +2267,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2260,7 +2315,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2311,7 +2366,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2363,7 +2418,7 @@ describe("API v1 - /polls", () => {
],
});
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2383,7 +2438,7 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll not found", async () => {
mockGetPollResults.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/nonexistent-poll/results", {
+ const res = await app.request("/v1/polls/nonexistent-poll/results", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2396,7 +2451,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id/results", {
+ const res = await app.request("/v1/polls/test-poll-id/results", {
method: "GET",
});
@@ -2423,7 +2478,7 @@ describe("API v1 - /polls", () => {
it("should include standard RateLimit headers on successful responses", async () => {
mockGetPollWithOptions.mockResolvedValue(null);
- const res = await app.request("/api/v1/polls/some-poll", {
+ const res = await app.request("/v1/polls/some-poll", {
method: "GET",
headers: { Authorization: `Bearer ${testApiKey}` },
});
@@ -2438,7 +2493,7 @@ describe("API v1 - /polls", () => {
mockGetPollWithOptions.mockResolvedValue(null);
const request = () =>
- app.request("/api/v1/polls/some-poll", {
+ app.request("/v1/polls/some-poll", {
method: "GET",
headers: { Authorization: `Bearer ${testApiKey}` },
});
@@ -2472,13 +2527,13 @@ describe("API v1 - /polls", () => {
mockListPolls.mockResolvedValue({ polls: [], nextCursor: null });
const responses = await Promise.all([
- app.request("/api/v1/polls/test-poll-id/participants", {
+ app.request("/v1/polls/test-poll-id/participants", {
headers: { Authorization: `Bearer ${testApiKey}` },
}),
- app.request("/api/v1/polls", {
+ app.request("/v1/polls", {
headers: { Authorization: `Bearer ${testApiKey}` },
}),
- app.request("/api/v1/polls/test-poll-id"),
+ app.request("/v1/polls/test-poll-id"),
]);
for (const res of responses) {
@@ -2515,7 +2570,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls/test-poll-id/participants", {
+ const res = await app.request("/v1/polls/test-poll-id/participants", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2557,7 +2612,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls/test-poll-id/participants", {
+ const res = await app.request("/v1/polls/test-poll-id/participants", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2580,7 +2635,7 @@ describe("API v1 - /polls", () => {
});
const res = await app.request(
- "/api/v1/polls/test-poll-id/participants?cursor=participant-1&limit=1",
+ "/v1/polls/test-poll-id/participants?cursor=participant-1&limit=1",
{
method: "GET",
headers: {
@@ -2607,7 +2662,7 @@ describe("API v1 - /polls", () => {
it("should return 400 when limit is out of range", async () => {
const res = await app.request(
- "/api/v1/polls/test-poll-id/participants?limit=500",
+ "/v1/polls/test-poll-id/participants?limit=500",
{
method: "GET",
headers: {
@@ -2627,7 +2682,7 @@ describe("API v1 - /polls", () => {
nextCursor: null,
});
- const res = await app.request("/api/v1/polls/test-poll-id/participants", {
+ const res = await app.request("/v1/polls/test-poll-id/participants", {
method: "GET",
headers: {
Authorization: `Bearer ${testApiKey}`,
@@ -2644,15 +2699,12 @@ describe("API v1 - /polls", () => {
it("should return 404 when poll not found", async () => {
mockGetPollParticipants.mockResolvedValue(null);
- const res = await app.request(
- "/api/v1/polls/nonexistent-poll/participants",
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${testApiKey}`,
- },
+ const res = await app.request("/v1/polls/nonexistent-poll/participants", {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${testApiKey}`,
},
- );
+ });
expect(res.status).toBe(404);
const json = await res.json();
@@ -2660,7 +2712,7 @@ describe("API v1 - /polls", () => {
});
it("should return 401 without authorization", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id/participants", {
+ const res = await app.request("/v1/polls/test-poll-id/participants", {
method: "GET",
});
@@ -2672,7 +2724,7 @@ describe("API v1 - /polls", () => {
const authed = { Authorization: `Bearer ${testApiKey}` };
it("should return 400 INVALID_AUTHORIZATION_HEADER as JSON for a malformed Authorization header", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "GET",
headers: { Authorization: "Basic not-a-bearer-token" },
});
@@ -2685,10 +2737,13 @@ describe("API v1 - /polls", () => {
});
it("should return 400 VALIDATION_ERROR naming the fields, without echoing the body, for an invalid JSON body", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: { ...authed, "Content-Type": "application/json" },
- body: JSON.stringify({ dates: ["not-a-date"], secret: "do-not-echo" }),
+ body: JSON.stringify({
+ options: { kind: "date", dates: ["not-a-date"] },
+ secret: "do-not-echo",
+ }),
});
const json = await expectErrorEnvelope(res, {
@@ -2696,7 +2751,7 @@ describe("API v1 - /polls", () => {
code: "VALIDATION_ERROR",
});
expect(json.error.message).toContain("title:");
- expect(json.error.message).toContain("dates.0:");
+ expect(json.error.message).toContain("options.dates.0:");
expect(Object.keys(json.error).sort()).toEqual(["code", "message"]);
expect(JSON.stringify(json)).not.toContain("do-not-echo");
expect(json).not.toHaveProperty("success");
@@ -2705,7 +2760,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 VALIDATION_ERROR as JSON for an invalid query string", async () => {
- const res = await app.request("/api/v1/polls?limit=9999", {
+ const res = await app.request("/v1/polls?limit=9999", {
method: "GET",
headers: authed,
});
@@ -2719,7 +2774,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 VALIDATION_ERROR as JSON for a PATCH body that fails validation", async () => {
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "PATCH",
headers: { ...authed, "Content-Type": "application/json" },
body: JSON.stringify({ status: "archived" }),
@@ -2734,7 +2789,7 @@ describe("API v1 - /polls", () => {
});
it("should return 400 VALIDATION_ERROR as JSON for a malformed JSON body", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "POST",
headers: { ...authed, "Content-Type": "application/json" },
body: "{not json",
@@ -2744,7 +2799,7 @@ describe("API v1 - /polls", () => {
});
it("should return 404 NOT_FOUND as JSON for an unknown route", async () => {
- const res = await app.request("/api/v1/nope", {
+ const res = await app.request("/v1/nope", {
method: "GET",
headers: authed,
});
@@ -2753,7 +2808,7 @@ describe("API v1 - /polls", () => {
});
it("should return 404 NOT_FOUND as JSON for an unsupported method on a known route", async () => {
- const res = await app.request("/api/v1/polls", {
+ const res = await app.request("/v1/polls", {
method: "PUT",
headers: authed,
});
@@ -2766,7 +2821,7 @@ describe("API v1 - /polls", () => {
onTestFinished(() => errorSpy.mockRestore());
mockGetPollWithOptions.mockRejectedValue(new TypeError("db exploded"));
- const res = await app.request("/api/v1/polls/test-poll-id", {
+ const res = await app.request("/v1/polls/test-poll-id", {
method: "GET",
headers: authed,
});
@@ -2791,7 +2846,7 @@ describe("API v1 - /polls", () => {
});
it("should document the full error code list in the spec", async () => {
- const res = await app.request("/api/v1/openapi");
+ const res = await app.request("/v1/openapi");
const json = await res.json();
for (const code of [
diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.ts
index 0261a8986..444291194 100644
--- a/apps/web/src/app/api/v1/[...route]/route.ts
+++ b/apps/web/src/app/api/v1/[...route]/route.ts
@@ -1,7 +1,6 @@
import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
-import { handle } from "hono/vercel";
import {
describeRoute,
generateSpecs,
@@ -66,7 +65,10 @@ type Env = {
};
};
-const app = new Hono<Env>().basePath("/api/v1");
+// The public URL has no `/api` prefix (https://api.rallly.co/v1/...), which
+// is also what a standalone API deployment would serve, so Hono mounts at
+// `/v1`. See `handler` below for how the app host's `/api/v1` reaches it.
+const app = new Hono<Env>().basePath("/v1");
// Process-wide: hono-openapi keys converters by schema vendor, and every zod
// schema reports "zod". Schemas without native `.meta()` ids convert exactly as
@@ -124,7 +126,7 @@ function toPollResponseBody(poll: {
title: poll.title,
description: poll.description,
location: poll.location,
- timezone: poll.timeZone,
+ timeZone: poll.timeZone,
status: poll.status,
kind: poll.kind,
createdAt: poll.createdAt.toISOString(),
@@ -203,6 +205,22 @@ app.onError((error, c) => {
);
});
+const unauthorizedResponse = {
+ description:
+ "The API key is missing, invalid, expired or revoked. Includes a `WWW-Authenticate` header.",
+ headers: {
+ "WWW-Authenticate": {
+ description: "The bearer challenge, per RFC 6750.",
+ schema: { type: "string" as const },
+ },
+ },
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+};
+
const spaceNotProResponse = {
description:
"The space associated with the API key does not have a Pro subscription",
@@ -263,7 +281,7 @@ async function buildOpenApiSpec() {
"",
"## Dates and times",
"",
- "Every poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timezone` (or the viewer's) for display. Timestamps such as `createdAt` and `updatedAt` are always ISO 8601 instants in UTC.",
+ "Every poll has a `kind`. A `date` poll offers calendar days: each option carries a `date` in `YYYY-MM-DD` format, which is a floating date with no time component and no timezone, so never convert it through a timezone. A `time` poll offers time slots: each option carries a `startTime` as an ISO 8601 instant in UTC and a `duration` in minutes; convert `startTime` into the poll's `timeZone` (or the viewer's) for display. Timestamps such as `createdAt` and `updatedAt` are always ISO 8601 instants in UTC.",
"",
"## Request bodies",
"",
@@ -287,7 +305,7 @@ async function buildOpenApiSpec() {
"| 400 | `INVALID_AUTHORIZATION_HEADER` | The `Authorization` header is not `Bearer <key>` |",
"| 400 | `ORGANIZER_NOT_MEMBER` | The organizer email is not a member of the space |",
"| 400 | `TOO_MANY_OPTIONS` | More than the maximum number of poll options |",
- "| 400 | `DUPLICATE_DATES` | `dates` contains the same date more than once |",
+ "| 400 | `DUPLICATE_DATES` | `options.dates` contains the same date more than once |",
"| 400 | `NO_OPTIONS_GENERATED` | No slot generator produced a valid time slot |",
"| 401 | `UNAUTHORIZED` | The API key is missing, invalid, expired or revoked |",
"| 403 | `SPACE_NOT_PRO` | The space behind the key has no Pro subscription |",
@@ -299,7 +317,10 @@ async function buildOpenApiSpec() {
"| 500 | `INTERNAL_ERROR` | Unexpected failure; the request id is logged |",
].join("\n"),
},
- servers: [{ url: absoluteUrl() }],
+ // The public host serves `/v1/...` directly; without one the API is
+ // reachable under the app's `/api` prefix. Read from process.env like
+ // lib/maintenance.ts: `@/env` validates eagerly on import.
+ servers: [{ url: process.env.API_BASE_URL ?? absoluteUrl("/api") }],
components: {
securitySchemes: {
bearerAuth: {
@@ -314,7 +335,7 @@ async function buildOpenApiSpec() {
// hono-openapi's validator middleware owns the request body schema and
// overwrites any content set via describeRoute, so named examples have to
// be attached to the generated spec instead.
- const createPollRequestBody = spec.paths["/api/v1/polls"]?.post?.requestBody;
+ const createPollRequestBody = spec.paths["/v1/polls"]?.post?.requestBody;
if (createPollRequestBody && "content" in createPollRequestBody) {
const media = createPollRequestBody.content?.["application/json"];
if (media) {
@@ -323,7 +344,7 @@ async function buildOpenApiSpec() {
}
const patchPollRequestBody =
- spec.paths["/api/v1/polls/{pollId}"]?.patch?.requestBody;
+ spec.paths["/v1/polls/{pollId}"]?.patch?.requestBody;
if (patchPollRequestBody && "content" in patchPollRequestBody) {
const media = patchPollRequestBody.content?.["application/json"];
if (media) {
@@ -349,14 +370,78 @@ app.post(
tags: ["Polls"],
summary: "Create a poll",
description: [
- "Creates a new poll. Provide the poll options in one of two ways:",
+ "Creates a poll and responds with `201 Created` and the full poll, exactly as `GET /polls/:pollId` returns it. Share `inviteUrl` with participants. `options.kind` chooses what participants vote on: whole days or time slots. A poll has at most 100 options.",
+ "",
+ "## Date poll",
+ "",
+ 'Pass `kind: "date"` and `dates`, a list of `YYYY-MM-DD` values. Each becomes one all-day option. Dates are floating calendar days with no timezone, so never convert them through one. A repeated date fails with `DUPLICATE_DATES`.',
+ "",
+ "```json",
+ "{",
+ ' "title": "Team offsite",',
+ ' "options": {',
+ ' "kind": "date",',
+ ' "dates": ["2027-03-01", "2027-03-02", "2027-03-03"]',
+ " }",
+ "}",
+ "```",
+ "",
+ "## Time poll",
+ "",
+ 'Pass `kind: "time"` with a `duration` in minutes that every slot shares, the slots themselves as `times`, `generators` or both, and optionally a `timeZone` (an IANA zone the times are written in).',
+ "",
+ "### Explicit times",
+ "",
+ "Each ISO datetime string in `times` becomes one slot starting at that moment. A time with no offset, like `2027-03-01T09:00:00`, is wall clock time in `timeZone` when that is set and a floating time with no conversion otherwise; a time with an offset or `Z` is an absolute instant.",
+ "",
+ "```json",
+ "{",
+ ' "title": "Kickoff",',
+ ' "options": {',
+ ' "kind": "time",',
+ ' "duration": 60,',
+ ' "timeZone": "Europe/London",',
+ ' "times": ["2027-03-01T09:00:00", "2027-03-02T14:00:00"]',
+ " }",
+ "}",
+ "```",
+ "",
+ "### Slot generators",
"",
- "- `dates` — a list of calendar dates. Each date becomes an all-day option (date poll).",
- "- `slots` — time-based options that share a fixed `duration` in minutes. Each entry in `slots.times` is either an ISO datetime for an explicit slot, or a slot generator that expands into recurring slots within a time window across a date range. Generated slots start every `interval` minutes (defaults to `duration`) and must fit entirely between `startTime` and `endTime`.",
+ "Each object in `generators` expands into recurring slots from a schedule, so availability across days or weeks does not have to be listed slot by slot.",
"",
- "`dates` and `slots` are mutually exclusive, and a poll can have at most 100 options. See the request examples for common scenarios.",
+ "```json",
+ "{",
+ ' "title": "Interview availability",',
+ ' "options": {',
+ ' "kind": "time",',
+ ' "duration": 30,',
+ ' "timeZone": "America/New_York",',
+ ' "generators": [',
+ " {",
+ ' "startDate": "2027-03-01",',
+ ' "endDate": "2027-03-05",',
+ ' "days": ["mon", "tue", "wed", "thu", "fri"],',
+ ' "startTime": "09:00",',
+ ' "endTime": "12:00",',
+ ' "interval": 60',
+ " }",
+ " ]",
+ " }",
+ "}",
+ "```",
"",
- "Responds with `201 Created` and the full poll, including the settings and organizer exactly as `GET /polls/:pollId` returns them.",
+ "This produces 30 minute slots at 09:00, 10:00 and 11:00 New York time on each weekday from 1 to 5 March, fifteen options in all. Drop `interval` and the window fills with back to back slots at 09:00, 09:30, 10:00, 10:30, 11:00 and 11:30.",
+ "",
+ "| Field | Meaning |",
+ "| --- | --- |",
+ "| `startDate`, `endDate` | The date range, inclusive. Fewer than 366 days. |",
+ "| `days` | Days of the week to include: `mon` to `sun`. Other days in the range are skipped. |",
+ "| `startTime` | Earliest slot start on each day, `HH:mm` in `timeZone`. |",
+ "| `endTime` | End of the daily window. A slot is only generated if it ends by this time. |",
+ "| `interval` | Minutes between slot starts. Optional; defaults to `duration`, which gives back to back slots. |",
+ "",
+ "Generators are expanded when the poll is created and duplicate slots are removed. A request that would exceed 100 options fails with `TOO_MANY_OPTIONS`; a generator whose window fits no slot produces nothing, and if nothing in `times` or `generators` yields a slot the request fails with `NO_OPTIONS_GENERATED`.",
].join("\n"),
security: [{ bearerAuth: [] }],
responses: {
@@ -376,6 +461,7 @@ app.post(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -423,7 +509,7 @@ app.post(
option_count: poll.options.length,
has_location: !!poll.location,
has_description: !!poll.description,
- timezone: poll.timeZone,
+ timeZone: poll.timeZone,
muted: false,
},
});
@@ -439,7 +525,7 @@ app.post(
optionCount: poll.options.length,
hasLocation: !!poll.location,
hasDescription: !!poll.description,
- timezone: poll.timeZone,
+ timeZone: poll.timeZone,
requireParticipantEmail: input.requireEmail,
hideParticipants: input.hideParticipants,
hideScores: input.hideScores,
@@ -457,21 +543,23 @@ app.post(
after(() => flushPostHog());
};
- // Process dates (all-day options)
- if (input.dates) {
- if (input.dates.length > MAX_POLL_OPTIONS) {
+ const optionsInput = input.options;
+
+ if (optionsInput.kind === "date") {
+ const { dates } = optionsInput;
+ if (dates.length > MAX_POLL_OPTIONS) {
return c.json(
apiError(
"TOO_MANY_OPTIONS",
- `Too many options (${input.dates.length}). Maximum allowed is ${MAX_POLL_OPTIONS}.`,
+ `Too many options (${dates.length}). Maximum allowed is ${MAX_POLL_OPTIONS}.`,
),
400,
);
}
- const uniqueDates = [...new Set(input.dates)];
- if (uniqueDates.length < input.dates.length) {
- const duplicateCount = input.dates.length - uniqueDates.length;
+ const uniqueDates = [...new Set(dates)];
+ if (uniqueDates.length < dates.length) {
+ const duplicateCount = dates.length - uniqueDates.length;
return c.json(
apiError(
"DUPLICATE_DATES",
@@ -505,37 +593,25 @@ app.post(
return c.json(pollResponseSchema.parse(toPollResponseBody(poll)), 201);
}
- // Process slots (time-based options)
- if (!input.slots) {
- return c.json(
- apiError(
- "VALIDATION_ERROR",
- "Either 'dates' or 'slots' must be provided",
- ),
- 400,
- );
- }
-
- const slots = input.slots;
- const timeZone = slots.timezone;
+ const timeZone = optionsInput.timeZone;
+ const duration = optionsInput.duration;
- const duration = slots.duration;
- const times = Array.isArray(slots.times) ? slots.times : [slots.times];
-
- const timeSlots = times.flatMap((time) => {
- if (typeof time === "string") {
- return parseStartTime(time, timeZone, duration);
- }
- const slotGenerator: SlotGeneratorInput = {
- startDate: time.startDate,
- endDate: time.endDate,
- daysOfWeek: time.days,
- fromTime: time.startTime,
- toTime: time.endTime,
- interval: time.interval,
- };
- return generateTimeSlots(slotGenerator, timeZone, duration);
- });
+ const timeSlots = [
+ ...(optionsInput.times ?? []).map((time) =>
+ parseStartTime(time, timeZone, duration),
+ ),
+ ...(optionsInput.generators ?? []).flatMap((generator) => {
+ const slotGenerator: SlotGeneratorInput = {
+ startDate: generator.startDate,
+ endDate: generator.endDate,
+ daysOfWeek: generator.days,
+ fromTime: generator.startTime,
+ toTime: generator.endTime,
+ interval: generator.interval,
+ };
+ return generateTimeSlots(slotGenerator, timeZone, duration);
+ }),
+ ];
const options = dedupeTimeSlots(timeSlots);
@@ -610,6 +686,7 @@ app.get(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -655,6 +732,7 @@ app.get(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -712,6 +790,7 @@ app.patch(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -787,6 +866,7 @@ app.get(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -866,6 +946,7 @@ app.get(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -931,6 +1012,7 @@ app.delete(
},
},
},
+ 401: unauthorizedResponse,
403: spaceNotProResponse,
429: rateLimitExceededResponse,
503: serviceUnavailableResponse,
@@ -973,7 +1055,31 @@ app.delete(
export { app };
-export const GET = handle(app);
-export const POST = handle(app);
-export const PATCH = handle(app);
-export const DELETE = handle(app);
+const APP_PREFIX = "/api";
+
+// Requests reach this file two ways: on the public host as `/v1/...` (the
+// next.config rewrite keeps the original URL, so that is what arrives here)
+// and on the app host as `/api/v1/...`. Both must hit the same Hono routes,
+// so the app prefix is stripped before dispatch. The forwarded request is
+// built field by field: `new Request(url, request)` drops the method under
+// vitest.
+async function handler(request: Request) {
+ const url = new URL(request.url);
+ if (!url.pathname.startsWith(`${APP_PREFIX}/v1`)) {
+ return app.fetch(request);
+ }
+ url.pathname = url.pathname.slice(APP_PREFIX.length);
+ return app.fetch(
+ new Request(url, {
+ method: request.method,
+ headers: request.headers,
+ body: request.body,
+ duplex: "half",
+ } as RequestInit),
+ );
+}
+
+export const GET = handler;
+export const POST = handler;
+export const PATCH = handler;
+export const DELETE = handler;
diff --git a/apps/web/src/app/api/v1/examples.ts b/apps/web/src/app/api/v1/examples.ts
index 873585f69..073e28480 100644
--- a/apps/web/src/app/api/v1/examples.ts
+++ b/apps/web/src/app/api/v1/examples.ts
@@ -5,47 +5,48 @@ type CreatePollInput = z.input<typeof createPollInputSchema>;
type PatchPollInput = z.input<typeof patchPollInputSchema>;
export const createPollRequestExamples = {
- datePoll: {
+ "Date poll": {
summary: "Date poll (all-day options)",
description:
- "Use `dates` to let participants pick between calendar days. Each date becomes an all-day option.",
+ "Let participants pick between calendar days. Each date becomes an all-day option.",
value: {
title: "Team offsite",
description: "Which days work for a two day offsite?",
- dates: ["2026-08-03", "2026-08-04", "2026-08-05"],
+ options: {
+ kind: "date",
+ dates: ["2027-03-01", "2027-03-02", "2027-03-03"],
+ },
} satisfies CreatePollInput,
},
- timePoll: {
+ "Time poll with explicit times": {
summary: "Time poll (explicit times)",
description:
- "Use `slots` with ISO datetime strings to offer specific time slots. Datetimes without an offset are interpreted as wall-clock in the poll's `timezone` — the example below offers 09:00 and 14:00 in London. Append `Z` or an offset to specify an absolute instant instead.",
+ "Offer specific time slots. Datetimes without an offset are interpreted as wall-clock in `timeZone` — this example offers 09:00 and 14:00 in London. Append `Z` or an offset to specify an absolute instant instead.",
value: {
title: "Project kickoff",
location: "Zoom",
- slots: {
+ options: {
+ kind: "time",
duration: 60,
- timezone: "Europe/London",
- times: [
- "2026-08-03T09:00:00",
- "2026-08-03T14:00:00",
- "2026-08-04T09:00:00",
- ],
+ timeZone: "Europe/London",
+ times: ["2027-03-01T09:00:00", "2027-03-01T14:00:00"],
},
} satisfies CreatePollInput,
},
- slotGenerator: {
+ "Time poll with a slot generator": {
summary: "Time poll (slot generator)",
description:
- "Use a slot generator to expand recurring slots across a date range. This example generates 30 minute slots at 09:00, 10:00 and 11:00 (New York time) every weekday between 3-7 August.",
+ "Expand recurring slots across a date range. This example generates 30 minute slots at 09:00, 10:00 and 11:00 (New York time) every weekday from 1 to 5 March.",
value: {
title: "Interview availability",
- slots: {
+ options: {
+ kind: "time",
duration: 30,
- timezone: "America/New_York",
- times: [
+ timeZone: "America/New_York",
+ generators: [
{
- startDate: "2026-08-03",
- endDate: "2026-08-07",
+ startDate: "2027-03-01",
+ endDate: "2027-03-05",
days: ["mon", "tue", "wed", "thu", "fri"],
startTime: "09:00",
endTime: "12:00",
@@ -55,20 +56,21 @@ export const createPollRequestExamples = {
},
} satisfies CreatePollInput,
},
- mixedTimes: {
+ "Time poll mixing times and a generator": {
summary: "Time poll (explicit times + generator)",
description:
- "`slots.times` can mix ISO datetime strings and slot generators. When `interval` is omitted it defaults to `duration`, so this generator produces back to back 90 minute slots at 14:00 and 15:30 on Monday and Wednesday.",
+ "`times` and `generators` combine. When `interval` is omitted it defaults to `duration`, so this generator produces back to back 90 minute slots at 14:00 and 15:30 on Monday and Wednesday.",
value: {
title: "Product workshop",
- slots: {
+ options: {
+ kind: "time",
duration: 90,
- timezone: "Europe/Berlin",
- times: [
- "2026-08-01T10:00:00",
+ timeZone: "Europe/Berlin",
+ times: ["2027-03-06T10:00:00"],
+ generators: [
{
- startDate: "2026-08-03",
- endDate: "2026-08-05",
+ startDate: "2027-03-08",
+ endDate: "2027-03-10",
days: ["mon", "wed"],
startTime: "14:00",
endTime: "17:00",
@@ -80,7 +82,7 @@ export const createPollRequestExamples = {
};
export const patchPollRequestExamples = {
- close: {
+ "Close the poll": {
summary: "Close a poll",
description:
"Set `status` to `closed` once you have picked a date or no longer need the poll. Closing is idempotent and makes the results final.",
diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.ts
index c5d10c184..dec8872f8 100644
--- a/apps/web/src/app/api/v1/schemas.ts
+++ b/apps/web/src/app/api/v1/schemas.ts
@@ -5,24 +5,47 @@ import { timezoneSchema } from "@/lib/utils/timezone-schema";
export const dateSchema = z.iso.date().meta({
description: "Date in YYYY-MM-DD format",
- example: "2025-12-23",
+ example: "2027-03-01",
});
-export const timeSchema = z.iso.time().meta({
+export const timeSchema = z.iso.time({ precision: -1 }).meta({
description: "Time in HH:mm (24-hour) format",
example: "09:30",
});
export const slotGeneratorSchema = z
.strictObject({
- startDate: dateSchema,
- endDate: dateSchema,
- days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])),
- startTime: timeSchema,
- endTime: timeSchema,
+ startDate: dateSchema.meta({
+ description: "First day of the range to generate slots on, inclusive.",
+ example: "2027-03-01",
+ }),
+ endDate: dateSchema.meta({
+ description:
+ "Last day of the range, inclusive. The range must span fewer than 366 days.",
+ example: "2027-03-05",
+ }),
+ days: z
+ .array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]))
+ .min(1)
+ .meta({
+ description:
+ "Days of the week to generate slots on. Days in the range that are not listed are skipped.",
+ example: ["mon", "tue", "wed", "thu", "fri"],
+ }),
+ startTime: timeSchema.meta({
+ description:
+ "Earliest slot start on each day, as a wall clock time in `timeZone`.",
+ example: "09:00",
+ }),
+ endTime: timeSchema.meta({
+ description:
+ "End of the daily window. A slot is only generated if it ends at or before this time.",
+ example: "17:00",
+ }),
interval: z.number().int().min(15).max(1440).optional().meta({
- description: "Interval in minutes between slots. Defaults to duration.",
- example: 30,
+ description:
+ "Minutes between consecutive slot starts. Defaults to `duration`, which produces back to back slots.",
+ example: 60,
}),
})
// Reject over-long ranges up front rather than silently truncating at the
@@ -39,44 +62,70 @@ export const slotGeneratorSchema = z
path: ["endDate"],
},
)
- .meta({ id: "SlotGenerator" });
+ .meta({
+ id: "SlotGenerator",
+ title: "Slot generator",
+ description:
+ "Expands into one slot of `duration` minutes every `interval` minutes between `startTime` and `endTime`, on each listed day of the week between `startDate` and `endDate`. Slots that would not end by `endTime` are not generated.",
+ });
+
+const explicitTimeSchema = z.iso.datetime({ local: true, offset: true }).meta({
+ description:
+ "ISO datetime start time. A string without an offset is wall clock time in `timeZone` when that is set (`2027-03-01T09:00:00` with `timeZone: Europe/London` means 09:00 in London) and a floating time with no conversion otherwise. A string with an offset or `Z` is an absolute instant.",
+ example: "2027-03-01T09:00:00",
+});
-const slotsInputSchema = z
+const dateOptionsSchema = z
.strictObject({
+ kind: z.literal("date"),
+ dates: z
+ .array(z.iso.date())
+ .min(1)
+ .meta({
+ description:
+ "Calendar days to offer. Each becomes one all-day option. A day may appear once.",
+ example: ["2027-03-01", "2027-03-02", "2027-03-03"],
+ }),
+ })
+ .meta({
+ id: "DateOptions",
+ title: "Date poll",
+ description:
+ "Whole days. Dates are floating calendar days with no timezone, so never convert them through one.",
+ });
+
+const timeOptionsSchema = z
+ .strictObject({
+ kind: z.literal("time"),
duration: z.number().int().min(15).max(1440).meta({
- description: "Duration in minutes for each time slot",
+ description: "Length of every slot in minutes",
example: 30,
}),
- timezone: timezoneSchema.optional().meta({
+ timeZone: timezoneSchema.optional().meta({
description:
- "IANA timezone. Datetime strings without an offset are interpreted in this timezone. If omitted, offset-less datetimes are treated as floating times (no timezone conversion) and the poll has no timezone set.",
+ "IANA time zone the times are written in. Datetime strings without an offset are interpreted in this zone. If omitted, offset-less datetimes are floating times (no conversion) and the poll has no time zone.",
example: "Europe/London",
}),
- times: z
- .array(
- z.union([
- z.iso.datetime({ local: true, offset: true }).meta({
- description:
- "ISO datetime start time. Strings without an offset are interpreted as wall-clock in `timezone` (e.g. `2025-01-15T09:00:00` with `timezone: Europe/London` means 09:00 in London). Strings with an offset or `Z` are treated as absolute instants.",
- example: "2025-01-15T09:00:00",
- }),
- slotGeneratorSchema,
- ]),
- )
- .min(1)
- .meta({
- description:
- "Times to include. An array of ISO datetime strings and/or slot generators.",
- }),
+ times: z.array(explicitTimeSchema).min(1).optional().meta({
+ description: "Explicit slots, one per start time.",
+ }),
+ generators: z.array(slotGeneratorSchema).min(1).optional().meta({
+ description:
+ "Slot generators. Each expands into recurring slots from a schedule.",
+ }),
})
- .meta({ id: "SlotsInput" });
-
-const datesInputSchema = z
- .array(z.iso.date())
- .min(1)
+ .refine((data) => data.times || data.generators, {
+ message: "Provide 'times', 'generators' or both",
+ path: ["times"],
+ })
+ // The refinement above does not survive JSON Schema conversion. Stating it
+ // as an anyOf would make Mintlify render two identical "Time poll" variants,
+ // so the description carries it instead.
.meta({
- description: "Array of ISO dates for all-day options",
- example: ["2025-01-15", "2025-01-16", "2025-01-17"],
+ id: "TimeOptions",
+ title: "Time poll",
+ description:
+ "Time slots that share one duration. Provide `times`, `generators` or both. Duplicate slots are removed.",
});
// Strict so a misspelt or unsupported field fails loudly instead of being
@@ -130,14 +179,21 @@ export const createPollInputSchema = z
description:
"Organizer of the poll. Defaults to the space owner if not provided. The organizer must be a member of the space.",
}),
- dates: datesInputSchema.optional(),
- slots: slotsInputSchema.optional(),
- })
- .refine((data) => data.dates || data.slots, {
- message: "Either 'dates' or 'slots' must be provided",
- })
- .refine((data) => !(data.dates && data.slots), {
- message: "Cannot provide both 'dates' and 'slots'",
+ options: z
+ .discriminatedUnion("kind", [dateOptionsSchema, timeOptionsSchema], {
+ error: 'kind must be "date" or "time"',
+ })
+ .meta({
+ description:
+ "What participants vote on: whole days (`kind: date`) or time slots (`kind: time`).",
+ discriminator: {
+ propertyName: "kind",
+ mapping: {
+ date: "#/components/schemas/DateOptions",
+ time: "#/components/schemas/TimeOptions",
+ },
+ },
+ }),
})
.meta({ id: "CreatePollInput" });
@@ -222,10 +278,9 @@ export const pollOrganizerSchema = z
id: z.string().meta({ example: "cm3f7d1qa0000t2k9c6b8h4jr" }),
name: z.string().meta({ example: "John Doe" }),
email: z.email().meta({ example: "[email protected]" }),
- image: z
- .string()
- .nullable()
- .meta({ example: "https://example.com/avatar.jpg" }),
+ image: z.string().nullable().meta({
+ example: "https://cdn.rallly.co/avatars/cm3f7d1qa0000t2k9c6b8h4jr.jpg",
+ }),
})
.meta({ id: "PollOrganizer" });
@@ -237,7 +292,7 @@ const pollSchema = z
example: "Pick a time that works for everyone",
}),
location: z.string().nullable().meta({ example: "Zoom" }),
- timezone: z.string().nullable().meta({ example: "Europe/London" }),
+ timeZone: z.string().nullable().meta({ example: "Europe/London" }),
status: pollStatusSchema,
kind: pollKindSchema,
createdAt: z.iso.datetime().meta({ example: "2025-01-10T12:00:00.000Z" }),
@@ -279,10 +334,10 @@ const pollSchema = z
options: z.array(pollOptionSchema),
adminUrl: z
.string()
- .meta({ example: "https://example.com/poll/Xk3pQ9vLm2Ab" }),
+ .meta({ example: "https://app.rallly.co/poll/Xk3pQ9vLm2Ab" }),
inviteUrl: z
.string()
- .meta({ example: "https://example.com/invite/Xk3pQ9vLm2Ab" }),
+ .meta({ example: "https://rallly.co/invite/Xk3pQ9vLm2Ab" }),
})
.meta({ id: "Poll" });
diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts
index ed671ff9e..3de6c8436 100644
--- a/apps/web/src/env.ts
+++ b/apps/web/src/env.ts
@@ -174,9 +174,12 @@ export const env = createEnv({
TURNSTILE_SECRET_KEY: z.string().optional(),
/**
* Base URL of the Rallly cloud API (e.g. https://api.rallly.co).
- * Set by the self-hosted Docker image so the instance can phone home for
- * update checks. Unset elsewhere — the features that depend on it no-op
- * when it's missing.
+ * On the cloud deployment it names the host that serves `/v1` without
+ * the app's `/api` prefix (see the rewrite in next.config.ts) and is
+ * the `servers` entry of the OpenAPI document. The self-hosted Docker
+ * image sets it so the instance can phone home for update checks.
+ * Unset elsewhere — the features that depend on it no-op when it's
+ * missing.
*/
API_BASE_URL: z.url().optional(),
},