Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
18bee0a
Add the translator and English catalog that localization builds on
claude Nov 13, 2026
d5f43d9
Keep the message catalogs out of client files with a lint rule
claude Nov 13, 2026
287efb2
Merge branch 'main' into claude/issue-620-client-lint
richshaw Nov 13, 2026
1930b8a
Check the message catalogs in pnpm test
claude Nov 13, 2026
28a7b8b
Merge claude/issue-620-client-lint, which now has main with #889
claude Nov 13, 2026
a4559c0
Lint hard-coded text where it has moved to the catalogs
claude Nov 13, 2026
218b7d9
Merge branch 'main' into claude/issue-623-catalog-check
richshaw Nov 13, 2026
a7a10ed
Catch a select shown as a plain placeholder in the catalog check
claude Nov 13, 2026
4480055
Precompile the message catalogs at build time
claude Nov 13, 2026
701bd61
Merge branch 'claude/issue-623-catalog-check' into claude/issue-623-t…
claude Nov 14, 2026
dd50e3b
Merge branch 'main' into claude/issue-623-text-lint
richshaw Nov 14, 2026
20409b8
Give slot dates and times a language
claude Nov 14, 2026
18564d2
Escape backslashes too in filesAt's globs
claude Nov 14, 2026
9ca3cb6
Merge branch 'claude/issue-623-text-lint' into claude/issue-624-preco…
claude Nov 14, 2026
86a0365
Merge branch 'claude/issue-624-precompile' into claude/issue-622-slot…
claude Nov 14, 2026
1559802
Merge branch 'main' into claude/issue-624-precompile
claude Nov 14, 2026
ee870e1
Merge branch 'claude/issue-624-precompile' into claude/issue-622-slot…
claude Nov 14, 2026
325f17a
Merge branch 'main' into claude/issue-622-slot-format
richshaw Nov 14, 2026
d768b87
Give the other formatters a language
claude Nov 14, 2026
3c9b122
Merge branch 'claude/issue-622-slot-format' into claude/issue-622-oth…
claude Nov 14, 2026
40bb396
Give a signup a language and an instance a default one, with no visib…
claude Nov 14, 2026
07afbfd
Add a Signup language control to the Settings tab, hidden while one l…
claude Nov 14, 2026
a5d1fab
Keep the language rules out of the browser's view, so no page grows
claude Nov 14, 2026
efff208
Read any stored signup language leniently, and check the one sent as …
claude Nov 14, 2026
d53625b
Say plainly that DEFAULT_LOCALE accepts only en today
claude Nov 14, 2026
49db138
Keep the Signup language form in the Settings page's own file
claude Nov 14, 2026
a7f3825
Merge branch 'main' into claude/issue-625-signup-locale
claude Nov 14, 2026
f9e4103
Merge branch 'claude/issue-625-signup-locale' into claude/issue-625-s…
claude Nov 14, 2026
fe68bb1
Work out an organizer's language as pure logic, with no storage yet
claude Nov 14, 2026
bd3c442
Read a public signup's row once per request, through a cached loader
claude Nov 14, 2026
5ddc90f
Carry the organizer's saved language in the session and the token con…
claude Nov 14, 2026
afaf7be
Let an organizer save a language for new signups, hidden until a seco…
claude Nov 14, 2026
dd7ef70
Start new signups in their organizer's language, once there's a choice
claude Nov 14, 2026
e99765d
Let create_signup take a locale, else the organizer's language
claude Nov 14, 2026
1e53268
Have the public signup pages work out the signup's language
claude Nov 14, 2026
d0a8a6b
Find the signup's language on the not-found pages from the request path
claude Nov 14, 2026
522775f
Show a signup's language to AI assistants and the public API
claude Nov 14, 2026
8811cf2
Share one ship() test helper for languages that haven't shipped
claude Nov 14, 2026
39eb1eb
Take the footer's language and the Banner and BottomSheet labels as p…
claude Nov 14, 2026
855ea58
Move the public signup page's server-rendered text into the catalogs
claude Nov 14, 2026
8fcca7f
Give the sign-up dialog its messages from a client provider
claude Nov 14, 2026
c536029
Take the sign-up dialog's text and the error copy from the catalog
claude Nov 14, 2026
2e10c73
Add a partial Swedish catalog and a Swedish test signup
claude Nov 14, 2026
5911881
Give the edit and unsubscribe pages their signup's language
claude Nov 14, 2026
b3d5f3c
Fit the Swedish Spots label, and warn when the e2e locale hook is on
claude Nov 14, 2026
45c4dce
Take the edit, cancel and unsubscribe pages' text from the catalog
claude Nov 14, 2026
3aebf1d
Name the case of a refused sign-up or edit in details.reason
claude Nov 14, 2026
b94d806
Merge #914's final branch into #915
claude Nov 14, 2026
e9d6a14
Merge #915's branch into #916
claude Nov 14, 2026
05eba67
Find the edit form's Swedish Spots field by its new label
claude Nov 14, 2026
56ce1b3
Merge #916's branch into #917
claude Nov 14, 2026
eaa788a
Merge main into claude/issue-625-signup-locale
claude Nov 15, 2026
009a51b
Merge main (Next.js 15.5.29, #984, #806) into the client messages PR
claude Nov 15, 2026
3d90da2
Merge #897's final head into claude/issue-625-settings-control
claude Nov 15, 2026
271a335
Merge main: #897 landed as c1f13bd, same tree as its head
claude Nov 15, 2026
67dbde0
Raise the edit page budget for Next.js 15.5.29
claude Nov 15, 2026
0f5ae9d
Merge #899's final head into claude/issue-626-organizer-locale-core
claude Nov 15, 2026
e4c7170
Merge main: #899 landed as 1d2a721, same tree as its head
claude Nov 15, 2026
9d4ec17
Merge the client messages PR (main's Next.js 15.5.29, #984, #806) int…
claude Nov 15, 2026
1dee0ac
Raise the edit page budget for Next.js 15.5.29
claude Nov 15, 2026
2074a5f
Merge #901's final head into claude/issue-628-signup-row-loader
claude Nov 15, 2026
f1e9bb4
Merge main: #901 landed as c2fb12a, same tree as its head
claude Nov 15, 2026
f031cc5
Merge the dialog text PR (main's Next.js 15.5.29, #984, #806) into th…
claude Nov 15, 2026
1330c8e
Merge the Swedish seed PR (main's Next.js 15.5.29, #984, #806) into t…
claude Nov 15, 2026
47ec19d
Merge #902's final head into claude/issue-626-organizer-locale-column
claude Nov 15, 2026
d348453
Merge main: #902 landed as 9f39d58, same tree as its head
claude Nov 15, 2026
5487a05
Merge the edit page locale PR (main's Next.js 15.5.29, #984, #806) in…
claude Nov 16, 2026
4ccf859
Merge #903's final head into claude/issue-626-account-language
claude Nov 16, 2026
4dbb0cc
Merge main: #903 landed as f8dabd9, same tree as its head
claude Nov 16, 2026
a1fa37d
Merge the edit page text PR (main's Next.js 15.5.29, #984, #806) into…
claude Nov 16, 2026
084a0d4
Merge #904's final head into claude/issue-627-signup-starts-in-language
claude Nov 16, 2026
b31a87c
Merge main: #904 landed as e2b4f49, same tree as its head
claude Nov 16, 2026
fd3afe4
Merge #905's final head into claude/issue-627-mcp-create-locale
claude Nov 16, 2026
300bfc7
Merge main: #905 landed as 950f718, same tree as its head
claude Nov 16, 2026
0c3c170
Merge #906's final head into claude/issue-628-page-locale
claude Nov 16, 2026
02989f4
Merge main: #906 landed as 614a0d7, same tree as its head
claude Nov 16, 2026
b108a9b
Merge #907's final head into claude/issue-628-path-header
claude Nov 16, 2026
7797da1
Merge main: #907 landed as ba75aae, same tree as its head
claude Nov 16, 2026
07d80d2
Merge #908's final head into claude/issue-625-locale-in-api
claude Nov 16, 2026
9694d0d
Merge main: #908 landed as 80d071b, same tree as its head
claude Nov 16, 2026
7910cb1
Merge #909's final head into claude/issue-629-common
claude Nov 16, 2026
4320ec9
Merge main: #909 landed as debb086, same tree as its head
claude Nov 16, 2026
f242d12
Merge #910's final head into claude/issue-629-server-text
claude Nov 16, 2026
d9ec84e
Merge main: #910 landed as bda7dfd, same tree as its head
claude Nov 16, 2026
40116ab
Merge #911's final head into claude/issue-629-client-messages
claude Nov 16, 2026
17e8e0f
Merge main: #911 landed as 2f93094, same tree as its head
claude Nov 16, 2026
20a474d
Merge #912's final head into claude/issue-629-dialog-text
claude Nov 16, 2026
ac3e06f
Merge main: #912 landed as 2e2e314, same tree as its head
claude Nov 16, 2026
6c85da5
Merge #913's final head into claude/issue-629-swedish-seed
claude Nov 16, 2026
baefdf4
Merge main: #913 landed as 271e16d, same tree as its head
claude Nov 16, 2026
01f9d2b
Merge #914's final head into claude/issue-630-edit-page-locale
claude Nov 16, 2026
6a7d27e
Merge main: #914 landed as 9324bc0, same tree as its head
claude Nov 16, 2026
e97074e
Merge #915's final head into claude/issue-630-edit-page-text
claude Nov 16, 2026
b961f87
Merge main: #915 landed as c5ac17a, same tree as its head
claude Nov 16, 2026
54f38b7
Merge #916's final head into claude/issue-631-error-reasons
claude Nov 16, 2026
f58589b
Merge main: #916 landed as d492687, same tree as its head
claude Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ All notable changes to OpenSignup are documented here. Format follows [Keep a Ch

### Added

- Errors from signing up and from the edit link now name their case in `details.reason` where the code alone doesn't (#631), so the participant pages can word each one themselves, in the signup's language: `email_required`, `email_invalid`, `name_required`, `name_too_long`, `notes_too_long`, `quantity_too_small`, `quantity_too_large` and `quantity_not_whole`, all on `invalid_input` from `POST /api/slots/[id]/commitments` and `PATCH /api/commitments/[id]`. Reasons are a closed set, like the codes, and include the `refusal` and `asked_again` Magic Compose already sent. Nothing else in an error changes: `message` and `suggestion` stay in English for API callers, and an error that had no `details` gains one holding only `reason`. Other errors, the AI connector's tools' included, carry no reason, and a client should fall back on `code` for a reason it doesn't know. The pages show the same text as before for now.
- `DEFAULT_LOCALE`, an optional setting for the instance's language (#625), for an instance that serves one language community. Today it accepts `en` and `sv`, and neither changes anything, since English is the only language shipped so far: Swedish is being translated, and until it ships, `sv` leaves every page in English. Any other value stops the app like any other bad setting: the reminder worker exits at startup, and every page that needs the database fails, both with an "Invalid environment" error. A language becomes valid once its translation has begun, and takes effect once it ships. Then every signup without a language of its own follows the setting (today that is every signup), so `sv` set now switches them all to Swedish with the upgrade that ships it; left unset, each organizer's own language will apply. It's read when the app starts, not built in: "Branding your instance" in the README says where it goes on each platform. Signups can now hold a language too, in `settings.locale`: `POST /api/signups` and `PATCH /api/signups/[id]` take one that has shipped to participants (only `en` so far), refuse any other with `invalid_input` on `settings.locale`, and clear it on `null`. A language stored earlier that has since stopped shipping doesn't stop other changes to the signup. The signup's page, its sign-up sheet, the pages for changing or cancelling a spot and for turning reminders off, and the page a broken edit link shows, show their dates and wording in it, the footer aside (a page for a signup that doesn't exist, or was deleted, is in the instance's language); the signup's emails don't follow it yet. The AI connector's `get_signup`, and the results of `create_signup` (which takes one too, below) and `update_signup`, show it as saved, and `update_signup` takes one as the REST API does: refused with `invalid_input` on `settings.locale` unless it has shipped, cleared on `null`. `GET /api/public/signups/[slug]` gains `settings.locale`, the language the signup's page is in, so API clients can mark its content: the signup's own once that has shipped to participants, else the instance's (`en` today, whatever is stored).
- A place for each organizer's own language (#626): migration `0015` adds `organizers.locale`, an empty, nullable text column. Nothing sets it yet, and nothing anyone sees follows it. It's read with the rest of the organizer's account, on each of their pages and each request from their AI assistant, in the query that already ran there, so neither sends another statement to the database. A stored value is passed along as it is, so one that names no language can't stop anyone signing in.
- The privacy page now lists, among what an organizer's account holds, the language they choose for their new signups (#626). Account Settings has a "Language for new signups" choice for it, which appears only once a second language has shipped to participants and offers only those, so it isn't there yet. New signups don't follow it yet either.
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ Every mutation must go through this chain — route handlers stay thin:
Helpers used by every service:

- `src/lib/result.ts` — `Result<T, E>`, `ok`, `err`. Services return `Result`; route handlers convert to HTTP via `api-response.ts`.
- `src/lib/errors.ts` — `ServiceError` with `code` from a closed enum (`not_found | conflict | capacity_full | closed | forbidden | unauthorized | invalid_input | rate_limited | already_consumed | internal`), `httpStatusFor`, `fromZodError`, `ServiceException` (thrown by guards).
- `src/lib/errors.ts` — `ServiceError` with `code` from a closed enum (`not_found | conflict | capacity_full | closed | forbidden | unauthorized | invalid_input | rate_limited | already_consumed | internal`), `httpStatusFor`, `fromZodError`, `ServiceException` (thrown by guards). Where one code covers cases a client words differently, `details.reason` names the case from the closed `ErrorReason` set (documented on the type): a client keys its own text, in its own language, on code and reason, never on `message` or `suggestion`, which stay English for API callers. `fromZodError` takes a table of reasons by field path and Zod issue code (`COMMITMENT_INPUT_REASONS` beside the commitment schemas); an issue the table doesn't name gets none, and adding a reason never changes the error's other fields.
- `src/lib/parse.ts` — wraps Zod parsing into a `Result`.
- `src/lib/activity.ts` — `recordActivity(tx, …)` writes to the append-only activity log **inside the same transaction** as the mutation it describes. Telemetry-only events (no describing mutation) write outside a tx; see `src/lib/view-tracker.ts` and `safeRecordAttemptFailed` in `src/services/commitments.ts`.
- `src/lib/ids.ts` — UUIDv7 + base62 + 3–4 char type prefix (`sig_`, `slot_`, `org_`, `ws_`, `mem_`, `com_`, `par_`).
Expand Down
70 changes: 69 additions & 1 deletion src/app/api/commitments/[id]/route.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { workspaces } from '@/db/schema/workspaces';
import { getEmailTransport } from '@/email';
import { makeId } from '@/lib/ids';
import type { Actor } from '@/lib/policy';
import { NOTES_MAX_LENGTH, QUANTITY_MAX } from '@/lib/participant-limits';
import { PUBLIC_COMMITMENT_FIELDS } from '@/lib/public-commitment';
import { RateLimits } from '@/lib/rate-limit';
import {
Expand Down Expand Up @@ -431,6 +432,73 @@ describe('/api/commitments/[id] (db)', () => {
expect(limited).not.toBeNull();
expect(limited!.headers.get('Retry-After')).toMatch(/^\d+$/);
const payload = await limited!.json();
expect(payload.error.code).toBe('rate_limited');
// As it has always been: the code and its wait say it all, so no reason.
expect(payload).toEqual({
error: {
code: 'rate_limited',
message: 'too many requests',
suggestion: expect.stringMatching(/^wait \d+s and retry$/),
details: {
retryAfterSeconds: expect.any(Number),
bucket: RateLimits.commitmentTokenOpsPerIp.bucket,
},
},
});
expect(Object.keys(payload.error.details)).toEqual(['retryAfterSeconds', 'bucket']);
});

// The edit form words an `invalid_input` by its `details.reason`. The reason
// comes after the fields the API has always sent, which stay as they were,
// byte for byte, in English for API callers.
it.each([
[
'too many spots',
{ quantity: QUANTITY_MAX + 1 },
`{"error":{"code":"invalid_input","message":"Number must be less than or equal to ${QUANTITY_MAX}","field":"quantity","suggestion":"Check the value of \\"quantity\\"."}}`,
'quantity_too_large',
],
[
'notes too long',
{ notes: 'n'.repeat(NOTES_MAX_LENGTH + 1) },
`{"error":{"code":"invalid_input","message":"String must contain at most ${NOTES_MAX_LENGTH} character(s)","field":"notes","suggestion":"Check the value of \\"notes\\"."}}`,
'notes_too_long',
],
[
'a blank name',
{ name: '' },
'{"error":{"code":"invalid_input","message":"name is required","field":"name","suggestion":"Check the value of \\"name\\"."}}',
'name_required',
],
])('PATCH names %s in details.reason', async (_label, body, before, reason) => {
const c = await makeCommitment(fx);
const { req, ctx } = makeRequest(c.id, { method: 'PATCH', token: c.token, body });
const res = await PATCH(req, ctx);
expect(res.status).toBe(400);
expect(await res.text()).toBe(`${before.slice(0, -2)},"details":{"reason":"${reason}"}}}`);
});

// The edit link's other refusals: each code means one thing to the edit
// form, so they carry no reason and read exactly as they always have.
it('PATCH answers a bad token and an inactive sign-up as before, with no reason', async () => {
const c = await makeCommitment(fx);
const patch = async (token: string | undefined) => {
const { req, ctx } = makeRequest(c.id, { method: 'PATCH', token, body: { notes: 'x' } });
const res = await PATCH(req, ctx);
return [res.status, await res.text()];
};
expect(await patch(undefined)).toEqual([
403,
'{"error":{"code":"forbidden","message":"edit token required","field":"token"}}',
]);
expect(await patch('not-the-token')).toEqual([
403,
'{"error":{"code":"forbidden","message":"invalid edit token"}}',
]);
const { req, ctx } = makeRequest(c.id, { method: 'DELETE', token: c.token });
expect((await DELETE(req, ctx)).status).toBe(200);
expect(await patch(c.token)).toEqual([
409,
'{"error":{"code":"conflict","message":"commitment is not active","details":{"status":"cancelled"}}}',
]);
});
});
93 changes: 92 additions & 1 deletion src/app/api/slots/[id]/commitments/route.db.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { randomBytes } from 'node:crypto';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { and, eq } from 'drizzle-orm';
import { and, eq, inArray } from 'drizzle-orm';
import { NextRequest } from 'next/server';
import { getDb } from '@/db/client';
import { workspaceMembers } from '@/db/schema/members';
import { organizers } from '@/db/schema/organizers';
import { rateLimits } from '@/db/schema/rate-limits';
import { slots } from '@/db/schema/slots';
import { workspaces } from '@/db/schema/workspaces';
import type { ErrorReason } from '@/lib/errors';
import { makeId } from '@/lib/ids';
import type { Actor } from '@/lib/policy';
import { NAME_MAX_LENGTH } from '@/lib/participant-limits';
import { RateLimits } from '@/lib/rate-limit';
import { parseReturningCommits } from '@/lib/returning-participant';
import { createSignup, publishSignup } from '@/services/signups';
Expand Down Expand Up @@ -160,4 +162,93 @@ describe('POST /api/slots/[id]/commitments (db)', () => {
]);
}
});

// The sign-up sheet words an `invalid_input` by its `details.reason`. The
// reason comes after the fields the API has always sent, which stay as they
// were, byte for byte, in English for API callers.
describe('a refused sign-up', () => {
// Its own address, so these stay clear of the per-IP limit the tests above
// spend, and a fresh email each run for the per-address one.
const refusedIp = `2001:db8::1:${Math.floor(Math.random() * 0xffff).toString(16)}`;
const email = `pat-${randomBytes(4).toString('hex')}@localhost`;

afterAll(async () => {
await db
.delete(rateLimits)
.where(
and(
inArray(rateLimits.bucket, [
RateLimits.commitmentPerIp.bucket,
RateLimits.commitmentPerEmail.bucket,
]),
inArray(rateLimits.subject, [refusedIp, email]),
),
);
});

async function refuse(slotId: string, body: Record<string, unknown>) {
const req = new NextRequest(`http://localhost/api/slots/${slotId}/commitments`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-forwarded-for': refusedIp },
body: JSON.stringify(body),
});
const res = await POST(req, { params: Promise.resolve({ id: slotId }) });
return { status: res.status, text: await res.text() };
}

/** `before`, the body as it was, with `details.reason` added at the end. */
function withReason(before: string, reason: ErrorReason): string {
return `${before.slice(0, -2)},"details":{"reason":"${reason}"}}}`;
}

it('names an email that is not an address', async () => {
// The browser takes `pat@localhost` as an email; the server doesn't.
const refused = await refuse(await newSlot(null), { name: 'Robin Example', email });
expect(refused.status).toBe(400);
expect(refused.text).toBe(
withReason(
'{"error":{"code":"invalid_input","message":"Invalid email","field":"email","suggestion":"Check the value of \\"email\\"."}}',
'email_invalid',
),
);
});

it('names an email the signup asks for and did not get', async () => {
// The default settings ask for an email; this file's signup doesn't.
const asks = await createSignup(db, actor, workspaceId, {
title: 'Commit POST test, email required',
description: '',
tags: [],
visibility: 'unlisted' as const,
settings: {},
});
if (!asks.ok) throw new Error(asks.error.message);
const slot = await addSlot(db, actor, asks.value.id, { values: {}, capacity: 5 });
if (!slot.ok) throw new Error(slot.error.message);
const published = await publishSignup(db, actor, asks.value.id);
if (!published.ok) throw new Error(published.error.message);

const refused = await refuse(slot.value.id, { name: 'Robin Example', quantity: 1 });
expect(refused.status).toBe(400);
expect(refused.text).toBe(
withReason(
'{"error":{"code":"invalid_input","message":"Email is required for this signup.","field":"email","suggestion":"Add your email and try again."}}',
'email_required',
),
);
});

it('names a name that is too long', async () => {
const refused = await refuse(await newSlot(null), {
name: 'x'.repeat(NAME_MAX_LENGTH + 1),
});
expect(refused.status).toBe(400);
expect(refused.text).toBe(
withReason(
`{"error":{"code":"invalid_input","message":"String must contain at most ${NAME_MAX_LENGTH} character(s)","field":"name","suggestion":"Check the value of \\"name\\"."}}`,
'name_too_long',
),
);
});
});
});
3 changes: 2 additions & 1 deletion src/lib/api-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export interface ErrorEnvelope {
received?: unknown;
expected?: string;
suggestion?: string;
details?: Record<string, unknown>;
/** Attached data, and the error's `reason` when it has one (see `ErrorReason`). */
details?: ServiceError['details'];
};
}

Expand Down
53 changes: 53 additions & 0 deletions src/lib/errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
import { errorEnvelope } from './api-response';
import { err, ok } from './result';
import {
fromZodError,
Expand Down Expand Up @@ -53,6 +54,58 @@ describe('fromZodError', () => {
expect(err.suggestion).toBeDefined();
expect(err.details).toBeUndefined();
});

describe('with a table of reasons', () => {
const reasons = {
name: { too_small: 'name_required', too_big: 'name_too_long' },
count: { invalid_type: 'quantity_not_whole' },
} as const;

function issueOf(input: unknown) {
const parsed = schema.safeParse(input);
if (parsed.success) throw new Error('expected a parse failure');
return parsed.error;
}

it('gives the reason the table names for the first issue, by its field and code', () => {
expect(fromZodError(issueOf({ name: 'a', count: 1 }), reasons).details).toEqual({
reason: 'name_required',
});
expect(fromZodError(issueOf({ name: 'ab', count: 1.5 }), reasons).details).toEqual({
reason: 'quantity_not_whole',
});
// Both fields wrong: the reason is the first issue's, as `field` is.
const both = fromZodError(issueOf({ name: 'a', count: 1.5 }), reasons);
expect(both.field).toBe('name');
expect(both.details).toEqual({ reason: 'name_required' });
});

it('gives none for an issue the table does not name', () => {
// `name` lists too_small and too_big, not invalid_type; `count` lists no too_small.
expect(fromZodError(issueOf({ name: 123, count: 1 }), reasons).details).toBeUndefined();
expect(fromZodError(issueOf({ name: 'ab', count: -1 }), reasons).details).toBeUndefined();
// An issue on the whole input has no field to look up.
expect(fromZodError(issueOf('not an object'), reasons).details).toBeUndefined();
});

it('leaves every other field as it was, in the same order, adding details last', () => {
for (const input of [
{ name: 'a', count: 1 },
{ name: 'ab', count: 1.5 },
]) {
const error = issueOf(input);
const without = fromZodError(error);
const withReason = fromZodError(error, reasons);
const { details, ...rest } = withReason;
expect(rest).toEqual(without);
// The bytes an API caller gets: the same, with `details` added at the end.
const before = JSON.stringify(errorEnvelope(without));
expect(JSON.stringify(errorEnvelope(withReason))).toBe(
`${before.slice(0, -2)},"details":${JSON.stringify(details)}}}`,
);
}
});
});
});

describe('refusalAsResult', () => {
Expand Down
Loading
Loading