Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,324 @@
import { describe, expect, it } from "vitest";
import {
CHAT_EVENT_NAMES,
CHAT_MESSAGE_MAX_ATTACHMENTS,
CHAT_MESSAGE_MAX_BODY_LENGTH,
CHAT_MESSAGE_MAX_LINK_PREVIEWS,
CHAT_MESSAGE_MAX_MENTIONS,
isChatServerEvent,
isEphemeralChatEvent,
isPersistentChatEvent,
normalizeChatEventCursor,
normalizeChatResumeCursor,
parseChatResumeCursor,
validateChatServerEvent,
type ChatServerEvent,
} from "./chat-events.js";
const now = "2026-07-15T12:00:00.000Z";
const base = {
cursor: "stream_1:42",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: now,
};
const message = {
id: "message_1",
clientMessageId: "client_message_1",
authorUserId: "user_1",
body: "Hello team",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [{ type: "user", id: "user_2", label: "Ada" }],
attachmentIds: [],
linkPreviews: [],
createdAt: now,
updatedAt: now,
editedAt: null,
deletedAt: null,
} as const;
const systemMessage = {
...message,
id: "message_system_1",
clientMessageId: "system:project:project_1:created",
authorUserId: null,
body: "",
bodyFormat: "system",
mentions: [],
systemEvent: {
kind: "project_created",
metadata: { projectId: "project_1", projectNumber: "P-1001" },
},
} as const;
function persistent(event: string, data: unknown): Record<string, unknown> {
return { ...base, event, data };
}
function ephemeral(event: string, data: unknown): Record<string, unknown> {
return { ...base, event, cursor: null, data };
}
describe("chat server event contract", () => {
it("validates every persistent server event with a stable cursor", () => {
const events: unknown[] = [
persistent(CHAT_EVENT_NAMES.messageCreated, { message }),
persistent(CHAT_EVENT_NAMES.messageUpdated, { message: { ...message, body: "Edited", editedAt: now } }),
persistent(CHAT_EVENT_NAMES.messageDeleted, { messageId: "message_1", deletedByUserId: "user_1", deletedAt: now }),
persistent(CHAT_EVENT_NAMES.reactionAdded, {
reaction: { id: "reaction_1", messageId: "message_1", userId: "user_2", emoji: "👍", reactedAt: now },
}),
persistent(CHAT_EVENT_NAMES.reactionRemoved, { messageId: "message_1", userId: "user_2", emoji: "👍", removedAt: now }),
persistent(CHAT_EVENT_NAMES.threadReply, {
thread: { id: "thread_1", parentMessageId: "message_1", replyCount: 1, lastReplyAt: now, participantUserIds: ["user_2"] },
message: { ...message, id: "message_2", clientMessageId: "client_message_2", parentMessageId: "message_1" },
}),
persistent(CHAT_EVENT_NAMES.readReceipt, { messageId: "message_1", userId: "user_2", readAt: now }),
persistent(CHAT_EVENT_NAMES.memberAdded, { userId: "user_2", roleInChat: "member", joinedAt: now }),
persistent(CHAT_EVENT_NAMES.memberRemoved, { userId: "user_2", leftAt: now }),
persistent(CHAT_EVENT_NAMES.channelArchived, { archivedAt: now, reason: "manual" }),
persistent(CHAT_EVENT_NAMES.pinChanged, { messageId: "message_1", pinned: true, changedByUserId: "user_1" }),
persistent(CHAT_EVENT_NAMES.linkPreviewReady, {
messageId: "message_1",
linkPreviews: [{ url: "https://example.com/article", title: "Article", description: null, imageUrl: null, siteName: "Example" }],
}),
];
for (const event of events) {
const validated = validateChatServerEvent(event);
expect(validated.cursor).toBe(base.cursor);
expect(validated.tenantId).toBe(base.tenantId);
expect(isPersistentChatEvent(validated)).toBe(true);
expect(isEphemeralChatEvent(validated)).toBe(false);
}
});
it("discriminates system messages and permits an actorless automation entry", () => {
const validated = validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message: systemMessage }));
expect(validated.event).toBe(CHAT_EVENT_NAMES.messageCreated);
if (validated.event === CHAT_EVENT_NAMES.messageCreated) {
expect(validated.data.message).toEqual(systemMessage);
expect(validated.data.message.bodyFormat).toBe("system");
if (validated.data.message.bodyFormat === "system") {
expect(validated.data.message.authorUserId).toBeNull();
expect(validated.data.message.systemEvent.kind).toBe("project_created");
}
}
});
it("keeps markdown and system message payloads structurally separate", () => {
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...message, systemEvent: { kind: "project_created", metadata: {} } },
})
)
).toThrow(/markdown messages cannot carry systemEvent/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...systemMessage, systemEvent: undefined },
})
)
).toThrow(/systemEvent must be an object/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...systemMessage, authorUserId: 42 },
})
)
).toThrow(/authorUserId must be a string/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...systemMessage, mentions: [{ type: "user", id: "user_2", label: "Ada" }] },
})
)
).toThrow(/system messages cannot carry/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...systemMessage, systemEvent: { kind: "unsupported", metadata: {} } },
})
)
).toThrow(/kind must be supported/);
});
it("validates typing and all presence states as explicitly ephemeral", () => {
const events: unknown[] = [
ephemeral(CHAT_EVENT_NAMES.typingStarted, { userId: "user_1" }),
ephemeral(CHAT_EVENT_NAMES.typingStopped, { userId: "user_1" }),
ephemeral(CHAT_EVENT_NAMES.presenceOnline, { userId: "user_1", presence: "online" }),
ephemeral(CHAT_EVENT_NAMES.presenceAway, { userId: "user_1", presence: "away" }),
ephemeral(CHAT_EVENT_NAMES.presenceOffline, { userId: "user_1", presence: "offline" }),
];
for (const event of events) {
const validated = validateChatServerEvent(event);
expect(validated.cursor).toBeNull();
expect(isEphemeralChatEvent(validated)).toBe(true);
expect(isPersistentChatEvent(validated)).toBe(false);
}
});
it("requires cursors for persistent events and null cursors for ephemeral events", () => {
expect(() => validateChatServerEvent({ ...persistent(CHAT_EVENT_NAMES.messageCreated, { message }), cursor: null })).toThrow(/persistent cursor/);
expect(() => validateChatServerEvent({ ...ephemeral(CHAT_EVENT_NAMES.typingStarted, { userId: "user_1" }), cursor: "cursor_1" })).toThrow(
/cursor null.*ephemeral/
);
});
it("parses and normalizes stream-generation cursors", () => {
expect(parseChatResumeCursor("stream_1:42")).toEqual({ streamId: "stream_1", sequence: "42" });
expect(normalizeChatEventCursor("stream_1:42")).toBe("stream_1:42");
expect(normalizeChatResumeCursor("stream_1:42")).toBe("stream_1:42");
expect(parseChatResumeCursor("0")).toEqual({ streamId: null, sequence: "0" });
expect(normalizeChatResumeCursor("0")).toBe("0");
});
it("accepts the PostgreSQL BigInt maximum and rejects ambiguous cursors", () => {
const maximum = "stream_1:9223372036854775807";
expect(parseChatResumeCursor(maximum)).toEqual({ streamId: "stream_1", sequence: "9223372036854775807" });
expect(normalizeChatResumeCursor(maximum)).toBe(maximum);
const invalidCursors = [
"0042",
"stream_1:0042",
"stream_1:0",
"stream_1:42:extra",
":42",
"stream.1:42",
" stream_1:42",
"stream_1:42 ",
"stream_1:9223372036854775808",
`stream_1:${"9".repeat(10_000)}`,
];
for (const cursor of invalidCursors) {
expect(() => parseChatResumeCursor(cursor)).toThrow(/cursor/);
}
expect(() => validateChatServerEvent({ ...persistent(CHAT_EVENT_NAMES.messageCreated, { message }), cursor: "0" })).toThrow(/positive persisted sequence/);
expect(() => normalizeChatEventCursor("0")).toThrow(/positive persisted sequence/);
expect(() => parseChatResumeCursor(42)).toThrow(/cursor must be a string/);
});
it("requires tenant and chat scope on every event", () => {
const valid = persistent(CHAT_EVENT_NAMES.messageCreated, { message });
expect(() => validateChatServerEvent({ ...valid, tenantId: "" })).toThrow(/tenantId must not be empty/);
expect(() => validateChatServerEvent({ ...valid, chatId: undefined })).toThrow(/chatId must be a string/);
});
it("rejects unsupported envelope and nested data keys", () => {
expect(() => validateChatServerEvent({ ...persistent(CHAT_EVENT_NAMES.messageCreated, { message }), authorization: "Bearer secret" })).toThrow(
/unsupported key: authorization/
);
expect(() => validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message: { ...message, providerPayload: { secret: true } } }))).toThrow(
/unsupported key: providerPayload/
);
expect(() =>
validateChatServerEvent(persistent(CHAT_EVENT_NAMES.readReceipt, { messageId: "message_1", userId: "user_1", readAt: now, extra: true }))
).toThrow(/unsupported key: extra/);
});
it("enforces the message body, mention, attachment, and preview limits", () => {
expect(() =>
validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message: { ...message, body: "x".repeat(CHAT_MESSAGE_MAX_BODY_LENGTH + 1) } }))
).toThrow(/maximum length/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: {
...message,
mentions: Array.from({ length: CHAT_MESSAGE_MAX_MENTIONS + 1 }, (_, index) => ({ type: "user", id: `user_${index}`, label: null })),
},
})
)
).toThrow(/maximum item count/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageCreated, {
message: { ...message, attachmentIds: Array.from({ length: CHAT_MESSAGE_MAX_ATTACHMENTS + 1 }, (_, index) => `file_${index}`) },
})
)
).toThrow(/maximum item count/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.linkPreviewReady, {
messageId: "message_1",
linkPreviews: Array.from({ length: CHAT_MESSAGE_MAX_LINK_PREVIEWS + 1 }, (_, index) => ({
url: `https://example.com/${index}`,
title: null,
description: null,
imageUrl: null,
siteName: null,
})),
})
)
).toThrow(/maximum item count/);
});
it("allows attachment-only and deleted tombstone messages but rejects an empty live message", () => {
expect(() =>
validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message: { ...message, body: "", attachmentIds: ["file_1"] } }))
).not.toThrow();
const deleted = validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.messageUpdated, {
message: {
...message,
deletedAt: now,
attachmentIds: ["file_1"],
linkPreviews: [{ url: "https://example.com/private", title: "Private", description: null, imageUrl: null, siteName: null }],
},
})
);
expect(deleted.event).toBe(CHAT_EVENT_NAMES.messageUpdated);
if (deleted.event === CHAT_EVENT_NAMES.messageUpdated) {
expect(deleted.data.message).toMatchObject({ body: "", mentions: [], attachmentIds: [], linkPreviews: [] });
}
expect(() => validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message: { ...message, body: "" } }))).toThrow(
/body text or an attachment/
);
});
it("rejects unsafe preview URLs, mismatched presence values, and mismatched thread parents", () => {
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.linkPreviewReady, {
messageId: "message_1",
linkPreviews: [{ url: "javascript:alert(1)", title: null, description: null, imageUrl: null, siteName: null }],
})
)
).toThrow(/absolute HTTP URL/);
expect(() => validateChatServerEvent(ephemeral(CHAT_EVENT_NAMES.presenceOnline, { userId: "user_1", presence: "offline" }))).toThrow(/must be online/);
expect(() =>
validateChatServerEvent(
persistent(CHAT_EVENT_NAMES.threadReply, {
thread: { id: "thread_1", parentMessageId: "message_1", replyCount: 1, lastReplyAt: now, participantUserIds: ["user_2"] },
message: { ...message, id: "message_2", parentMessageId: "message_other" },
})
)
).toThrow(/event thread parent/);
});
it("provides a non-throwing type guard", () => {
const event = persistent(CHAT_EVENT_NAMES.messageCreated, { message });
expect(isChatServerEvent(event)).toBe(true);
expect(isChatServerEvent({ ...event, event: "message.unknown" })).toBe(false);
expect(isChatServerEvent(null)).toBe(false);
});
it("narrows persistent and ephemeral event unions", () => {
const events: ChatServerEvent[] = [
validateChatServerEvent(persistent(CHAT_EVENT_NAMES.messageCreated, { message })),
validateChatServerEvent(ephemeral(CHAT_EVENT_NAMES.typingStarted, { userId: "user_1" })),
];
expect(events.filter(isPersistentChatEvent)).toHaveLength(1);
expect(events.filter(isEphemeralChatEvent)).toHaveLength(1);
});
});
@@ -0,0 +1,858 @@
export const CHAT_EVENT_NAMES = {
messageCreated: "chat.message.created",
messageUpdated: "chat.message.updated",
messageDeleted: "chat.message.deleted",
reactionAdded: "chat.reaction.added",
reactionRemoved: "chat.reaction.removed",
threadReply: "chat.thread.reply",
readReceipt: "chat.read.updated",
typingStarted: "chat.typing.started",
typingStopped: "chat.typing.stopped",
presenceOnline: "chat.presence.online",
presenceAway: "chat.presence.away",
presenceOffline: "chat.presence.offline",
memberAdded: "chat.member.added",
memberRemoved: "chat.member.removed",
channelArchived: "chat.channel.archived",
pinChanged: "chat.message.pin_changed",
linkPreviewReady: "chat.link_preview.ready",
} as const;
export type ChatEventName = (typeof CHAT_EVENT_NAMES)[keyof typeof CHAT_EVENT_NAMES];
export type ChatConnectionPresence = "online" | "away" | "offline";
export type ChatMessageFormat = "markdown" | "system";
export type ChatMentionType = "user" | "project" | "contact" | "company";
export type ChatMemberRole = "admin" | "member";
export type ChatArchiveReason = "manual" | "project_completed" | "project_cancelled";
export const CHAT_SYSTEM_EVENT_KINDS = [
"group_created",
"project_created",
"project_leader_changed",
"member_write_access_changed",
"member_added",
"member_removed",
"channel_renamed",
"channel_privacy_changed",
"channel_archived",
"project_stage_changed",
"acceptance_completed",
"task_created",
] as const;
export type ChatSystemEventKind = (typeof CHAT_SYSTEM_EVENT_KINDS)[number];
export type ChatSystemEventMetadataValue =
| string
| number
| boolean
| null
| ChatSystemEventMetadataValue[]
| { [key: string]: ChatSystemEventMetadataValue };
export type ChatSystemEventMetadata = { [key: string]: ChatSystemEventMetadataValue };
export type ChatSystemEvent = {
kind: ChatSystemEventKind;
metadata: ChatSystemEventMetadata;
};
export const CHAT_MESSAGE_MAX_BODY_LENGTH = 8_000;
export const CHAT_MESSAGE_MAX_MENTIONS = 100;
export const CHAT_MESSAGE_MAX_ATTACHMENTS = 20;
export const CHAT_MESSAGE_MAX_LINK_PREVIEWS = 3;
export const CHAT_THREAD_MAX_PARTICIPANTS = 500;
const MAX_IDENTIFIER_LENGTH = 500;
const MAX_LABEL_LENGTH = 300;
const MAX_URL_LENGTH = 2_048;
const MAX_PREVIEW_DESCRIPTION_LENGTH = 1_000;
const MAX_EMOJI_LENGTH = 16;
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const CHAT_EVENT_SEQUENCE_PATTERN = /^[1-9]\d*$/;
const CHAT_STREAM_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
const CHAT_EVENT_CURSOR_MAX = 9_223_372_036_854_775_807n;
const PERSISTENT_CHAT_EVENTS = new Set<ChatEventName>([
CHAT_EVENT_NAMES.messageCreated,
CHAT_EVENT_NAMES.messageUpdated,
CHAT_EVENT_NAMES.messageDeleted,
CHAT_EVENT_NAMES.reactionAdded,
CHAT_EVENT_NAMES.reactionRemoved,
CHAT_EVENT_NAMES.threadReply,
CHAT_EVENT_NAMES.readReceipt,
CHAT_EVENT_NAMES.memberAdded,
CHAT_EVENT_NAMES.memberRemoved,
CHAT_EVENT_NAMES.channelArchived,
CHAT_EVENT_NAMES.pinChanged,
CHAT_EVENT_NAMES.linkPreviewReady,
]);
const EPHEMERAL_CHAT_EVENTS = new Set<ChatEventName>([
CHAT_EVENT_NAMES.typingStarted,
CHAT_EVENT_NAMES.typingStopped,
CHAT_EVENT_NAMES.presenceOnline,
CHAT_EVENT_NAMES.presenceAway,
CHAT_EVENT_NAMES.presenceOffline,
]);
const CHAT_EVENT_NAME_VALUES = new Set<ChatEventName>(Object.values(CHAT_EVENT_NAMES));
export type ChatMention = {
type: ChatMentionType;
id: string;
label: string | null;
};
export type ChatLinkPreview = {
url: string;
title: string | null;
description: string | null;
imageUrl: string | null;
siteName: string | null;
};
type ChatRealtimeMessageBase = {
id: string;
clientMessageId: string;
body: string;
parentMessageId: string | null;
mentions: ChatMention[];
attachmentIds: string[];
linkPreviews: ChatLinkPreview[];
createdAt: string;
updatedAt: string;
editedAt: string | null;
deletedAt: string | null;
};
export type ChatRealtimeMarkdownMessage = ChatRealtimeMessageBase & {
authorUserId: string;
bodyFormat: "markdown";
/** System metadata is forbidden on user-authored Markdown messages. */
systemEvent?: never;
};
export type ChatRealtimeSystemMessage = ChatRealtimeMessageBase & {
authorUserId: string | null;
bodyFormat: "system";
systemEvent: ChatSystemEvent;
};
export type ChatRealtimeMessage = ChatRealtimeMarkdownMessage | ChatRealtimeSystemMessage;
export type ChatRealtimeReaction = {
id: string;
messageId: string;
userId: string;
emoji: string;
reactedAt: string;
};
export type ChatRealtimeThread = {
id: string;
parentMessageId: string;
replyCount: number;
lastReplyAt: string;
participantUserIds: string[];
};
type ChatEventEnvelope<TEvent extends ChatEventName, TCursor extends string | null, TData> = {
event: TEvent;
cursor: TCursor;
requestId: string;
tenantId: string;
chatId: string;
occurredAt: string;
data: TData;
};
export type ChatMessageCreatedEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.messageCreated, string, { message: ChatRealtimeMessage }>;
export type ChatMessageUpdatedEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.messageUpdated, string, { message: ChatRealtimeMessage }>;
export type ChatMessageDeletedEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.messageDeleted,
string,
{ messageId: string; deletedByUserId: string; deletedAt: string }
>;
export type ChatReactionAddedEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.reactionAdded, string, { reaction: ChatRealtimeReaction }>;
export type ChatReactionRemovedEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.reactionRemoved,
string,
{ messageId: string; userId: string; emoji: string; removedAt: string }
>;
export type ChatThreadReplyEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.threadReply, string, { thread: ChatRealtimeThread; message: ChatRealtimeMessage }>;
export type ChatReadReceiptEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.readReceipt, string, { messageId: string; userId: string; readAt: string }>;
export type ChatTypingEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.typingStarted | typeof CHAT_EVENT_NAMES.typingStopped, null, { userId: string }>;
export type ChatPresenceEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.presenceOnline | typeof CHAT_EVENT_NAMES.presenceAway | typeof CHAT_EVENT_NAMES.presenceOffline,
null,
{ userId: string; presence: ChatConnectionPresence }
>;
export type ChatMemberAddedEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.memberAdded,
string,
{ userId: string; roleInChat: ChatMemberRole; joinedAt: string }
>;
export type ChatMemberRemovedEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.memberRemoved, string, { userId: string; leftAt: string }>;
export type ChatChannelArchivedEvent = ChatEventEnvelope<typeof CHAT_EVENT_NAMES.channelArchived, string, { archivedAt: string; reason: ChatArchiveReason }>;
export type ChatPinChangedEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.pinChanged,
string,
{ messageId: string; pinned: boolean; changedByUserId: string }
>;
export type ChatLinkPreviewReadyEvent = ChatEventEnvelope<
typeof CHAT_EVENT_NAMES.linkPreviewReady,
string,
{ messageId: string; linkPreviews: ChatLinkPreview[] }
>;
export type ChatPersistentEvent =
| ChatMessageCreatedEvent
| ChatMessageUpdatedEvent
| ChatMessageDeletedEvent
| ChatReactionAddedEvent
| ChatReactionRemovedEvent
| ChatThreadReplyEvent
| ChatReadReceiptEvent
| ChatMemberAddedEvent
| ChatMemberRemovedEvent
| ChatChannelArchivedEvent
| ChatPinChangedEvent
| ChatLinkPreviewReadyEvent;
export type ChatEphemeralEvent = ChatTypingEvent | ChatPresenceEvent;
export type ChatServerEvent = ChatPersistentEvent | ChatEphemeralEvent;
type NormalizedChatEventBase = {
event: ChatEventName;
cursor: string | null;
requestId: string;
tenantId: string;
chatId: string;
occurredAt: string;
};
export type ParsedChatResumeCursor = {
streamId: string | null;
sequence: string;
};
export function validateChatServerEvent(input: unknown): ChatServerEvent {
if (!isRecord(input)) {
throw new Error("chat event must be an object");
}
assertAllowedKeys(input, new Set(["event", "cursor", "requestId", "tenantId", "chatId", "occurredAt", "data"]), "chat event");
const base = normalizeEventBase(input);
const data = requireRecord(input.data, "chat event data");
switch (base.event) {
case CHAT_EVENT_NAMES.messageCreated: {
assertPersistentCursor(base);
const message = normalizeMessageData(data);
if (message.parentMessageId !== null) {
throw new Error(`${CHAT_EVENT_NAMES.messageCreated} must carry a top-level message`);
}
return { ...base, event: CHAT_EVENT_NAMES.messageCreated, cursor: base.cursor, data: { message } };
}
case CHAT_EVENT_NAMES.messageUpdated: {
assertPersistentCursor(base);
return {
...base,
event: CHAT_EVENT_NAMES.messageUpdated,
cursor: base.cursor,
data: { message: normalizeMessageData(data) },
};
}
case CHAT_EVENT_NAMES.messageDeleted: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["messageId", "deletedByUserId", "deletedAt"]), `${CHAT_EVENT_NAMES.messageDeleted} data`);
return {
...base,
event: CHAT_EVENT_NAMES.messageDeleted,
cursor: base.cursor,
data: {
messageId: normalizeIdentifier(data.messageId, "data.messageId"),
deletedByUserId: normalizeIdentifier(data.deletedByUserId, "data.deletedByUserId"),
deletedAt: normalizeIsoDate(data.deletedAt, "data.deletedAt"),
},
};
}
case CHAT_EVENT_NAMES.reactionAdded: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["reaction"]), `${CHAT_EVENT_NAMES.reactionAdded} data`);
return {
...base,
event: CHAT_EVENT_NAMES.reactionAdded,
cursor: base.cursor,
data: { reaction: normalizeReaction(data.reaction) },
};
}
case CHAT_EVENT_NAMES.reactionRemoved: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["messageId", "userId", "emoji", "removedAt"]), `${CHAT_EVENT_NAMES.reactionRemoved} data`);
return {
...base,
event: CHAT_EVENT_NAMES.reactionRemoved,
cursor: base.cursor,
data: {
messageId: normalizeIdentifier(data.messageId, "data.messageId"),
userId: normalizeIdentifier(data.userId, "data.userId"),
emoji: normalizeEmoji(data.emoji, "data.emoji"),
removedAt: normalizeIsoDate(data.removedAt, "data.removedAt"),
},
};
}
case CHAT_EVENT_NAMES.threadReply: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["thread", "message"]), `${CHAT_EVENT_NAMES.threadReply} data`);
const thread = normalizeThread(data.thread);
const message = normalizeMessage(data.message);
if (message.parentMessageId === null || message.parentMessageId !== thread.parentMessageId) {
throw new Error(`${CHAT_EVENT_NAMES.threadReply} message must reference the event thread parent`);
}
return { ...base, event: CHAT_EVENT_NAMES.threadReply, cursor: base.cursor, data: { thread, message } };
}
case CHAT_EVENT_NAMES.readReceipt: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["messageId", "userId", "readAt"]), `${CHAT_EVENT_NAMES.readReceipt} data`);
return {
...base,
event: CHAT_EVENT_NAMES.readReceipt,
cursor: base.cursor,
data: {
messageId: normalizeIdentifier(data.messageId, "data.messageId"),
userId: normalizeIdentifier(data.userId, "data.userId"),
readAt: normalizeIsoDate(data.readAt, "data.readAt"),
},
};
}
case CHAT_EVENT_NAMES.typingStarted:
case CHAT_EVENT_NAMES.typingStopped: {
assertEphemeralCursor(base);
assertAllowedKeys(data, new Set(["userId"]), `${base.event} data`);
return {
...base,
event: base.event,
cursor: null,
data: { userId: normalizeIdentifier(data.userId, "data.userId") },
};
}
case CHAT_EVENT_NAMES.presenceOnline:
case CHAT_EVENT_NAMES.presenceAway:
case CHAT_EVENT_NAMES.presenceOffline: {
assertEphemeralCursor(base);
assertAllowedKeys(data, new Set(["userId", "presence"]), `${base.event} data`);
const expectedPresence = presenceForEvent(base.event);
if (data.presence !== expectedPresence) {
throw new Error(`${base.event} data.presence must be ${expectedPresence}`);
}
return {
...base,
event: base.event,
cursor: null,
data: { userId: normalizeIdentifier(data.userId, "data.userId"), presence: expectedPresence },
};
}
case CHAT_EVENT_NAMES.memberAdded: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["userId", "roleInChat", "joinedAt"]), `${CHAT_EVENT_NAMES.memberAdded} data`);
return {
...base,
event: CHAT_EVENT_NAMES.memberAdded,
cursor: base.cursor,
data: {
userId: normalizeIdentifier(data.userId, "data.userId"),
roleInChat: normalizeMemberRole(data.roleInChat),
joinedAt: normalizeIsoDate(data.joinedAt, "data.joinedAt"),
},
};
}
case CHAT_EVENT_NAMES.memberRemoved: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["userId", "leftAt"]), `${CHAT_EVENT_NAMES.memberRemoved} data`);
return {
...base,
event: CHAT_EVENT_NAMES.memberRemoved,
cursor: base.cursor,
data: {
userId: normalizeIdentifier(data.userId, "data.userId"),
leftAt: normalizeIsoDate(data.leftAt, "data.leftAt"),
},
};
}
case CHAT_EVENT_NAMES.channelArchived: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["archivedAt", "reason"]), `${CHAT_EVENT_NAMES.channelArchived} data`);
return {
...base,
event: CHAT_EVENT_NAMES.channelArchived,
cursor: base.cursor,
data: {
archivedAt: normalizeIsoDate(data.archivedAt, "data.archivedAt"),
reason: normalizeArchiveReason(data.reason),
},
};
}
case CHAT_EVENT_NAMES.pinChanged: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["messageId", "pinned", "changedByUserId"]), `${CHAT_EVENT_NAMES.pinChanged} data`);
if (typeof data.pinned !== "boolean") {
throw new Error("data.pinned must be a boolean");
}
return {
...base,
event: CHAT_EVENT_NAMES.pinChanged,
cursor: base.cursor,
data: {
messageId: normalizeIdentifier(data.messageId, "data.messageId"),
pinned: data.pinned,
changedByUserId: normalizeIdentifier(data.changedByUserId, "data.changedByUserId"),
},
};
}
case CHAT_EVENT_NAMES.linkPreviewReady: {
assertPersistentCursor(base);
assertAllowedKeys(data, new Set(["messageId", "linkPreviews"]), `${CHAT_EVENT_NAMES.linkPreviewReady} data`);
return {
...base,
event: CHAT_EVENT_NAMES.linkPreviewReady,
cursor: base.cursor,
data: {
messageId: normalizeIdentifier(data.messageId, "data.messageId"),
linkPreviews: normalizeLinkPreviews(data.linkPreviews, "data.linkPreviews"),
},
};
}
}
}
export function isChatServerEvent(input: unknown): input is ChatServerEvent {
try {
validateChatServerEvent(input);
return true;
} catch {
return false;
}
}
export function isPersistentChatEvent(event: ChatServerEvent): event is ChatPersistentEvent {
return PERSISTENT_CHAT_EVENTS.has(event.event);
}
export function isEphemeralChatEvent(event: ChatServerEvent): event is ChatEphemeralEvent {
return EPHEMERAL_CHAT_EVENTS.has(event.event);
}
function normalizeEventBase(input: Record<string, unknown>): NormalizedChatEventBase {
if (typeof input.event !== "string" || !CHAT_EVENT_NAME_VALUES.has(input.event as ChatEventName)) {
throw new Error("event must be a supported chat event name");
}
const event = input.event as ChatEventName;
let cursor: string | null;
if (EPHEMERAL_CHAT_EVENTS.has(event)) {
if (input.cursor !== null) {
throw new Error(`${event} must carry cursor null because it is ephemeral`);
}
cursor = null;
} else {
if (input.cursor === null) {
throw new Error(`${event} must carry a persistent cursor`);
}
cursor = normalizeChatEventCursor(input.cursor);
}
return {
event,
cursor,
requestId: normalizeIdentifier(input.requestId, "requestId"),
tenantId: normalizeIdentifier(input.tenantId, "tenantId"),
chatId: normalizeIdentifier(input.chatId, "chatId"),
occurredAt: normalizeIsoDate(input.occurredAt, "occurredAt"),
};
}
/** Stream generation plus monotonic TeamChatEvent sequence. */
export function normalizeChatEventCursor(value: unknown): string {
const cursor = parseChatResumeCursor(value);
if (cursor.streamId === null) {
throw new Error("event cursor must reference a positive persisted sequence");
}
return `${cursor.streamId}:${cursor.sequence}`;
}
/** Last-seen reconnect cursor. Zero represents a client with no prior event. */
export function normalizeChatResumeCursor(value: unknown): string {
const cursor = parseChatResumeCursor(value);
if (cursor.streamId === null) {
return cursor.sequence;
}
return `${cursor.streamId}:${cursor.sequence}`;
}
/** Parses an initial cursor or a persisted stream-generation cursor. */
export function parseChatResumeCursor(value: unknown): ParsedChatResumeCursor {
if (value === "0") {
return { streamId: null, sequence: "0" };
}
if (typeof value !== "string") {
throw new Error("cursor must be a string");
}
const separatorIndex = value.indexOf(":");
if (separatorIndex <= 0 || separatorIndex !== value.lastIndexOf(":")) {
throw new Error("cursor must contain exactly one stream and sequence separator");
}
const streamId = value.slice(0, separatorIndex);
const sequence = value.slice(separatorIndex + 1);
if (!CHAT_STREAM_ID_PATTERN.test(streamId)) {
throw new Error("cursor streamId must be a canonical stream identifier");
}
if (!CHAT_EVENT_SEQUENCE_PATTERN.test(sequence)) {
throw new Error("cursor sequence must be a positive canonical PostgreSQL BigInt decimal string");
}
if (sequence.length > CHAT_EVENT_CURSOR_MAX.toString().length || BigInt(sequence) > CHAT_EVENT_CURSOR_MAX) {
throw new Error("cursor sequence exceeds PostgreSQL BigInt");
}
return { streamId, sequence };
}
function assertPersistentCursor(base: NormalizedChatEventBase): asserts base is NormalizedChatEventBase & { cursor: string } {
if (!PERSISTENT_CHAT_EVENTS.has(base.event) || base.cursor === null) {
throw new Error(`${base.event} must carry a persistent cursor`);
}
}
function assertEphemeralCursor(base: NormalizedChatEventBase): asserts base is NormalizedChatEventBase & { cursor: null } {
if (!EPHEMERAL_CHAT_EVENTS.has(base.event) || base.cursor !== null) {
throw new Error(`${base.event} must carry cursor null because it is ephemeral`);
}
}
function normalizeMessageData(data: Record<string, unknown>): ChatRealtimeMessage {
assertAllowedKeys(data, new Set(["message"]), "message event data");
return normalizeMessage(data.message);
}
function normalizeMessage(value: unknown): ChatRealtimeMessage {
const message = requireRecord(value, "message");
assertAllowedKeys(
message,
new Set([
"id",
"clientMessageId",
"authorUserId",
"body",
"bodyFormat",
"parentMessageId",
"mentions",
"attachmentIds",
"linkPreviews",
"createdAt",
"updatedAt",
"editedAt",
"deletedAt",
"systemEvent",
]),
"message"
);
const body = normalizeBoundedString(message.body, "message.body", CHAT_MESSAGE_MAX_BODY_LENGTH, { trim: false, allowEmpty: true });
const attachmentIds = normalizeIdentifierArray(message.attachmentIds, "message.attachmentIds", CHAT_MESSAGE_MAX_ATTACHMENTS);
const deletedAt = normalizeNullableIsoDate(message.deletedAt, "message.deletedAt");
const bodyFormat = normalizeMessageFormat(message.bodyFormat);
const baseMessage: ChatRealtimeMessageBase = {
id: normalizeIdentifier(message.id, "message.id"),
clientMessageId: normalizeIdentifier(message.clientMessageId, "message.clientMessageId"),
body,
parentMessageId: normalizeNullableIdentifier(message.parentMessageId, "message.parentMessageId"),
mentions: normalizeMentions(message.mentions),
attachmentIds,
linkPreviews: normalizeLinkPreviews(message.linkPreviews, "message.linkPreviews"),
createdAt: normalizeIsoDate(message.createdAt, "message.createdAt"),
updatedAt: normalizeIsoDate(message.updatedAt, "message.updatedAt"),
editedAt: normalizeNullableIsoDate(message.editedAt, "message.editedAt"),
deletedAt,
};
if (bodyFormat === "system") {
if (baseMessage.parentMessageId !== null) {
throw new Error("system messages must be top-level messages");
}
if (baseMessage.mentions.length > 0 || attachmentIds.length > 0 || baseMessage.linkPreviews.length > 0) {
throw new Error("system messages cannot carry mentions, attachments, or link previews");
}
if (baseMessage.editedAt !== null || deletedAt !== null) {
throw new Error("system messages are immutable");
}
return {
...baseMessage,
authorUserId: normalizeNullableIdentifier(message.authorUserId, "message.authorUserId"),
bodyFormat,
systemEvent: normalizeSystemEvent(message.systemEvent),
};
}
if ("systemEvent" in message) {
throw new Error("markdown messages cannot carry systemEvent metadata");
}
if (!body.trim() && attachmentIds.length === 0 && deletedAt === null) {
throw new Error("message must contain body text or an attachment");
}
const normalizedMessage: ChatRealtimeMarkdownMessage = {
...baseMessage,
authorUserId: normalizeIdentifier(message.authorUserId, "message.authorUserId"),
bodyFormat,
};
if (deletedAt === null) return normalizedMessage;
return {
...normalizedMessage,
body: "",
mentions: [],
attachmentIds: [],
linkPreviews: [],
};
}
function normalizeSystemEvent(value: unknown): ChatSystemEvent {
const event = requireRecord(value, "message.systemEvent");
assertAllowedKeys(event, new Set(["kind", "metadata"]), "message.systemEvent");
if (typeof event.kind !== "string" || !CHAT_SYSTEM_EVENT_KINDS.includes(event.kind as ChatSystemEventKind)) {
throw new Error("message.systemEvent.kind must be supported");
}
return {
kind: event.kind as ChatSystemEventKind,
metadata: normalizeSystemEventMetadata(event.metadata, "message.systemEvent.metadata"),
};
}
function normalizeSystemEventMetadata(value: unknown, label: string): ChatSystemEventMetadata {
if (!isRecord(value)) {
throw new Error(`${label} must be an object`);
}
return normalizeSystemEventMetadataRecord(value, label, 0);
}
function normalizeSystemEventMetadataRecord(value: Record<string, unknown>, label: string, depth: number): ChatSystemEventMetadata {
if (depth > 10) {
throw new Error(`${label} exceeds its maximum nesting depth`);
}
const normalized: ChatSystemEventMetadata = {};
for (const [key, entry] of Object.entries(value)) {
if (!key || key.length > MAX_LABEL_LENGTH) {
throw new Error(`${label} contains an invalid key`);
}
normalized[key] = normalizeSystemEventMetadataValue(entry, `${label}.${key}`, depth + 1);
}
return normalized;
}
function normalizeSystemEventMetadataValue(value: unknown, label: string, depth: number): ChatSystemEventMetadataValue {
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
if (typeof value === "number") {
if (!Number.isFinite(value)) throw new Error(`${label} must be a finite JSON number`);
return value;
}
if (Array.isArray(value)) {
if (depth > 10) throw new Error(`${label} exceeds its maximum nesting depth`);
return value.map((entry, index) => normalizeSystemEventMetadataValue(entry, `${label}[${index}]`, depth + 1));
}
if (isRecord(value)) return normalizeSystemEventMetadataRecord(value, label, depth);
throw new Error(`${label} must contain only JSON values`);
}
function normalizeMentions(value: unknown): ChatMention[] {
const mentions = requireArray(value, "message.mentions", CHAT_MESSAGE_MAX_MENTIONS);
return mentions.map((entry, index) => {
const mention = requireRecord(entry, `message.mentions[${index}]`);
assertAllowedKeys(mention, new Set(["type", "id", "label"]), `message.mentions[${index}]`);
if (mention.type !== "user" && mention.type !== "project" && mention.type !== "contact" && mention.type !== "company") {
throw new Error(`message.mentions[${index}].type must be supported`);
}
return {
type: mention.type,
id: normalizeIdentifier(mention.id, `message.mentions[${index}].id`),
label: normalizeNullableBoundedString(mention.label, `message.mentions[${index}].label`, MAX_LABEL_LENGTH),
};
});
}
function normalizeLinkPreviews(value: unknown, label: string): ChatLinkPreview[] {
const previews = requireArray(value, label, CHAT_MESSAGE_MAX_LINK_PREVIEWS);
return previews.map((entry, index) => {
const previewLabel = `${label}[${index}]`;
const preview = requireRecord(entry, previewLabel);
assertAllowedKeys(preview, new Set(["url", "title", "description", "imageUrl", "siteName"]), previewLabel);
return {
url: normalizeHttpUrl(preview.url, `${previewLabel}.url`),
title: normalizeNullableBoundedString(preview.title, `${previewLabel}.title`, MAX_LABEL_LENGTH),
description: normalizeNullableBoundedString(preview.description, `${previewLabel}.description`, MAX_PREVIEW_DESCRIPTION_LENGTH),
imageUrl: preview.imageUrl === null ? null : normalizeHttpUrl(preview.imageUrl, `${previewLabel}.imageUrl`),
siteName: normalizeNullableBoundedString(preview.siteName, `${previewLabel}.siteName`, MAX_LABEL_LENGTH),
};
});
}
function normalizeReaction(value: unknown): ChatRealtimeReaction {
const reaction = requireRecord(value, "reaction");
assertAllowedKeys(reaction, new Set(["id", "messageId", "userId", "emoji", "reactedAt"]), "reaction");
return {
id: normalizeIdentifier(reaction.id, "reaction.id"),
messageId: normalizeIdentifier(reaction.messageId, "reaction.messageId"),
userId: normalizeIdentifier(reaction.userId, "reaction.userId"),
emoji: normalizeEmoji(reaction.emoji, "reaction.emoji"),
reactedAt: normalizeIsoDate(reaction.reactedAt, "reaction.reactedAt"),
};
}
function normalizeThread(value: unknown): ChatRealtimeThread {
const thread = requireRecord(value, "thread");
assertAllowedKeys(thread, new Set(["id", "parentMessageId", "replyCount", "lastReplyAt", "participantUserIds"]), "thread");
if (typeof thread.replyCount !== "number" || !Number.isInteger(thread.replyCount) || thread.replyCount < 1) {
throw new Error("thread.replyCount must be a positive integer");
}
return {
id: normalizeIdentifier(thread.id, "thread.id"),
parentMessageId: normalizeIdentifier(thread.parentMessageId, "thread.parentMessageId"),
replyCount: thread.replyCount,
lastReplyAt: normalizeIsoDate(thread.lastReplyAt, "thread.lastReplyAt"),
participantUserIds: normalizeIdentifierArray(thread.participantUserIds, "thread.participantUserIds", CHAT_THREAD_MAX_PARTICIPANTS),
};
}
function normalizeMessageFormat(value: unknown): ChatMessageFormat {
if (value !== "markdown" && value !== "system") {
throw new Error("message.bodyFormat must be markdown or system");
}
return value;
}
function normalizeMemberRole(value: unknown): ChatMemberRole {
if (value !== "admin" && value !== "member") {
throw new Error("data.roleInChat must be admin or member");
}
return value;
}
function normalizeArchiveReason(value: unknown): ChatArchiveReason {
if (value !== "manual" && value !== "project_completed" && value !== "project_cancelled") {
throw new Error("data.reason must be a supported archive reason");
}
return value;
}
function presenceForEvent(event: ChatPresenceEvent["event"]): ChatConnectionPresence {
switch (event) {
case CHAT_EVENT_NAMES.presenceOnline:
return "online";
case CHAT_EVENT_NAMES.presenceAway:
return "away";
case CHAT_EVENT_NAMES.presenceOffline:
return "offline";
}
}
function normalizeEmoji(value: unknown, label: string): string {
return normalizeBoundedString(value, label, MAX_EMOJI_LENGTH, { trim: true, allowEmpty: false });
}
function normalizeIdentifier(value: unknown, label: string): string {
return normalizeBoundedString(value, label, MAX_IDENTIFIER_LENGTH, { trim: true, allowEmpty: false });
}
function normalizeNullableIdentifier(value: unknown, label: string): string | null {
if (value === null) return null;
return normalizeIdentifier(value, label);
}
function normalizeIdentifierArray(value: unknown, label: string, maxItems: number): string[] {
return requireArray(value, label, maxItems).map((entry, index) => normalizeIdentifier(entry, `${label}[${index}]`));
}
function normalizeNullableBoundedString(value: unknown, label: string, maxLength: number): string | null {
if (value === null) return null;
return normalizeBoundedString(value, label, maxLength, { trim: true, allowEmpty: false });
}
function normalizeBoundedString(value: unknown, label: string, maxLength: number, options: { trim: boolean; allowEmpty: boolean }): string {
if (typeof value !== "string") {
throw new Error(`${label} must be a string`);
}
const normalized = options.trim ? value.trim() : value;
if (!options.allowEmpty && !normalized) {
throw new Error(`${label} must not be empty`);
}
if (normalized.length > maxLength) {
throw new Error(`${label} exceeds its maximum length of ${maxLength}`);
}
return normalized;
}
function normalizeIsoDate(value: unknown, label: string): string {
const normalized = normalizeBoundedString(value, label, MAX_IDENTIFIER_LENGTH, { trim: true, allowEmpty: false });
if (!ISO_DATE_PATTERN.test(normalized) || Number.isNaN(Date.parse(normalized))) {
throw new Error(`${label} must be an ISO timestamp`);
}
return normalized;
}
function normalizeNullableIsoDate(value: unknown, label: string): string | null {
if (value === null) return null;
return normalizeIsoDate(value, label);
}
function normalizeHttpUrl(value: unknown, label: string): string {
const normalized = normalizeBoundedString(value, label, MAX_URL_LENGTH, { trim: true, allowEmpty: false });
let parsed: URL;
try {
parsed = new URL(normalized);
} catch {
throw new Error(`${label} must be an absolute HTTP URL`);
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(`${label} must be an absolute HTTP URL`);
}
return normalized;
}
function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (!isRecord(value)) {
throw new Error(`${label} must be an object`);
}
return value;
}
function requireArray(value: unknown, label: string, maxItems: number): unknown[] {
if (!Array.isArray(value)) {
throw new Error(`${label} must be an array`);
}
if (value.length > maxItems) {
throw new Error(`${label} exceeds its maximum item count of ${maxItems}`);
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function assertAllowedKeys(value: Record<string, unknown>, allowedKeys: ReadonlySet<string>, label: string): void {
for (const key of Object.keys(value)) {
if (!allowedKeys.has(key)) {
throw new Error(`${label} contains unsupported key: ${key}`);
}
}
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { CHAT_EVENT_NAMES, validateChatServerEvent } from "./chat-events.js";
import { assertChatEventInScope, normalizeChatEventScope } from "./chat-guards.js";
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.readReceipt,
cursor: "stream_1:42",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T12:00:00.000Z",
data: { messageId: "message_1", userId: "user_1", readAt: "2026-07-15T12:00:00.000Z" },
});
describe("chat event scope guard", () => {
it("normalizes a strict tenant and channel scope", () => {
expect(normalizeChatEventScope({ tenantId: " tenant_1 ", chatId: " chat_1 " })).toEqual({ tenantId: "tenant_1", chatId: "chat_1" });
});
it("rejects missing, blank, non-string, and oversized scope values", () => {
expect(() => normalizeChatEventScope({ chatId: "chat_1" })).toThrow(/tenantId must be a string/);
expect(() => normalizeChatEventScope({ tenantId: "tenant_1", chatId: " " })).toThrow(/chatId must not be empty/);
expect(() => normalizeChatEventScope({ tenantId: 42, chatId: "chat_1" })).toThrow(/tenantId must be a string/);
expect(() => normalizeChatEventScope({ tenantId: "tenant_1", chatId: "x".repeat(501) })).toThrow(/chatId is too long/);
});
it("accepts an event only in its exact tenant and channel scope", () => {
expect(() => assertChatEventInScope(event, { tenantId: "tenant_1", chatId: "chat_1" })).not.toThrow();
expect(() => assertChatEventInScope(event, { tenantId: "tenant_2", chatId: "chat_1" })).toThrow(/event\.tenantId/);
expect(() => assertChatEventInScope(event, { tenantId: "tenant_1", chatId: "chat_2" })).toThrow(/event\.chatId/);
});
});
@@ -0,0 +1,43 @@
import type { ChatServerEvent } from "./chat-events.js";
export type ChatEventScope = {
tenantId: string;
chatId: string;
};
export type ChatEventScopeInput = {
tenantId?: unknown;
chatId?: unknown;
};
const MAX_SCOPE_VALUE_LENGTH = 500;
export function normalizeChatEventScope(input: ChatEventScopeInput): ChatEventScope {
return {
tenantId: normalizeRequiredScopeString(input.tenantId, "tenantId"),
chatId: normalizeRequiredScopeString(input.chatId, "chatId"),
};
}
export function assertChatEventInScope(event: ChatServerEvent, scope: ChatEventScope): void {
if (event.tenantId !== scope.tenantId) {
throw new Error("event.tenantId does not match chat event scope");
}
if (event.chatId !== scope.chatId) {
throw new Error("event.chatId does not match chat event scope");
}
}
function normalizeRequiredScopeString(value: unknown, label: string): string {
if (typeof value !== "string") {
throw new Error(`${label} must be a string`);
}
const normalized = value.trim();
if (!normalized) {
throw new Error(`${label} must not be empty`);
}
if (normalized.length > MAX_SCOPE_VALUE_LENGTH) {
throw new Error(`${label} is too long`);
}
return normalized;
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { extractChatMentions, findChatMentionQuery, insertChatMention, toChatMentionToken } from "./chat-mentions.js";
describe("chat mention syntax", () => {
it("extracts canonical mentions once and never trusts a client label", () => {
expect(extractChatMentions("Hi <@user:user_1>, Projekt <@project:project-1> und noch einmal <@user:user_1>."))
.toEqual([
{ type: "user", id: "user_1", label: null },
{ type: "project", id: "project-1", label: null },
]);
});
it("recognizes the general and explicit German picker prefixes at the caret", () => {
expect(findChatMentionQuery("Hallo @raf", 10)).toEqual({ start: 6, end: 10, query: "raf", kind: null });
expect(findChatMentionQuery("Siehe @projekt:P-20", 19)).toEqual({ start: 6, end: 19, query: "P-20", kind: "project" });
expect(findChatMentionQuery("@kontakt:", 9)).toEqual({ start: 0, end: 9, query: "", kind: "contact" });
expect(findChatMentionQuery("bereits <@user:user_1>", 22)).toBeNull();
});
it("inserts a canonical token and returns the next caret position", () => {
const query = findChatMentionQuery("Hallo @raf morgen", 10)!;
expect(insertChatMention("Hallo @raf morgen", query, { type: "user", id: "user_1" })).toEqual({
body: "Hallo <@user:user_1> morgen",
caret: 21,
});
});
it("rejects identifiers that could break the token grammar", () => {
expect(() => toChatMentionToken({ type: "user", id: "user>" })).toThrow(/invalid/);
});
});
@@ -0,0 +1,74 @@
import { CHAT_MESSAGE_MAX_MENTIONS, type ChatMention, type ChatMentionType } from "./chat-events.js";
const CHAT_MENTION_ID_PATTERN = /^[A-Za-z0-9._-]{1,500}$/u;
const CHAT_MENTION_TOKEN_PATTERN = /<@(user|project|contact|company):([A-Za-z0-9._-]{1,500})>/gu;
const EXPLICIT_MENTION_PREFIXES = {
projekt: "project",
kontakt: "contact",
firma: "company",
} as const satisfies Readonly<Record<string, ChatMentionType>>;
export type ChatMentionQuery = Readonly<{
start: number;
end: number;
query: string;
kind: ChatMentionType | null;
}>;
/** Returns the canonical Markdown token stored in a chat message body. */
export function toChatMentionToken(mention: Pick<ChatMention, "type" | "id">): string {
if (!CHAT_MENTION_ID_PATTERN.test(mention.id)) throw new Error("chat mention id is invalid");
return `<@${mention.type}:${mention.id}>`;
}
/** Extracts unique, ordered mention references without trusting client labels. */
export function extractChatMentions(body: string): ChatMention[] {
const mentions: ChatMention[] = [];
const seen = new Set<string>();
for (const match of body.matchAll(CHAT_MENTION_TOKEN_PATTERN)) {
const type = match[1] as ChatMentionType;
const id = match[2]!;
const key = `${type}\u0000${id}`;
if (seen.has(key)) continue;
seen.add(key);
mentions.push({ type, id, label: null });
if (mentions.length === CHAT_MESSAGE_MAX_MENTIONS) break;
}
return mentions;
}
/** Resolves the mention fragment immediately before the caret. */
export function findChatMentionQuery(body: string, caret: number): ChatMentionQuery | null {
if (!Number.isInteger(caret) || caret < 0 || caret > body.length) return null;
const prefix = body.slice(0, caret);
const boundary = Math.max(prefix.lastIndexOf(" "), prefix.lastIndexOf("\n"), prefix.lastIndexOf("\t"));
const start = boundary + 1;
const fragment = prefix.slice(start);
if (!fragment.startsWith("@") || fragment.startsWith("<@") || /[<>]/u.test(fragment)) return null;
const explicit = /^@(projekt|kontakt|firma):([^\s@]*)$/u.exec(fragment);
if (explicit) {
return {
start,
end: caret,
query: explicit[2]!,
kind: EXPLICIT_MENTION_PREFIXES[explicit[1] as keyof typeof EXPLICIT_MENTION_PREFIXES],
};
}
const general = /^@([^\s@:]*)$/u.exec(fragment);
if (!general) return null;
return { start, end: caret, query: general[1]!, kind: null };
}
/** Replaces the active query with one canonical token and a trailing space. */
export function insertChatMention(body: string, query: ChatMentionQuery, mention: Pick<ChatMention, "type" | "id">): { body: string; caret: number } {
if (query.start < 0 || query.end < query.start || query.end > body.length) throw new Error("chat mention query range is invalid");
const token = toChatMentionToken(mention);
const suffix = body.slice(query.end);
const separator = /^\s/u.test(suffix) ? "" : " ";
const nextBody = `${body.slice(0, query.start)}${token}${separator}${suffix}`;
const caret = query.start + token.length + (separator.length || (suffix.length > 0 ? 1 : 0));
return { body: nextBody, caret };
}
@@ -0,0 +1,359 @@
import { describe, expect, it } from "vitest";
import { CHAT_EVENT_NAMES, CHAT_MESSAGE_MAX_BODY_LENGTH, CHAT_MESSAGE_MAX_MENTIONS } from "./chat-events.js";
import {
CHAT_CLIENT_FRAME_TYPES,
CHAT_MAX_ACTIVE_SUBSCRIPTIONS,
CHAT_WIRE_MAX_CLIENT_JSON_LENGTH,
CHAT_WIRE_MAX_GAP_EVENTS,
CHAT_WIRE_MAX_RESUME_CURSORS,
CHAT_WIRE_MAX_SERVER_JSON_LENGTH,
isChatClientFrame,
isChatServerFrame,
parseChatClientFrameJson,
parseChatServerFrameJson,
serializeChatClientFrame,
serializeChatServerFrame,
validateChatClientFrame,
validateChatServerFrame,
} from "./chat-wire.js";
const occurredAt = "2026-07-15T12:00:00.000Z";
const message = {
id: "message_1",
clientMessageId: "client_message_1",
authorUserId: "user_1",
body: "Hello team",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: occurredAt,
updatedAt: occurredAt,
editedAt: null,
deletedAt: null,
} as const;
function persistentEvent(sequence = 1, overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: `stream_1:${sequence}`,
requestId: `request_${sequence}`,
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt,
data: { message: { ...message, id: `message_${sequence}`, clientMessageId: `client_message_${sequence}` } },
...overrides,
};
}
function typingEvent(): Record<string, unknown> {
return {
event: CHAT_EVENT_NAMES.typingStarted,
cursor: null,
requestId: "request_typing",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt,
data: { userId: "user_2" },
};
}
describe("chat websocket client wire contract", () => {
it("shares one bounded active-subscription ceiling", () => {
expect(CHAT_MAX_ACTIVE_SUBSCRIPTIONS).toBe(64);
expect(CHAT_WIRE_MAX_RESUME_CURSORS).toBe(CHAT_MAX_ACTIVE_SUBSCRIPTIONS);
});
it("validates authentication and canonical per-chat resume cursors", () => {
expect(
validateChatClientFrame({
type: CHAT_CLIENT_FRAME_TYPES.authenticate,
token: "session-token-value",
resumeCursors: [
{ chatId: " chat_1 ", afterCursor: "stream_1:42" },
{ chatId: "chat_2", afterCursor: "0" },
],
})
).toEqual({
type: CHAT_CLIENT_FRAME_TYPES.authenticate,
token: "session-token-value",
resumeCursors: [
{ chatId: "chat_1", afterCursor: "stream_1:42" },
{ chatId: "chat_2", afterCursor: "0" },
],
});
});
it("validates subscribe, unsubscribe, typing, presence, read, and ping frames", () => {
expect(validateChatClientFrame({ type: "subscribe", chatId: "chat_1", afterCursor: "0" })).toEqual({
type: "subscribe",
chatId: "chat_1",
afterCursor: "0",
});
expect(validateChatClientFrame({ type: "unsubscribe", chatId: "chat_1" })).toEqual({ type: "unsubscribe", chatId: "chat_1" });
expect(validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "started" })).toEqual({
type: "typing",
chatId: "chat_1",
status: "started",
});
expect(validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "stopped" })).toMatchObject({ status: "stopped" });
expect(validateChatClientFrame({ type: "presence", status: "online" })).toEqual({ type: "presence", status: "online" });
expect(validateChatClientFrame({ type: "presence", status: "away" })).toEqual({ type: "presence", status: "away" });
expect(validateChatClientFrame({ type: "mark_read", chatId: "chat_1", messageId: "message_1", requestId: "request_1" })).toEqual({
type: "mark_read",
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
});
expect(validateChatClientFrame({ type: "ping" })).toEqual({ type: "ping" });
});
it("validates bounded message content and normalized mention targets", () => {
expect(
validateChatClientFrame({
type: "send_message",
chatId: "chat_1",
requestId: "request_1",
clientMessageId: "client_message_1",
body: " Hello\nteam ",
mentions: [
{ type: "user", id: "user_2", label: " Ada " },
{ type: "project", id: "project_1" },
],
})
).toEqual({
type: "send_message",
chatId: "chat_1",
requestId: "request_1",
clientMessageId: "client_message_1",
body: " Hello\nteam ",
mentions: [
{ type: "user", id: "user_2", label: "Ada" },
{ type: "project", id: "project_1", label: null },
],
});
});
it("rejects unsupported keys, invalid types, and unsafe identifiers", () => {
expect(() => validateChatClientFrame(null)).toThrow(/must be an object/);
expect(() => validateChatClientFrame([])).toThrow(/must be an object/);
expect(() => validateChatClientFrame({ type: "unknown" })).toThrow(/supported chat client frame type/);
expect(() => validateChatClientFrame({ type: "ping", metadata: {} })).toThrow(/unsupported key/);
expect(() => validateChatClientFrame({ type: "subscribe", chatId: "chat id", afterCursor: "0" })).toThrow(/safe identifier/);
expect(() => validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "active" })).toThrow(/started or stopped/);
expect(() => validateChatClientFrame({ type: "presence", status: "offline" })).toThrow(/online or away/);
expect(() => validateChatClientFrame({ type: "mark_read", chatId: "chat_1", messageId: null, requestId: "request_1" })).toThrow(
/messageId must be a string/
);
});
it("rejects secret token shape errors without reflecting token contents", () => {
const secret = " Bearer private-session-token ";
let diagnostic = "";
try {
validateChatClientFrame({ type: "authenticate", token: secret, resumeCursors: [] });
} catch (error) {
diagnostic = error instanceof Error ? error.message : String(error);
}
expect(diagnostic).toBe("authenticate token is invalid");
expect(diagnostic).not.toContain("private-session-token");
expect(() => validateChatClientFrame({ type: "authenticate", token: "x".repeat(8_193), resumeCursors: [] })).toThrow(/token is invalid/);
});
it("rejects malformed, duplicate, invalid, and oversized resume cursors", () => {
expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: null })).toThrow(/must be an array/);
expect(() =>
validateChatClientFrame({
type: "authenticate",
token: "token",
resumeCursors: [
{ chatId: "chat_1", afterCursor: "0" },
{ chatId: "chat_1", afterCursor: "stream_1:2" },
],
})
).toThrow(/duplicate chatId/);
expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: [{ chatId: "chat_1", afterCursor: "stream_1:0" }] })).toThrow(
/positive canonical/
);
expect(() =>
validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: [{ chatId: "chat_1", afterCursor: "0", extra: true }] })
).toThrow(/unsupported key/);
expect(() =>
validateChatClientFrame({
type: "authenticate",
token: "token",
resumeCursors: Array.from({ length: CHAT_WIRE_MAX_RESUME_CURSORS + 1 }, (_, index) => ({ chatId: `chat_${index}`, afterCursor: "0" })),
})
).toThrow(/too many entries/);
});
it("rejects empty or oversized bodies and malformed mentions", () => {
const base = {
type: "send_message",
chatId: "chat_1",
requestId: "request_1",
clientMessageId: "client_message_1",
body: "Hello",
mentions: [],
};
expect(() => validateChatClientFrame({ ...base, body: " \n " })).toThrow(/must not be empty/);
expect(() => validateChatClientFrame({ ...base, body: "x".repeat(CHAT_MESSAGE_MAX_BODY_LENGTH + 1) })).toThrow(/maximum length/);
expect(() => validateChatClientFrame({ ...base, body: "Hello\u0000" })).toThrow(/control character/);
expect(() =>
validateChatClientFrame({
...base,
mentions: [
{ type: "user", id: "user_2" },
{ type: "user", id: "user_2" },
],
})
).toThrow(/duplicate targets/);
expect(() => validateChatClientFrame({ ...base, mentions: [{ type: "email", id: "user_2" }] })).toThrow(/supported mention type/);
expect(() => validateChatClientFrame({ ...base, mentions: [{ type: "user", id: "user_2", token: "secret" }] })).toThrow(/unsupported key/);
expect(() =>
validateChatClientFrame({
...base,
mentions: Array.from({ length: CHAT_MESSAGE_MAX_MENTIONS + 1 }, (_, index) => ({ type: "user", id: `user_${index}` })),
})
).toThrow(/too many entries/);
});
it("parses and serializes size-bounded client JSON without exposing raw input", () => {
const raw = serializeChatClientFrame({ type: "subscribe", chatId: "chat_1", afterCursor: "stream_1:42" });
expect(parseChatClientFrameJson(raw)).toEqual({ type: "subscribe", chatId: "chat_1", afterCursor: "stream_1:42" });
expect(() => parseChatClientFrameJson("{private-token")).toThrow("chat client frame must contain valid JSON");
expect(() => parseChatClientFrameJson("x".repeat(CHAT_WIRE_MAX_CLIENT_JSON_LENGTH + 1))).toThrow(/exceeds its maximum length/);
});
it("provides a non-throwing client-frame guard", () => {
expect(isChatClientFrame({ type: "ping" })).toBe(true);
expect(isChatClientFrame({ type: "ping", extra: true })).toBe(false);
});
});
describe("chat websocket server wire contract", () => {
it("validates ready, event, error, and pong frames", () => {
expect(validateChatServerFrame({ type: "ready", connectionId: "connection_1" })).toEqual({ type: "ready", connectionId: "connection_1" });
expect(validateChatServerFrame({ type: "event", event: persistentEvent() })).toMatchObject({
type: "event",
event: { event: CHAT_EVENT_NAMES.messageCreated, cursor: "stream_1:1" },
});
expect(validateChatServerFrame({ type: "event", event: typingEvent() })).toMatchObject({
type: "event",
event: { event: CHAT_EVENT_NAMES.typingStarted, cursor: null },
});
expect(
validateChatServerFrame({
type: "error",
i18nKey: "chat.errors.invalidInput",
retryable: false,
requestId: "request_1",
clientMessageId: "client_message_1",
})
).toEqual({
type: "error",
i18nKey: "chat.errors.invalidInput",
retryable: false,
requestId: "request_1",
clientMessageId: "client_message_1",
});
expect(validateChatServerFrame({ type: "pong" })).toEqual({ type: "pong" });
});
it("validates ordered gap pages and reset results", () => {
expect(
validateChatServerFrame({
type: "subscribed",
chatId: "chat_1",
result: {
status: "ok",
events: [persistentEvent(2), persistentEvent(8)],
nextCursor: "stream_1:8",
hasMore: true,
},
})
).toMatchObject({
type: "subscribed",
chatId: "chat_1",
result: { status: "ok", nextCursor: "stream_1:8", hasMore: true },
});
expect(
validateChatServerFrame({
type: "subscribed",
chatId: "chat_1",
result: { status: "reset_required", currentStreamId: "new-stream_1" },
})
).toEqual({
type: "subscribed",
chatId: "chat_1",
result: { status: "reset_required", currentStreamId: "new-stream_1" },
});
});
it("rejects malformed or unsafe error diagnostics", () => {
expect(() => validateChatServerFrame({ type: "error", i18nKey: "Something failed with token abc", retryable: false })).toThrow(/catalog error key/);
expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.status.offline", retryable: false })).toThrow(/catalog error key/);
expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: "yes" })).toThrow(/must be a boolean/);
expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, message: "raw failure" })).toThrow(
/unsupported key/
);
expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, stack: "token" })).toThrow(/unsupported key/);
expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, requestId: null })).toThrow(
/requestId must be a string/
);
});
it("rejects non-persistent, cross-scope, mixed-stream, unordered, and inconsistent gap pages", () => {
const subscribed = (events: unknown[], nextCursor: string, hasMore = false) => ({
type: "subscribed",
chatId: "chat_1",
result: { status: "ok", events, nextCursor, hasMore },
});
expect(() => validateChatServerFrame(subscribed([typingEvent()], "stream_1:1"))).toThrow(/must be persistent/);
expect(() => validateChatServerFrame(subscribed([persistentEvent(1, { chatId: "chat_2" })], "stream_1:1"))).toThrow(/chatId does not match/);
expect(() => validateChatServerFrame(subscribed([persistentEvent(1), persistentEvent(2, { tenantId: "tenant_2" })], "stream_1:2"))).toThrow(/one tenant/);
expect(() => validateChatServerFrame(subscribed([persistentEvent(1), persistentEvent(2, { cursor: "stream_2:2" })], "stream_2:2"))).toThrow(
/one stream generation/
);
expect(() => validateChatServerFrame(subscribed([persistentEvent(2), persistentEvent(1)], "stream_1:1"))).toThrow(/strictly ascending/);
expect(() => validateChatServerFrame(subscribed([persistentEvent(1)], "stream_1:2"))).toThrow(/nextCursor must match/);
expect(() => validateChatServerFrame(subscribed([], "0", true))).toThrow(/empty page/);
expect(() =>
validateChatServerFrame(
subscribed(
Array.from({ length: CHAT_WIRE_MAX_GAP_EVENTS + 1 }, (_, index) => persistentEvent(index + 1)),
"stream_1:251"
)
)
).toThrow(/too many events/);
});
it("rejects unsupported server frame keys and malformed nested events", () => {
expect(() => validateChatServerFrame(new Date())).toThrow(/plain object/);
expect(() => validateChatServerFrame({ type: "unknown" })).toThrow(/supported chat server frame type/);
expect(() => validateChatServerFrame({ type: "ready", connectionId: "connection_1", token: "secret" })).toThrow(/unsupported key/);
expect(() => validateChatServerFrame({ type: "event", event: { ...persistentEvent(), authorization: "secret" } })).toThrow(
/unsupported key: authorization/
);
expect(() =>
validateChatServerFrame({ type: "subscribed", chatId: "chat_1", result: { status: "reset_required", currentStreamId: "bad:stream" } })
).toThrow(/separator/);
});
it("parses and serializes size-bounded server JSON", () => {
const raw = serializeChatServerFrame({ type: "event", event: persistentEvent() });
expect(parseChatServerFrameJson(raw)).toMatchObject({ type: "event", event: { cursor: "stream_1:1" } });
expect(() => parseChatServerFrameJson("{")).toThrow("chat server frame must contain valid JSON");
expect(() => parseChatServerFrameJson("x".repeat(CHAT_WIRE_MAX_SERVER_JSON_LENGTH + 1))).toThrow(/exceeds its maximum length/);
});
it("provides a non-throwing server-frame guard", () => {
expect(isChatServerFrame({ type: "pong" })).toBe(true);
expect(isChatServerFrame({ type: "pong", payload: "secret" })).toBe(false);
});
});
@@ -0,0 +1,549 @@
import {
CHAT_MESSAGE_MAX_BODY_LENGTH,
CHAT_MESSAGE_MAX_MENTIONS,
isPersistentChatEvent,
normalizeChatResumeCursor,
parseChatResumeCursor,
validateChatServerEvent,
type ChatMention,
type ChatMentionType,
type ChatPersistentEvent,
type ChatServerEvent,
} from "./chat-events.js";
export const CHAT_CLIENT_FRAME_TYPES = {
authenticate: "authenticate",
subscribe: "subscribe",
unsubscribe: "unsubscribe",
sendMessage: "send_message",
typing: "typing",
presence: "presence",
markRead: "mark_read",
ping: "ping",
} as const;
export const CHAT_SERVER_FRAME_TYPES = {
ready: "ready",
subscribed: "subscribed",
event: "event",
error: "error",
pong: "pong",
} as const;
/** Shared gateway/client ceiling for concurrently active chat rooms. */
export const CHAT_MAX_ACTIVE_SUBSCRIPTIONS = 64;
export const CHAT_WIRE_MAX_RESUME_CURSORS = CHAT_MAX_ACTIVE_SUBSCRIPTIONS;
export const CHAT_WIRE_MAX_GAP_EVENTS = 250;
export const CHAT_WIRE_MAX_CLIENT_JSON_LENGTH = 256 * 1024;
export const CHAT_WIRE_MAX_SERVER_JSON_LENGTH = 4 * 1024 * 1024;
const MAX_TOKEN_LENGTH = 8_192;
const MAX_IDENTIFIER_LENGTH = 128;
const MAX_MENTION_LABEL_LENGTH = 300;
const MAX_I18N_KEY_LENGTH = 160;
const SAFE_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:~-]*$/;
const CATALOG_I18N_KEY_PATTERN = /^[a-z][a-z0-9]*\.errors\.[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)*$/;
export type ChatResumeCursorEntry = {
chatId: string;
afterCursor: string;
};
export type ChatAuthenticateFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.authenticate;
token: string;
resumeCursors: ChatResumeCursorEntry[];
};
export type ChatSubscribeFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.subscribe;
chatId: string;
afterCursor: string;
};
export type ChatUnsubscribeFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.unsubscribe;
chatId: string;
};
export type ChatSendMessageFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.sendMessage;
chatId: string;
requestId: string;
clientMessageId: string;
body: string;
mentions: ChatMention[];
};
export type ChatTypingFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.typing;
chatId: string;
status: "started" | "stopped";
};
export type ChatPresenceFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.presence;
status: "online" | "away";
};
export type ChatMarkReadFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.markRead;
chatId: string;
messageId: string;
requestId: string;
};
export type ChatPingFrame = {
type: typeof CHAT_CLIENT_FRAME_TYPES.ping;
};
export type ChatClientFrame =
| ChatAuthenticateFrame
| ChatSubscribeFrame
| ChatUnsubscribeFrame
| ChatSendMessageFrame
| ChatTypingFrame
| ChatPresenceFrame
| ChatMarkReadFrame
| ChatPingFrame;
export type ChatSubscriptionResult =
| {
status: "ok";
events: ChatPersistentEvent[];
nextCursor: string;
hasMore: boolean;
}
| {
status: "reset_required";
currentStreamId: string;
};
export type ChatReadyFrame = {
type: typeof CHAT_SERVER_FRAME_TYPES.ready;
connectionId: string;
};
export type ChatSubscribedFrame = {
type: typeof CHAT_SERVER_FRAME_TYPES.subscribed;
chatId: string;
result: ChatSubscriptionResult;
};
export type ChatEventFrame = {
type: typeof CHAT_SERVER_FRAME_TYPES.event;
event: ChatServerEvent;
};
export type ChatErrorFrame = {
type: typeof CHAT_SERVER_FRAME_TYPES.error;
i18nKey: string;
retryable: boolean;
requestId?: string;
clientMessageId?: string;
};
export type ChatPongFrame = {
type: typeof CHAT_SERVER_FRAME_TYPES.pong;
};
export type ChatServerFrame = ChatReadyFrame | ChatSubscribedFrame | ChatEventFrame | ChatErrorFrame | ChatPongFrame;
export function validateChatClientFrame(input: unknown): ChatClientFrame {
const frame = requirePlainRecord(input, "chat client frame");
switch (frame.type) {
case CHAT_CLIENT_FRAME_TYPES.authenticate:
assertAllowedKeys(frame, new Set(["type", "token", "resumeCursors"]), "authenticate frame");
return {
type: CHAT_CLIENT_FRAME_TYPES.authenticate,
token: normalizeToken(frame.token),
resumeCursors: normalizeResumeCursors(frame.resumeCursors),
};
case CHAT_CLIENT_FRAME_TYPES.subscribe:
assertAllowedKeys(frame, new Set(["type", "chatId", "afterCursor"]), "subscribe frame");
return {
type: CHAT_CLIENT_FRAME_TYPES.subscribe,
chatId: normalizeIdentifier(frame.chatId, "chatId"),
afterCursor: normalizeChatResumeCursor(frame.afterCursor),
};
case CHAT_CLIENT_FRAME_TYPES.unsubscribe:
assertAllowedKeys(frame, new Set(["type", "chatId"]), "unsubscribe frame");
return {
type: CHAT_CLIENT_FRAME_TYPES.unsubscribe,
chatId: normalizeIdentifier(frame.chatId, "chatId"),
};
case CHAT_CLIENT_FRAME_TYPES.sendMessage:
assertAllowedKeys(frame, new Set(["type", "chatId", "requestId", "clientMessageId", "body", "mentions"]), "send_message frame");
return {
type: CHAT_CLIENT_FRAME_TYPES.sendMessage,
chatId: normalizeIdentifier(frame.chatId, "chatId"),
requestId: normalizeIdentifier(frame.requestId, "requestId"),
clientMessageId: normalizeIdentifier(frame.clientMessageId, "clientMessageId"),
body: normalizeMessageBody(frame.body),
mentions: normalizeMentions(frame.mentions),
};
case CHAT_CLIENT_FRAME_TYPES.typing:
assertAllowedKeys(frame, new Set(["type", "chatId", "status"]), "typing frame");
if (frame.status !== "started" && frame.status !== "stopped") {
throw new Error("typing status must be started or stopped");
}
return {
type: CHAT_CLIENT_FRAME_TYPES.typing,
chatId: normalizeIdentifier(frame.chatId, "chatId"),
status: frame.status,
};
case CHAT_CLIENT_FRAME_TYPES.presence:
assertAllowedKeys(frame, new Set(["type", "status"]), "presence frame");
if (frame.status !== "online" && frame.status !== "away") {
throw new Error("presence status must be online or away");
}
return { type: CHAT_CLIENT_FRAME_TYPES.presence, status: frame.status };
case CHAT_CLIENT_FRAME_TYPES.markRead:
assertAllowedKeys(frame, new Set(["type", "chatId", "messageId", "requestId"]), "mark_read frame");
return {
type: CHAT_CLIENT_FRAME_TYPES.markRead,
chatId: normalizeIdentifier(frame.chatId, "chatId"),
messageId: normalizeIdentifier(frame.messageId, "messageId"),
requestId: normalizeIdentifier(frame.requestId, "requestId"),
};
case CHAT_CLIENT_FRAME_TYPES.ping:
assertAllowedKeys(frame, new Set(["type"]), "ping frame");
return { type: CHAT_CLIENT_FRAME_TYPES.ping };
default:
throw new Error("type must be a supported chat client frame type");
}
}
export function validateChatServerFrame(input: unknown): ChatServerFrame {
const frame = requirePlainRecord(input, "chat server frame");
switch (frame.type) {
case CHAT_SERVER_FRAME_TYPES.ready:
assertAllowedKeys(frame, new Set(["type", "connectionId"]), "ready frame");
return {
type: CHAT_SERVER_FRAME_TYPES.ready,
connectionId: normalizeIdentifier(frame.connectionId, "connectionId"),
};
case CHAT_SERVER_FRAME_TYPES.subscribed: {
assertAllowedKeys(frame, new Set(["type", "chatId", "result"]), "subscribed frame");
const chatId = normalizeIdentifier(frame.chatId, "chatId");
return {
type: CHAT_SERVER_FRAME_TYPES.subscribed,
chatId,
result: normalizeSubscriptionResult(frame.result, chatId),
};
}
case CHAT_SERVER_FRAME_TYPES.event:
assertAllowedKeys(frame, new Set(["type", "event"]), "event frame");
return {
type: CHAT_SERVER_FRAME_TYPES.event,
event: validateChatServerEvent(frame.event),
};
case CHAT_SERVER_FRAME_TYPES.error: {
assertAllowedKeys(frame, new Set(["type", "i18nKey", "retryable", "requestId", "clientMessageId"]), "error frame");
if (typeof frame.retryable !== "boolean") {
throw new Error("error retryable must be a boolean");
}
const requestId = normalizeOptionalIdentifier(frame.requestId, "requestId");
const clientMessageId = normalizeOptionalIdentifier(frame.clientMessageId, "clientMessageId");
return {
type: CHAT_SERVER_FRAME_TYPES.error,
i18nKey: normalizeCatalogI18nKey(frame.i18nKey),
retryable: frame.retryable,
...(requestId === undefined ? {} : { requestId }),
...(clientMessageId === undefined ? {} : { clientMessageId }),
};
}
case CHAT_SERVER_FRAME_TYPES.pong:
assertAllowedKeys(frame, new Set(["type"]), "pong frame");
return { type: CHAT_SERVER_FRAME_TYPES.pong };
default:
throw new Error("type must be a supported chat server frame type");
}
}
export function isChatClientFrame(input: unknown): input is ChatClientFrame {
try {
validateChatClientFrame(input);
return true;
} catch {
return false;
}
}
export function isChatServerFrame(input: unknown): input is ChatServerFrame {
try {
validateChatServerFrame(input);
return true;
} catch {
return false;
}
}
export function parseChatClientFrameJson(raw: unknown): ChatClientFrame {
return validateChatClientFrame(parseFrameJson(raw, "chat client frame", CHAT_WIRE_MAX_CLIENT_JSON_LENGTH));
}
export function parseChatServerFrameJson(raw: unknown): ChatServerFrame {
return validateChatServerFrame(parseFrameJson(raw, "chat server frame", CHAT_WIRE_MAX_SERVER_JSON_LENGTH));
}
export function serializeChatClientFrame(input: unknown): string {
return serializeFrameJson(validateChatClientFrame(input), "chat client frame", CHAT_WIRE_MAX_CLIENT_JSON_LENGTH);
}
export function serializeChatServerFrame(input: unknown): string {
return serializeFrameJson(validateChatServerFrame(input), "chat server frame", CHAT_WIRE_MAX_SERVER_JSON_LENGTH);
}
function normalizeResumeCursors(value: unknown): ChatResumeCursorEntry[] {
if (!Array.isArray(value)) {
throw new Error("resumeCursors must be an array");
}
if (value.length > CHAT_WIRE_MAX_RESUME_CURSORS) {
throw new Error("resumeCursors contains too many entries");
}
const seenChatIds = new Set<string>();
return value.map((entry, index) => {
const cursor = requirePlainRecord(entry, `resumeCursors[${index}]`);
assertAllowedKeys(cursor, new Set(["chatId", "afterCursor"]), `resumeCursors[${index}]`);
const chatId = normalizeIdentifier(cursor.chatId, `resumeCursors[${index}].chatId`);
if (seenChatIds.has(chatId)) {
throw new Error("resumeCursors must not contain duplicate chatId values");
}
seenChatIds.add(chatId);
return {
chatId,
afterCursor: normalizeChatResumeCursor(cursor.afterCursor),
};
});
}
function normalizeMentions(value: unknown): ChatMention[] {
if (!Array.isArray(value)) {
throw new Error("mentions must be an array");
}
if (value.length > CHAT_MESSAGE_MAX_MENTIONS) {
throw new Error("mentions contains too many entries");
}
const seenMentions = new Set<string>();
return value.map((entry, index) => {
const mention = requirePlainRecord(entry, `mentions[${index}]`);
assertAllowedKeys(mention, new Set(["type", "id", "label"]), `mentions[${index}]`);
const type = normalizeMentionType(mention.type, `mentions[${index}].type`);
const id = normalizeIdentifier(mention.id, `mentions[${index}].id`);
const deduplicationKey = `${type}:${id}`;
if (seenMentions.has(deduplicationKey)) {
throw new Error("mentions must not contain duplicate targets");
}
seenMentions.add(deduplicationKey);
return {
type,
id,
label: normalizeOptionalLabel(mention.label, `mentions[${index}].label`),
};
});
}
function normalizeSubscriptionResult(value: unknown, chatId: string): ChatSubscriptionResult {
const result = requirePlainRecord(value, "subscription result");
if (result.status === "reset_required") {
assertAllowedKeys(result, new Set(["status", "currentStreamId"]), "reset subscription result");
return {
status: "reset_required",
currentStreamId: normalizeStreamId(result.currentStreamId),
};
}
if (result.status !== "ok") {
throw new Error("subscription result status must be ok or reset_required");
}
assertAllowedKeys(result, new Set(["status", "events", "nextCursor", "hasMore"]), "gap subscription result");
if (!Array.isArray(result.events)) {
throw new Error("subscription result events must be an array");
}
if (result.events.length > CHAT_WIRE_MAX_GAP_EVENTS) {
throw new Error("subscription result contains too many events");
}
if (typeof result.hasMore !== "boolean") {
throw new Error("subscription result hasMore must be a boolean");
}
if (result.hasMore && result.events.length === 0) {
throw new Error("subscription result cannot have more events after an empty page");
}
const events = result.events.map((entry, index) => {
const event = validateChatServerEvent(entry);
if (!isPersistentChatEvent(event)) {
throw new Error(`subscription result events[${index}] must be persistent`);
}
if (event.chatId !== chatId) {
throw new Error(`subscription result events[${index}] chatId does not match the subscribed chat`);
}
return event;
});
assertAscendingGapEvents(events);
const nextCursor = normalizeChatResumeCursor(result.nextCursor);
const lastEvent = events.at(-1);
if (lastEvent && lastEvent.cursor !== nextCursor) {
throw new Error("subscription result nextCursor must match the final event cursor");
}
return {
status: "ok",
events,
nextCursor,
hasMore: result.hasMore,
};
}
function assertAscendingGapEvents(events: readonly ChatPersistentEvent[]): void {
let tenantId: string | null = null;
let streamId: string | null = null;
let previousSequence = -1n;
for (const event of events) {
const parsedCursor = parseChatResumeCursor(event.cursor);
if (parsedCursor.streamId === null) {
throw new Error("subscription event cursor must reference a persisted stream");
}
if (tenantId !== null && event.tenantId !== tenantId) {
throw new Error("subscription result events must belong to one tenant");
}
if (streamId !== null && parsedCursor.streamId !== streamId) {
throw new Error("subscription result events must belong to one stream generation");
}
const sequence = BigInt(parsedCursor.sequence);
if (sequence <= previousSequence) {
throw new Error("subscription result event cursors must be strictly ascending");
}
tenantId = event.tenantId;
streamId = parsedCursor.streamId;
previousSequence = sequence;
}
}
function normalizeToken(value: unknown): string {
if (typeof value !== "string") {
throw new Error("authenticate token must be a string");
}
if (!value || value !== value.trim() || value.length > MAX_TOKEN_LENGTH || /[\u0000-\u001f\u007f]/u.test(value)) {
throw new Error("authenticate token is invalid");
}
return value;
}
function normalizeMessageBody(value: unknown): string {
if (typeof value !== "string") {
throw new Error("body must be a string");
}
if (!value.trim()) {
throw new Error("body must not be empty");
}
if (value.length > CHAT_MESSAGE_MAX_BODY_LENGTH) {
throw new Error(`body exceeds its maximum length of ${CHAT_MESSAGE_MAX_BODY_LENGTH}`);
}
if (value.includes("\u0000")) {
throw new Error("body contains an unsupported control character");
}
return value;
}
function normalizeMentionType(value: unknown, label: string): ChatMentionType {
if (value !== "user" && value !== "project" && value !== "contact" && value !== "company") {
throw new Error(`${label} must be a supported mention type`);
}
return value;
}
function normalizeOptionalLabel(value: unknown, label: string): string | null {
if (value === undefined || value === null) return null;
if (typeof value !== "string") {
throw new Error(`${label} must be a string or null`);
}
const normalized = value.trim();
if (!normalized || normalized.length > MAX_MENTION_LABEL_LENGTH || /[\u0000-\u001f\u007f]/u.test(normalized)) {
throw new Error(`${label} is invalid`);
}
return normalized;
}
function normalizeCatalogI18nKey(value: unknown): string {
if (typeof value !== "string" || value.length > MAX_I18N_KEY_LENGTH || !CATALOG_I18N_KEY_PATTERN.test(value)) {
throw new Error("error i18nKey must be a catalog error key");
}
return value;
}
function normalizeStreamId(value: unknown): string {
if (typeof value !== "string") {
throw new Error("currentStreamId must be a string");
}
const parsed = parseChatResumeCursor(`${value}:1`);
if (parsed.streamId === null) {
throw new Error("currentStreamId must be a canonical stream identifier");
}
return parsed.streamId;
}
function normalizeIdentifier(value: unknown, label: string): string {
if (typeof value !== "string") {
throw new Error(`${label} must be a string`);
}
const normalized = value.trim();
if (!normalized || normalized.length > MAX_IDENTIFIER_LENGTH || !SAFE_IDENTIFIER_PATTERN.test(normalized)) {
throw new Error(`${label} must be a safe identifier`);
}
return normalized;
}
function normalizeOptionalIdentifier(value: unknown, label: string): string | undefined {
if (value === undefined) return undefined;
return normalizeIdentifier(value, label);
}
function requirePlainRecord(value: unknown, label: string): Record<string, unknown> {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
throw new Error(`${label} must be a plain object`);
}
return value as Record<string, unknown>;
}
function assertAllowedKeys(value: Record<string, unknown>, allowedKeys: ReadonlySet<string>, label: string): void {
for (const key of Object.keys(value)) {
if (!allowedKeys.has(key)) {
throw new Error(`${label} contains an unsupported key`);
}
}
}
function parseFrameJson(raw: unknown, label: string, maxLength: number): unknown {
if (typeof raw !== "string") {
throw new Error(`${label} JSON must be a string`);
}
if (raw.length > maxLength) {
throw new Error(`${label} JSON exceeds its maximum length`);
}
try {
return JSON.parse(raw) as unknown;
} catch {
throw new Error(`${label} must contain valid JSON`);
}
}
function serializeFrameJson(value: ChatClientFrame | ChatServerFrame, label: string, maxLength: number): string {
const serialized = JSON.stringify(value);
if (serialized.length > maxLength) {
throw new Error(`${label} JSON exceeds its maximum length`);
}
return serialized;
}
@@ -5,7 +5,15 @@ describe("@hivegrid/realtime public entrypoint", () => {
const entrypoint = await import("./index.js");
expect(entrypoint.REALTIME_EVENT_NAMES.notificationSnapshot).toBe("notification.snapshot");
expect(entrypoint.CHAT_EVENT_NAMES.messageCreated).toBe("chat.message.created");
expect(entrypoint.validateRealtimeEvent).toBeTypeOf("function");
expect(entrypoint.validateChatServerEvent).toBeTypeOf("function");
expect(entrypoint.parseChatResumeCursor).toBeTypeOf("function");
expect(entrypoint.assertChatEventInScope).toBeTypeOf("function");
expect(entrypoint.validateChatClientFrame).toBeTypeOf("function");
expect(entrypoint.validateChatServerFrame).toBeTypeOf("function");
expect(entrypoint.createChatRealtimeClient).toBeTypeOf("function");
expect(entrypoint.CHAT_MAX_ACTIVE_SUBSCRIPTIONS).toBe(64);
expect(entrypoint.isRealtimeEvent).toBeTypeOf("function");
expect(entrypoint.subscribeToRealtime).toBeTypeOf("function");
});
@@ -1,4 +1,9 @@
export * from "./client.js";
export * from "./chat-client.js";
export * from "./chat-events.js";
export * from "./chat-guards.js";
export * from "./chat-mentions.js";
export * from "./chat-wire.js";
export * from "./events.js";
export * from "./guards.js";
export * from "./server.js";