update
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"$schema": "../../node_modules/oxlint/configuration_schema.json",
|
||||
"extends": ["../../.oxlintrc.json"],
|
||||
"ignorePatterns": ["dist"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
dist
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@repo/contracts",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsdown",
|
||||
"dev": "tsdown --watch --no-clean",
|
||||
"lint": "oxlint",
|
||||
"format": "prettier --write \"**/*.ts\"",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsdown": "^0.23.7",
|
||||
"typescript": "^6.0.2",
|
||||
"vitest": "^4.1.2"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from 'zod';
|
||||
import { userSummarySchema } from './users';
|
||||
|
||||
/**
|
||||
* A voice and video call. Any conversation or cauldron can have one: it
|
||||
* starts when the first person joins and is over when the last one leaves.
|
||||
*/
|
||||
export const callSchema = z.object({
|
||||
/** The conversation or cauldron it is in; there is one call per place. */
|
||||
conversationId: z.uuid(),
|
||||
/** Set when that place is a cauldron: its realm. */
|
||||
realmId: z.uuid().nullable(),
|
||||
/** Who is in it, in the order they joined. Empty once the call is over. */
|
||||
participants: z.array(userSummarySchema),
|
||||
startedAt: z.iso.datetime(),
|
||||
});
|
||||
export type Call = z.infer<typeof callSchema>;
|
||||
|
||||
/** GET /calls. */
|
||||
export const callsOverviewSchema = z.object({
|
||||
/** False when the server has no calls set up; nothing can be joined then. */
|
||||
enabled: z.boolean(),
|
||||
/** The calls going on in the user's conversations and cauldrons. */
|
||||
calls: z.array(callSchema),
|
||||
});
|
||||
export type CallsOverview = z.infer<typeof callsOverviewSchema>;
|
||||
|
||||
/**
|
||||
* POST /conversations/:id/call: what a browser needs to join the call
|
||||
* there, starting it if nobody is in it. The token lets this user alone
|
||||
* into this call alone, and only for the next few minutes.
|
||||
*/
|
||||
export const callAccessSchema = z.object({
|
||||
/** The media server's address. */
|
||||
url: z.string(),
|
||||
token: z.string(),
|
||||
});
|
||||
export type CallAccess = z.infer<typeof callAccessSchema>;
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ATTACHMENT_MAX_SIZE,
|
||||
createAttachmentSchema,
|
||||
createGroupSchema,
|
||||
GROUP_MAX_MEMBERS,
|
||||
reactionEmojiSchema,
|
||||
sendMessageSchema,
|
||||
} from './conversations';
|
||||
|
||||
describe('createGroupSchema', () => {
|
||||
it('trims the name and turns a blank one into null', () => {
|
||||
expect(
|
||||
createGroupSchema.parse({ name: ' Coven ', memberIds: ['a', 'b'] }),
|
||||
).toEqual({ name: 'Coven', memberIds: ['a', 'b'] });
|
||||
expect(
|
||||
createGroupSchema.parse({ name: ' ', memberIds: ['a', 'b'] }).name,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('needs at least two other people', () => {
|
||||
expect(createGroupSchema.safeParse({ memberIds: ['a'] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects the same person twice', () => {
|
||||
expect(
|
||||
createGroupSchema.safeParse({ memberIds: ['a', 'b', 'a'] }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves room for the creator under the member limit', () => {
|
||||
const ids = (count: number) =>
|
||||
Array.from({ length: count }, (_, index) => `user-${index}`);
|
||||
expect(
|
||||
createGroupSchema.safeParse({ memberIds: ids(GROUP_MAX_MEMBERS - 1) })
|
||||
.success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
createGroupSchema.safeParse({ memberIds: ids(GROUP_MAX_MEMBERS) })
|
||||
.success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sendMessageSchema', () => {
|
||||
const fileId = '019b0000-0000-7000-8000-000000000001';
|
||||
|
||||
it('accepts text, files or both', () => {
|
||||
expect(sendMessageSchema.parse({ content: ' hi ' })).toEqual({
|
||||
content: 'hi',
|
||||
attachmentIds: [],
|
||||
});
|
||||
expect(sendMessageSchema.parse({ attachmentIds: [fileId] })).toEqual({
|
||||
content: '',
|
||||
attachmentIds: [fileId],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a message with neither', () => {
|
||||
expect(sendMessageSchema.safeParse({ content: ' ' }).success).toBe(false);
|
||||
expect(sendMessageSchema.safeParse({}).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects the same file twice', () => {
|
||||
expect(
|
||||
sendMessageSchema.safeParse({ attachmentIds: [fileId, fileId] }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAttachmentSchema', () => {
|
||||
const file = { filename: 'cat.png', contentType: 'image/png', size: 1200 };
|
||||
|
||||
it('takes path separators out of the name', () => {
|
||||
expect(
|
||||
createAttachmentSchema.parse({ ...file, filename: '../etc/passwd' })
|
||||
.filename,
|
||||
).toBe('.._etc_passwd');
|
||||
});
|
||||
|
||||
it('rejects empty and oversized files', () => {
|
||||
expect(createAttachmentSchema.safeParse({ ...file, size: 0 }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
createAttachmentSchema.safeParse({
|
||||
...file,
|
||||
size: ATTACHMENT_MAX_SIZE + 1,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('wants both dimensions or neither', () => {
|
||||
expect(
|
||||
createAttachmentSchema.safeParse({ ...file, width: 10 }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
createAttachmentSchema.safeParse({ ...file, width: 10, height: 20 })
|
||||
.success,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reactionEmojiSchema', () => {
|
||||
it('accepts one emoji, however many code points it takes', () => {
|
||||
for (const emoji of ['👍', '❤️', '👨👩👧', '🇺🇦', '👋🏽']) {
|
||||
expect(reactionEmojiSchema.safeParse(emoji).success).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects text and more than one emoji', () => {
|
||||
for (const text of ['ok', '👍👍', '', ' 👍', '1']) {
|
||||
expect(reactionEmojiSchema.safeParse(text).success).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import { z } from 'zod';
|
||||
import { userIdSchema, userSummarySchema } from './users';
|
||||
|
||||
export const MESSAGE_MAX_LENGTH = 4000;
|
||||
export const MESSAGE_PAGE_SIZE = 50;
|
||||
export const GROUP_NAME_MAX_LENGTH = 100;
|
||||
/** Everyone in a group chat, the person who made it included. */
|
||||
export const GROUP_MAX_MEMBERS = 10;
|
||||
/** A new group needs this many people besides its creator. */
|
||||
export const GROUP_MIN_INVITED = 2;
|
||||
|
||||
/** Bytes: 10 MB per file. */
|
||||
export const ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024;
|
||||
export const ATTACHMENT_FILENAME_MAX_LENGTH = 255;
|
||||
export const MESSAGE_MAX_ATTACHMENTS = 5;
|
||||
/** Files someone may have uploaded and not sent yet. */
|
||||
export const PENDING_ATTACHMENTS_MAX = 20;
|
||||
/** Different emoji on one message; any number of people may share each. */
|
||||
export const MESSAGE_MAX_REACTIONS = 20;
|
||||
/** Unread counts stop here; show it as "99+". */
|
||||
export const UNREAD_COUNT_MAX = 100;
|
||||
/** The image types shown in the chat itself; anything else is a download. */
|
||||
export const INLINE_IMAGE_TYPES = [
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
];
|
||||
|
||||
export const conversationIdSchema = z.uuid();
|
||||
export const messageIdSchema = z.uuid();
|
||||
export const attachmentIdSchema = z.uuid();
|
||||
|
||||
/** A file posted with a message. Fetch it from GET /attachments/:id. */
|
||||
export const attachmentSchema = z.object({
|
||||
id: attachmentIdSchema,
|
||||
filename: z.string(),
|
||||
contentType: z.string(),
|
||||
/** Bytes. */
|
||||
size: z.number().int(),
|
||||
/** Pixels, for the image types shown in the chat; null for other files. */
|
||||
width: z.number().int().nullable(),
|
||||
height: z.number().int().nullable(),
|
||||
});
|
||||
export type Attachment = z.infer<typeof attachmentSchema>;
|
||||
|
||||
/** Whether an attachment is shown as a picture rather than as a download. */
|
||||
export function isInlineImage(attachment: Attachment): boolean {
|
||||
return (
|
||||
INLINE_IMAGE_TYPES.includes(attachment.contentType) &&
|
||||
attachment.width !== null &&
|
||||
attachment.height !== null
|
||||
);
|
||||
}
|
||||
|
||||
/** One emoji on a message and how many people chose it. */
|
||||
export const reactionSchema = z.object({
|
||||
emoji: z.string(),
|
||||
count: z.number().int(),
|
||||
/** Whether the signed-in user is one of them. */
|
||||
mine: z.boolean(),
|
||||
});
|
||||
export type Reaction = z.infer<typeof reactionSchema>;
|
||||
|
||||
export const messageSchema = z.object({
|
||||
/** Time-ordered: a later message always has a greater id. */
|
||||
id: messageIdSchema,
|
||||
conversationId: conversationIdSchema,
|
||||
/** Sent along so messages from people who have left still have a name. */
|
||||
author: userSummarySchema,
|
||||
/** May be empty when the message has attachments. */
|
||||
content: z.string(),
|
||||
/** In the order they were picked. */
|
||||
attachments: z.array(attachmentSchema),
|
||||
/** In the order each emoji was first used. */
|
||||
reactions: z.array(reactionSchema),
|
||||
createdAt: z.iso.datetime(),
|
||||
});
|
||||
export type Message = z.infer<typeof messageSchema>;
|
||||
|
||||
export const conversationSchema = z.object({
|
||||
id: conversationIdSchema,
|
||||
/**
|
||||
* "direct" is a one-to-one chat; "group" has a name, an owner and more
|
||||
* people. A realm's cauldrons hold messages too, but come with the realm.
|
||||
*/
|
||||
type: z.enum(['direct', 'group']),
|
||||
/** Groups only, and optional there: without one, show who is in it. */
|
||||
name: z.string().nullable(),
|
||||
/** Groups only: the member who may remove others. */
|
||||
ownerId: z.string().nullable(),
|
||||
/**
|
||||
* Everyone in it, the signed-in user included: a group's owner first, then
|
||||
* in the order they joined.
|
||||
*/
|
||||
members: z.array(userSummarySchema),
|
||||
lastMessage: messageSchema.nullable(),
|
||||
lastActivityAt: z.iso.datetime(),
|
||||
/**
|
||||
* Messages from other people the user hasn't read yet, counted up to
|
||||
* UNREAD_COUNT_MAX.
|
||||
*/
|
||||
unreadCount: z.number().int(),
|
||||
});
|
||||
export type Conversation = z.infer<typeof conversationSchema>;
|
||||
|
||||
export const conversationListSchema = z.array(conversationSchema);
|
||||
|
||||
/** Body of POST /conversations/direct: opens (or creates) the chat with a friend. */
|
||||
export const openDirectConversationSchema = z.object({ userId: userIdSchema });
|
||||
export type OpenDirectConversation = z.infer<
|
||||
typeof openDirectConversationSchema
|
||||
>;
|
||||
|
||||
/** Blank text clears the name. */
|
||||
export const groupNameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
GROUP_NAME_MAX_LENGTH,
|
||||
`Name must be at most ${GROUP_NAME_MAX_LENGTH} characters.`,
|
||||
)
|
||||
.transform((name) => (name === '' ? null : name))
|
||||
.nullable();
|
||||
|
||||
const uniqueUserIds = z
|
||||
.array(userIdSchema)
|
||||
.refine((ids) => new Set(ids).size === ids.length, {
|
||||
message: 'The same person is listed twice.',
|
||||
});
|
||||
|
||||
/** Body of POST /conversations/group. */
|
||||
export const createGroupSchema = z.object({
|
||||
name: groupNameSchema.optional(),
|
||||
/** Friends to start it with; the creator is added automatically. */
|
||||
memberIds: uniqueUserIds
|
||||
.min(GROUP_MIN_INVITED, `Pick at least ${GROUP_MIN_INVITED} friends.`)
|
||||
.max(
|
||||
GROUP_MAX_MEMBERS - 1,
|
||||
`A group can have at most ${GROUP_MAX_MEMBERS} people.`,
|
||||
),
|
||||
});
|
||||
export type CreateGroup = z.infer<typeof createGroupSchema>;
|
||||
|
||||
/** Body of PATCH /conversations/:id. */
|
||||
export const updateGroupSchema = z.object({ name: groupNameSchema });
|
||||
export type UpdateGroup = z.infer<typeof updateGroupSchema>;
|
||||
|
||||
/** Body of POST /conversations/:id/members. */
|
||||
export const addGroupMembersSchema = z.object({
|
||||
userIds: uniqueUserIds
|
||||
.min(1, 'Pick at least one friend.')
|
||||
.max(GROUP_MAX_MEMBERS - 1),
|
||||
});
|
||||
export type AddGroupMembers = z.infer<typeof addGroupMembersSchema>;
|
||||
|
||||
/**
|
||||
* Body of POST /attachments, sent before the file itself: the answer says
|
||||
* where to send the bytes.
|
||||
*/
|
||||
export const createAttachmentSchema = z
|
||||
.object({
|
||||
filename: z
|
||||
.string()
|
||||
// Path separators and control characters never belong in a name.
|
||||
.transform((name) => name.replace(/[\p{Cc}/\\]/gu, '_').trim())
|
||||
.pipe(
|
||||
z
|
||||
.string()
|
||||
.min(1, 'The file needs a name.')
|
||||
.max(
|
||||
ATTACHMENT_FILENAME_MAX_LENGTH,
|
||||
`File names can be at most ${ATTACHMENT_FILENAME_MAX_LENGTH} characters.`,
|
||||
),
|
||||
),
|
||||
/** As the browser reports it, e.g. "image/png". */
|
||||
contentType: z
|
||||
.string()
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.max(100)
|
||||
.regex(
|
||||
/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/,
|
||||
'Not a file type.',
|
||||
),
|
||||
size: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1, 'The file is empty.')
|
||||
.max(
|
||||
ATTACHMENT_MAX_SIZE,
|
||||
`Files can be at most ${ATTACHMENT_MAX_SIZE / 1024 / 1024} MB.`,
|
||||
),
|
||||
/** Pixels, for pictures: lets the chat keep room for them as they load. */
|
||||
width: z.number().int().min(1).max(20_000).optional(),
|
||||
height: z.number().int().min(1).max(20_000).optional(),
|
||||
})
|
||||
.refine(
|
||||
(file) => (file.width === undefined) === (file.height === undefined),
|
||||
{
|
||||
message: 'Give both the width and the height, or neither.',
|
||||
},
|
||||
);
|
||||
export type CreateAttachment = z.infer<typeof createAttachmentSchema>;
|
||||
|
||||
/** What POST /attachments answers with. */
|
||||
export const attachmentUploadSchema = z.object({
|
||||
attachment: attachmentSchema,
|
||||
/**
|
||||
* Send the file's bytes here, with exactly these headers and no cookies.
|
||||
* Then list the attachment's id in the message it belongs to.
|
||||
*/
|
||||
upload: z.object({
|
||||
url: z.url(),
|
||||
method: z.literal('PUT'),
|
||||
headers: z.record(z.string(), z.string()),
|
||||
}),
|
||||
});
|
||||
export type AttachmentUpload = z.infer<typeof attachmentUploadSchema>;
|
||||
|
||||
/** Body of POST /conversations/:id/messages: text, files or both. */
|
||||
export const sendMessageSchema = z
|
||||
.object({
|
||||
content: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
MESSAGE_MAX_LENGTH,
|
||||
`Message must be at most ${MESSAGE_MAX_LENGTH} characters.`,
|
||||
)
|
||||
.default(''),
|
||||
/** Files uploaded through POST /attachments and not sent yet. */
|
||||
attachmentIds: z
|
||||
.array(attachmentIdSchema)
|
||||
.max(
|
||||
MESSAGE_MAX_ATTACHMENTS,
|
||||
`A message can have at most ${MESSAGE_MAX_ATTACHMENTS} files.`,
|
||||
)
|
||||
.refine((ids) => new Set(ids).size === ids.length, {
|
||||
message: 'The same file is listed twice.',
|
||||
})
|
||||
.default([]),
|
||||
})
|
||||
.refine(
|
||||
(message) => message.content !== '' || message.attachmentIds.length > 0,
|
||||
{ path: ['content'], message: 'Message is empty.' },
|
||||
);
|
||||
export type SendMessage = z.infer<typeof sendMessageSchema>;
|
||||
|
||||
let emojiPattern: RegExp | undefined;
|
||||
|
||||
/** Whether the text is exactly one emoji, as people see it. */
|
||||
export function isEmoji(text: string): boolean {
|
||||
try {
|
||||
// The "v" flag knows whole emoji (flags, families, skin tones). Built on
|
||||
// first use, so an engine without it can still load this module.
|
||||
emojiPattern ??= new RegExp('^\\p{RGI_Emoji}$', 'v');
|
||||
} catch {
|
||||
emojiPattern = /^\p{Extended_Pictographic}/u;
|
||||
}
|
||||
return emojiPattern.test(text);
|
||||
}
|
||||
|
||||
/** The emoji in PUT and DELETE /conversations/:id/messages/:messageId/reactions/:emoji. */
|
||||
export const reactionEmojiSchema = z
|
||||
.string()
|
||||
.max(32)
|
||||
.refine(isEmoji, { message: 'Reactions are single emoji.' });
|
||||
|
||||
/** What the "reaction:changed" event carries. */
|
||||
export const reactionChangeSchema = z.object({
|
||||
conversationId: conversationIdSchema,
|
||||
messageId: messageIdSchema,
|
||||
emoji: z.string(),
|
||||
/** How many people have chosen this emoji now; 0 when no one is left. */
|
||||
count: z.number().int(),
|
||||
/** Who added or took back their reaction. */
|
||||
userId: z.string(),
|
||||
added: z.boolean(),
|
||||
});
|
||||
export type ReactionChange = z.infer<typeof reactionChangeSchema>;
|
||||
|
||||
/** Body of PUT /conversations/:id/read: the newest message the user has seen. */
|
||||
/** A message that was deleted, as the "message:deleted" event carries it. */
|
||||
export const messageDeletionSchema = z.object({
|
||||
conversationId: z.uuid(),
|
||||
messageId: z.uuid(),
|
||||
/** Set when the message was in a cauldron: its realm. */
|
||||
realmId: z.uuid().nullable(),
|
||||
});
|
||||
export type MessageDeletion = z.infer<typeof messageDeletionSchema>;
|
||||
|
||||
export const markReadSchema = z.object({ messageId: messageIdSchema });
|
||||
export type MarkRead = z.infer<typeof markReadSchema>;
|
||||
|
||||
/** What PUT /conversations/:id/read answers and "conversation:read" carries. */
|
||||
export const conversationReadSchema = z.object({
|
||||
conversationId: conversationIdSchema,
|
||||
/** Set when the conversation is a realm's cauldron. */
|
||||
realmId: z.uuid().nullable(),
|
||||
/** What is still unread: messages that came after the one marked. */
|
||||
unreadCount: z.number().int(),
|
||||
});
|
||||
export type ConversationRead = z.infer<typeof conversationReadSchema>;
|
||||
|
||||
/** Query of GET /conversations/:id/messages. */
|
||||
export const listMessagesQuerySchema = z.object({
|
||||
/** Return messages older than this one; leave out for the newest. */
|
||||
before: messageIdSchema.optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(MESSAGE_PAGE_SIZE),
|
||||
});
|
||||
export type ListMessagesQuery = z.infer<typeof listMessagesQuerySchema>;
|
||||
|
||||
/** One page of history, newest message first. */
|
||||
export const messagePageSchema = z.object({
|
||||
items: z.array(messageSchema),
|
||||
/** Pass as `before` to get the next older page; null when there is none. */
|
||||
nextCursor: messageIdSchema.nullable(),
|
||||
});
|
||||
export type MessagePage = z.infer<typeof messagePageSchema>;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod';
|
||||
import { userSummarySchema, usernameSchema } from './users';
|
||||
|
||||
/** A request that has not been answered yet. */
|
||||
export const friendRequestSchema = z.object({
|
||||
/** The other person: who sent it (incoming) or who it went to (outgoing). */
|
||||
user: userSummarySchema,
|
||||
createdAt: z.iso.datetime(),
|
||||
});
|
||||
export type FriendRequest = z.infer<typeof friendRequestSchema>;
|
||||
|
||||
/** Response of GET /friends. */
|
||||
export const friendsOverviewSchema = z.object({
|
||||
friends: z.array(userSummarySchema),
|
||||
incoming: z.array(friendRequestSchema),
|
||||
outgoing: z.array(friendRequestSchema),
|
||||
/**
|
||||
* People the user blocked: they can't send the user friend requests, and
|
||||
* so can't message or call them directly.
|
||||
*/
|
||||
blocked: z.array(userSummarySchema),
|
||||
});
|
||||
export type FriendsOverview = z.infer<typeof friendsOverviewSchema>;
|
||||
|
||||
/** Body of POST /friends/requests. */
|
||||
export const sendFriendRequestSchema = z.object({ username: usernameSchema });
|
||||
export type SendFriendRequest = z.infer<typeof sendFriendRequestSchema>;
|
||||
|
||||
/**
|
||||
* Response of POST /friends/requests. "accepted" means the other person had
|
||||
* already asked, so the two are friends straight away.
|
||||
*/
|
||||
export const friendRequestResultSchema = z.object({
|
||||
status: z.enum(['pending', 'accepted']),
|
||||
user: userSummarySchema,
|
||||
});
|
||||
export type FriendRequestResult = z.infer<typeof friendRequestResultSchema>;
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from './calls';
|
||||
export * from './conversations';
|
||||
export * from './friends';
|
||||
export * from './realms';
|
||||
export * from './realtime';
|
||||
export * from './users';
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createInviteSchema,
|
||||
createRoleSchema,
|
||||
hasPermissions,
|
||||
inviteCodeSchema,
|
||||
} from './realms';
|
||||
|
||||
describe('createRoleSchema', () => {
|
||||
it('rejects unknown and repeated permissions', () => {
|
||||
expect(
|
||||
createRoleSchema.safeParse({ name: 'Mod', permissions: ['banEveryone'] })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
createRoleSchema.safeParse({
|
||||
name: 'Mod',
|
||||
permissions: ['kickMembers', 'kickMembers'],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createInviteSchema', () => {
|
||||
it('defaults to a week and no limit on uses', () => {
|
||||
expect(createInviteSchema.parse({})).toEqual({
|
||||
expiresInDays: 7,
|
||||
maxUses: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('only takes the offered lifetimes', () => {
|
||||
expect(createInviteSchema.safeParse({ expiresInDays: 3 }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
createInviteSchema.parse({ expiresInDays: null }).expiresInDays,
|
||||
).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('inviteCodeSchema', () => {
|
||||
it('refuses anything that could not be a code', () => {
|
||||
expect(inviteCodeSchema.safeParse('abcDEF12_-xy').success).toBe(true);
|
||||
expect(inviteCodeSchema.safeParse('short').success).toBe(false);
|
||||
expect(inviteCodeSchema.safeParse('has/slash12').success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasPermissions', () => {
|
||||
it('needs every permission asked for', () => {
|
||||
expect(hasPermissions(['sendMessages'], [])).toBe(true);
|
||||
expect(hasPermissions(['sendMessages'], ['sendMessages'])).toBe(true);
|
||||
expect(
|
||||
hasPermissions(['sendMessages'], ['sendMessages', 'kickMembers']),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { z } from 'zod';
|
||||
import { userSummarySchema } from './users';
|
||||
|
||||
export const REALM_NAME_MAX_LENGTH = 50;
|
||||
export const CAULDRON_NAME_MAX_LENGTH = 50;
|
||||
export const ROLE_NAME_MAX_LENGTH = 30;
|
||||
export const REALM_MAX_CAULDRONS = 50;
|
||||
/** The built-in "Everyone" role included. */
|
||||
export const REALM_MAX_ROLES = 25;
|
||||
/** The cauldron every new realm starts with. */
|
||||
export const DEFAULT_CAULDRON_NAME = 'general';
|
||||
export const DEFAULT_ROLE_NAME = 'Everyone';
|
||||
|
||||
/**
|
||||
* What a member of a realm may do beyond reading it. A member has the
|
||||
* permissions of the "Everyone" role plus those of every role they were
|
||||
* given; the realm's owner has all of them.
|
||||
*/
|
||||
export const REALM_PERMISSIONS = [
|
||||
/** Rename the realm and see or revoke anyone's invites. */
|
||||
'manageRealm',
|
||||
/** Create, rename and delete cauldrons. */
|
||||
'manageCauldrons',
|
||||
/** Create, change, delete and hand out roles (never beyond one's own). */
|
||||
'manageRoles',
|
||||
/** Remove members (never someone who can do more than oneself). */
|
||||
'kickMembers',
|
||||
/** Ban members, under the same rule, and lift bans. */
|
||||
'banMembers',
|
||||
/** Make invite links. */
|
||||
'createInvites',
|
||||
/** Post in cauldrons and join their calls. */
|
||||
'sendMessages',
|
||||
/** Delete other people's messages. */
|
||||
'manageMessages',
|
||||
] as const;
|
||||
export const realmPermissionSchema = z.enum(REALM_PERMISSIONS);
|
||||
export type RealmPermission = z.infer<typeof realmPermissionSchema>;
|
||||
|
||||
/** What the "Everyone" role of a new realm allows. */
|
||||
export const DEFAULT_MEMBER_PERMISSIONS: RealmPermission[] = [
|
||||
'createInvites',
|
||||
'sendMessages',
|
||||
];
|
||||
|
||||
export const realmIdSchema = z.uuid();
|
||||
export const roleIdSchema = z.uuid();
|
||||
|
||||
const nameSchema = (what: string, max: number) =>
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, `${what} is required.`)
|
||||
.max(max, `${what} must be at most ${max} characters.`);
|
||||
|
||||
export const realmNameSchema = nameSchema('Name', REALM_NAME_MAX_LENGTH);
|
||||
export const cauldronNameSchema = nameSchema('Name', CAULDRON_NAME_MAX_LENGTH);
|
||||
export const roleNameSchema = nameSchema('Name', ROLE_NAME_MAX_LENGTH);
|
||||
|
||||
export const realmPermissionsSchema = z
|
||||
.array(realmPermissionSchema)
|
||||
.refine((list) => new Set(list).size === list.length, {
|
||||
message: 'The same permission is listed twice.',
|
||||
});
|
||||
|
||||
/** A realm as it appears in the list of realms someone is in. */
|
||||
export const realmSummarySchema = z.object({
|
||||
id: realmIdSchema,
|
||||
name: z.string(),
|
||||
ownerId: z.string(),
|
||||
});
|
||||
export type RealmSummary = z.infer<typeof realmSummarySchema>;
|
||||
|
||||
/** A realm in GET /realms. */
|
||||
export const realmListItemSchema = realmSummarySchema.extend({
|
||||
/** Whether any of its cauldrons has messages the user hasn't read. */
|
||||
hasUnread: z.boolean(),
|
||||
});
|
||||
export type RealmListItem = z.infer<typeof realmListItemSchema>;
|
||||
export const realmListSchema = z.array(realmListItemSchema);
|
||||
|
||||
/** A room of a realm. Its id is also its conversation id, for messages. */
|
||||
export const cauldronSchema = z.object({
|
||||
id: z.uuid(),
|
||||
name: z.string(),
|
||||
});
|
||||
export type Cauldron = z.infer<typeof cauldronSchema>;
|
||||
|
||||
/** A cauldron as it comes with its realm. */
|
||||
export const realmCauldronSchema = cauldronSchema.extend({
|
||||
/**
|
||||
* Messages from other people the user hasn't read yet, counted up to
|
||||
* UNREAD_COUNT_MAX.
|
||||
*/
|
||||
unreadCount: z.number().int(),
|
||||
});
|
||||
export type RealmCauldron = z.infer<typeof realmCauldronSchema>;
|
||||
|
||||
export const realmRoleSchema = z.object({
|
||||
id: roleIdSchema,
|
||||
name: z.string(),
|
||||
permissions: z.array(realmPermissionSchema),
|
||||
/** The "Everyone" role: all members have it; it can't be deleted or renamed. */
|
||||
isDefault: z.boolean(),
|
||||
});
|
||||
export type RealmRole = z.infer<typeof realmRoleSchema>;
|
||||
|
||||
/** A realm as its members see it. */
|
||||
export const realmSchema = realmSummarySchema.extend({
|
||||
/** Oldest first. */
|
||||
cauldrons: z.array(realmCauldronSchema),
|
||||
/** "Everyone" first, then oldest first. */
|
||||
roles: z.array(realmRoleSchema),
|
||||
memberCount: z.number().int(),
|
||||
/** What the signed-in user may do here. */
|
||||
permissions: z.array(realmPermissionSchema),
|
||||
});
|
||||
export type Realm = z.infer<typeof realmSchema>;
|
||||
|
||||
export const realmMemberSchema = z.object({
|
||||
user: userSummarySchema,
|
||||
/** Roles they were given; the "Everyone" role is not listed. */
|
||||
roleIds: z.array(roleIdSchema),
|
||||
joinedAt: z.iso.datetime(),
|
||||
});
|
||||
export type RealmMember = z.infer<typeof realmMemberSchema>;
|
||||
export const realmMemberListSchema = z.array(realmMemberSchema);
|
||||
|
||||
export const BAN_REASON_MAX_LENGTH = 200;
|
||||
|
||||
/** Body of PUT /realms/:id/bans/:userId. */
|
||||
export const banMemberSchema = z.object({
|
||||
/** For the people who run the realm; the banned person isn't shown it. */
|
||||
reason: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
BAN_REASON_MAX_LENGTH,
|
||||
`Reason must be at most ${BAN_REASON_MAX_LENGTH} characters.`,
|
||||
)
|
||||
.transform((reason) => (reason === '' ? null : reason))
|
||||
.nullable()
|
||||
.default(null),
|
||||
});
|
||||
export type BanMember = z.infer<typeof banMemberSchema>;
|
||||
export type BanMemberInput = z.input<typeof banMemberSchema>;
|
||||
|
||||
/** Someone who was put out of a realm and can't come back with an invite. */
|
||||
export const realmBanSchema = z.object({
|
||||
user: userSummarySchema,
|
||||
/** Null when that account is gone. */
|
||||
bannedBy: userSummarySchema.nullable(),
|
||||
reason: z.string().nullable(),
|
||||
createdAt: z.iso.datetime(),
|
||||
});
|
||||
export type RealmBan = z.infer<typeof realmBanSchema>;
|
||||
export const realmBanListSchema = z.array(realmBanSchema);
|
||||
|
||||
/** Body of POST /realms. */
|
||||
export const createRealmSchema = z.object({ name: realmNameSchema });
|
||||
export type CreateRealm = z.infer<typeof createRealmSchema>;
|
||||
|
||||
/** Body of PATCH /realms/:id. */
|
||||
export const updateRealmSchema = z.object({ name: realmNameSchema });
|
||||
export type UpdateRealm = z.infer<typeof updateRealmSchema>;
|
||||
|
||||
/** Body of POST /realms/:id/cauldrons and PATCH /realms/:id/cauldrons/:id. */
|
||||
export const cauldronInputSchema = z.object({ name: cauldronNameSchema });
|
||||
export type CauldronInput = z.infer<typeof cauldronInputSchema>;
|
||||
|
||||
/** Body of POST /realms/:id/roles. */
|
||||
export const createRoleSchema = z.object({
|
||||
name: roleNameSchema,
|
||||
permissions: realmPermissionsSchema,
|
||||
});
|
||||
export type CreateRole = z.infer<typeof createRoleSchema>;
|
||||
|
||||
/** Body of PATCH /realms/:id/roles/:roleId; only the fields sent change. */
|
||||
export const updateRoleSchema = createRoleSchema.partial();
|
||||
export type UpdateRole = z.infer<typeof updateRoleSchema>;
|
||||
|
||||
/** Body of PUT /realms/:id/members/:userId/roles: the full set to end up with. */
|
||||
export const setMemberRolesSchema = z.object({
|
||||
roleIds: z
|
||||
.array(roleIdSchema)
|
||||
.max(REALM_MAX_ROLES)
|
||||
.refine((ids) => new Set(ids).size === ids.length, {
|
||||
message: 'The same role is listed twice.',
|
||||
}),
|
||||
});
|
||||
export type SetMemberRoles = z.infer<typeof setMemberRolesSchema>;
|
||||
|
||||
export const INVITE_EXPIRY_DAYS = [1, 7, 30] as const;
|
||||
export const INVITE_MAX_USES_LIMIT = 100;
|
||||
export const inviteCodeSchema = z.string().regex(/^[A-Za-z0-9_-]{8,32}$/);
|
||||
|
||||
/** Body of POST /realms/:id/invites. */
|
||||
export const createInviteSchema = z.object({
|
||||
/** Null for a link that never expires. */
|
||||
expiresInDays: z
|
||||
.union(INVITE_EXPIRY_DAYS.map((days) => z.literal(days)))
|
||||
.nullable()
|
||||
.default(7),
|
||||
/** Null for no limit on how many people may use it. */
|
||||
maxUses: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(INVITE_MAX_USES_LIMIT)
|
||||
.nullable()
|
||||
.default(null),
|
||||
});
|
||||
export type CreateInvite = z.infer<typeof createInviteSchema>;
|
||||
export type CreateInviteInput = z.input<typeof createInviteSchema>;
|
||||
|
||||
export const realmInviteSchema = z.object({
|
||||
/** The secret part of the link the web app shares: /app/invite/<code>. */
|
||||
code: z.string(),
|
||||
realmId: realmIdSchema,
|
||||
createdBy: userSummarySchema,
|
||||
createdAt: z.iso.datetime(),
|
||||
expiresAt: z.iso.datetime().nullable(),
|
||||
maxUses: z.number().int().nullable(),
|
||||
uses: z.number().int(),
|
||||
});
|
||||
export type RealmInvite = z.infer<typeof realmInviteSchema>;
|
||||
export const realmInviteListSchema = z.array(realmInviteSchema);
|
||||
|
||||
/** What someone holding an invite link sees before joining. */
|
||||
export const invitePreviewSchema = z.object({
|
||||
code: z.string(),
|
||||
realm: z.object({
|
||||
id: realmIdSchema,
|
||||
name: z.string(),
|
||||
memberCount: z.number().int(),
|
||||
}),
|
||||
/** The signed-in user is in the realm already. */
|
||||
isMember: z.boolean(),
|
||||
/** The signed-in user was banned from it, so the invite won't let them in. */
|
||||
isBanned: z.boolean(),
|
||||
});
|
||||
export type InvitePreview = z.infer<typeof invitePreviewSchema>;
|
||||
|
||||
/** True when `permissions` has everything in `needed`. */
|
||||
export function hasPermissions(
|
||||
permissions: readonly RealmPermission[],
|
||||
needed: readonly RealmPermission[],
|
||||
): boolean {
|
||||
return needed.every((permission) => permissions.includes(permission));
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Call } from './calls';
|
||||
import type {
|
||||
ConversationRead,
|
||||
Message,
|
||||
MessageDeletion,
|
||||
ReactionChange,
|
||||
} from './conversations';
|
||||
|
||||
/**
|
||||
* Events the API pushes over the socket. Changes are always made with an
|
||||
* HTTP request; the socket only tells the other tabs and people about them.
|
||||
*/
|
||||
export interface ServerToClientEvents {
|
||||
/**
|
||||
* A message was posted in a conversation or cauldron the user can read
|
||||
* (their own messages too). `realmId` is set for a cauldron's message.
|
||||
*/
|
||||
'message:created': (
|
||||
message: Message,
|
||||
context: { realmId: string | null },
|
||||
) => void;
|
||||
/**
|
||||
* A message the user can read was deleted, by its author or by someone
|
||||
* who looks after the place.
|
||||
*/
|
||||
'message:deleted': (deletion: MessageDeletion) => void;
|
||||
/**
|
||||
* Someone added or took back a reaction on a message the user can read.
|
||||
* It carries the new count, so applying it twice does no harm.
|
||||
*/
|
||||
'reaction:changed': (change: ReactionChange) => void;
|
||||
/**
|
||||
* The user read a conversation or cauldron somewhere (this tab included):
|
||||
* its unread count is now this.
|
||||
*/
|
||||
'conversation:read': (read: ConversationRead) => void;
|
||||
/**
|
||||
* Someone joined or left the call in a conversation or cauldron the user
|
||||
* can read. No participants left means the call is over.
|
||||
*/
|
||||
'call:changed': (call: Call) => void;
|
||||
/**
|
||||
* A realm the user is (or just stopped being) in changed. "details" covers
|
||||
* its name, cauldrons, roles, what the user may do in it and whether they
|
||||
* are still in it: fetch GET /realms and GET /realms/:id again. "members"
|
||||
* is a change to who is in it or which roles they hold: fetch
|
||||
* GET /realms/:id (for the member count) and GET /realms/:id/members.
|
||||
*/
|
||||
'realm:changed': (realmId: string, what: 'details' | 'members') => void;
|
||||
/**
|
||||
* A conversation the user is (or just stopped being) in was created,
|
||||
* renamed or changed members; fetch GET /conversations again.
|
||||
*/
|
||||
'conversations:changed': () => void;
|
||||
/** The user's friends or friend requests changed; fetch GET /friends again. */
|
||||
'friends:changed': () => void;
|
||||
}
|
||||
|
||||
/** Nothing yet: clients only listen. */
|
||||
export type ClientToServerEvents = Record<string, never>;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { updateProfileSchema, usernameSchema } from './users';
|
||||
|
||||
describe('usernameSchema', () => {
|
||||
it('trims and lower-cases', () => {
|
||||
expect(usernameSchema.parse(' Alice_01 ')).toBe('alice_01');
|
||||
});
|
||||
|
||||
it.each(['ab', 'a'.repeat(31), 'has space', 'émile', 'semi;colon'])(
|
||||
'rejects %j',
|
||||
(value) => {
|
||||
expect(usernameSchema.safeParse(value).success).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('updateProfileSchema', () => {
|
||||
it('accepts a partial update', () => {
|
||||
expect(updateProfileSchema.parse({ name: ' Alice ' })).toEqual({
|
||||
name: 'Alice',
|
||||
});
|
||||
});
|
||||
|
||||
it('turns a blank bio into null', () => {
|
||||
expect(updateProfileSchema.parse({ bio: ' ' })).toEqual({ bio: null });
|
||||
});
|
||||
|
||||
it('rejects a blank name', () => {
|
||||
expect(updateProfileSchema.safeParse({ name: ' ' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('drops fields it does not know', () => {
|
||||
expect(updateProfileSchema.parse({ email: 'x@example.com' })).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const USERNAME_MIN_LENGTH = 3;
|
||||
export const USERNAME_MAX_LENGTH = 30;
|
||||
/** Checked after lower-casing, so "Alice" is accepted and stored as "alice". */
|
||||
export const USERNAME_PATTERN = /^[a-z0-9_.]+$/;
|
||||
export const NAME_MAX_LENGTH = 50;
|
||||
export const BIO_MAX_LENGTH = 190;
|
||||
|
||||
/** A unique handle, e.g. for finding someone to add as a friend. */
|
||||
export const usernameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.min(
|
||||
USERNAME_MIN_LENGTH,
|
||||
`Username must be at least ${USERNAME_MIN_LENGTH} characters.`,
|
||||
)
|
||||
.max(
|
||||
USERNAME_MAX_LENGTH,
|
||||
`Username must be at most ${USERNAME_MAX_LENGTH} characters.`,
|
||||
)
|
||||
.regex(
|
||||
USERNAME_PATTERN,
|
||||
'Username can only contain letters, numbers, underscores and dots.',
|
||||
);
|
||||
|
||||
/** The name shown next to someone's messages; not unique. */
|
||||
export const displayNameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'Name is required.')
|
||||
.max(NAME_MAX_LENGTH, `Name must be at most ${NAME_MAX_LENGTH} characters.`);
|
||||
|
||||
/** Blank text clears the bio. */
|
||||
export const bioSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(BIO_MAX_LENGTH, `Bio must be at most ${BIO_MAX_LENGTH} characters.`)
|
||||
.transform((bio) => (bio === '' ? null : bio))
|
||||
.nullable();
|
||||
|
||||
/** A user id as issued by the auth system (not a UUID). */
|
||||
export const userIdSchema = z.string().min(1).max(64);
|
||||
|
||||
/** Enough of a user to show them in a list or next to a message. */
|
||||
export const userSummarySchema = z.object({
|
||||
id: z.string(),
|
||||
/** Null only for an account that has not picked one yet. */
|
||||
username: z.string().nullable(),
|
||||
name: z.string(),
|
||||
image: z.string().nullable(),
|
||||
});
|
||||
export type UserSummary = z.infer<typeof userSummarySchema>;
|
||||
|
||||
/** What anyone signed in may see about a user. */
|
||||
export const publicProfileSchema = z.object({
|
||||
id: z.string(),
|
||||
username: z.string(),
|
||||
name: z.string(),
|
||||
bio: z.string().nullable(),
|
||||
image: z.string().nullable(),
|
||||
createdAt: z.iso.datetime(),
|
||||
});
|
||||
export type PublicProfile = z.infer<typeof publicProfileSchema>;
|
||||
|
||||
/** The signed-in user's own profile. */
|
||||
export const ownProfileSchema = publicProfileSchema.extend({
|
||||
/** Null until the user picks one (accounts created before usernames). */
|
||||
username: z.string().nullable(),
|
||||
email: z.string(),
|
||||
});
|
||||
export type OwnProfile = z.infer<typeof ownProfileSchema>;
|
||||
|
||||
/** Body of PATCH /users/me; only the fields sent are changed. */
|
||||
export const updateProfileSchema = z
|
||||
.object({
|
||||
name: displayNameSchema,
|
||||
username: usernameSchema,
|
||||
bio: bioSchema,
|
||||
})
|
||||
.partial();
|
||||
export type UpdateProfile = z.infer<typeof updateProfileSchema>;
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
entry: 'src/index.ts',
|
||||
format: 'esm',
|
||||
dts: true,
|
||||
});
|
||||
Reference in New Issue
Block a user