diff --git a/.env.example b/.env.example index b7c8ade..921d211 100644 --- a/.env.example +++ b/.env.example @@ -21,5 +21,7 @@ NODE_ENV="development" WEB_APP_URL="http://localhost:7153" # --- apps/web --- -# Public URL of the API consumed by the frontend -VITE_API_URL="http://localhost:4100" +# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so +# you normally leave this unset. Only set it to point the frontend at a +# different API origin; the client always appends /api to it. +# VITE_API_URL="" diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 05416f1..6733eba 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -39,12 +39,14 @@ export function createApp() { ) }) - // BetterAuth owns every route under /api/auth/*. + // Every API route lives under /api: in production nginx serves the SPA on the + // root and proxies /api/* to this server, so unprefixed paths would collide + // with client routes (/lists, /invitations, ...). BetterAuth owns /api/auth/*. app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw)) - app.route('/health', healthModule) - app.route('/lists', listsModule) - app.route('/invitations', invitationsModule) + app.route('/api/health', healthModule) + app.route('/api/lists', listsModule) + app.route('/api/invitations', invitationsModule) app.notFound(notFoundHandler) app.onError(errorHandler) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 83c801b..04cbdb3 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -9,5 +9,14 @@ logger.info({ port }, 'api listening') export default { port, - fetch: app.fetch, + fetch(req: Request, server: Bun.Server) { + // SSE streams stay open while the list is quiet: without this, Bun closes + // the connection after its 10s idle timeout. Heartbeats are not enough on + // their own because they are sent less often than the default timeout. + if (new URL(req.url).pathname.endsWith('/events')) { + server.timeout(req, 0) + } + + return app.fetch(req) + }, } diff --git a/apps/api/src/lib/events.test.ts b/apps/api/src/lib/events.test.ts new file mode 100644 index 0000000..098ec72 --- /dev/null +++ b/apps/api/src/lib/events.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'bun:test' +import type { ListEvent, ListItem } from '@superlist/shared' + +import { ListEvents } from './events' + +const item: ListItem = { + id: 'item-1', + listId: 'list-1', + name: 'Leche', + completed: false, + boughtAt: null, + quantity: null, + notes: null, + order: 0, + createdAt: '2026-10-16T10:00:00.000Z', + updatedAt: '2026-10-16T10:00:00.000Z', +} + +describe('ListEvents', () => { + it('delivers an event to the subscribers of its list', () => { + const bus = new ListEvents() + const received: ListEvent[] = [] + bus.subscribe('list-1', (event) => received.push(event)) + + const event: ListEvent = { type: 'item.created', listId: 'list-1', item } + bus.publish(event) + + expect(received).toEqual([event]) + }) + + it('does not deliver to the subscribers of another list', () => { + const bus = new ListEvents() + const received: ListEvent[] = [] + bus.subscribe('list-2', (event) => received.push(event)) + + bus.publish({ type: 'item.created', listId: 'list-1', item }) + + expect(received).toHaveLength(0) + }) + + it('delivers to every subscriber of the same list', () => { + const bus = new ListEvents() + const first: ListEvent[] = [] + const second: ListEvent[] = [] + bus.subscribe('list-1', (event) => first.push(event)) + bus.subscribe('list-1', (event) => second.push(event)) + + bus.publish({ type: 'item.updated', listId: 'list-1', item }) + + expect(first).toHaveLength(1) + expect(second).toHaveLength(1) + }) + + it('stops delivering after unsubscribe', () => { + const bus = new ListEvents() + const received: ListEvent[] = [] + const unsubscribe = bus.subscribe('list-1', (event) => received.push(event)) + + unsubscribe() + bus.publish({ type: 'item.created', listId: 'list-1', item }) + + expect(received).toHaveLength(0) + }) +}) diff --git a/apps/api/src/lib/events.ts b/apps/api/src/lib/events.ts new file mode 100644 index 0000000..54b9702 --- /dev/null +++ b/apps/api/src/lib/events.ts @@ -0,0 +1,38 @@ +import type { ListEvent } from '@superlist/shared' + +type ListEventListener = (event: ListEvent) => void + +/** + * In-process pub/sub used to fan out list changes to the SSE streams of every + * member currently viewing a list. + * + * It only reaches the API instance that published the event, which is enough + * for a single-instance deployment. Scaling horizontally would need a shared + * bus (e.g. Postgres `LISTEN`/`NOTIFY`); this interface would stay the same. + */ +export class ListEvents { + private readonly listeners = new Map>() + + /** Subscribes to one list's events; returns the unsubscribe function. */ + subscribe(listId: string, listener: ListEventListener): () => void { + const listeners = this.listeners.get(listId) ?? new Set() + listeners.add(listener) + this.listeners.set(listId, listeners) + + return () => { + listeners.delete(listener) + if (listeners.size === 0) this.listeners.delete(listId) + } + } + + /** Delivers the event to every subscriber of its list. */ + publish(event: ListEvent): void { + const listeners = this.listeners.get(event.listId) + if (!listeners) return + + for (const listener of listeners) listener(event) + } +} + +/** Process-wide bus shared by the use cases and the SSE routes. */ +export const listEvents = new ListEvents() diff --git a/apps/api/src/lib/list-access.ts b/apps/api/src/lib/list-access.ts new file mode 100644 index 0000000..f7da645 --- /dev/null +++ b/apps/api/src/lib/list-access.ts @@ -0,0 +1,27 @@ +import { problems } from '@superlist/shared' +import type { MiddlewareHandler } from 'hono' +import { prisma } from '@/lib/prisma' +import { problemResponse } from '@/lib/problem-details' +import type { AppEnv } from '@/types' + +/** + * Guards a `/:listId/*` route so only members of the list reach it. Expects + * `requireSession` to have run first (it reads `c.get('user')`). + */ +export const requireListMembership: MiddlewareHandler = async (c, next) => { + const listId = c.req.param('listId') + + if (!listId) { + return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.')) + } + + const membership = await prisma.shoppingListMember.findUnique({ + where: { listId_userId: { listId, userId: c.get('user').id } }, + }) + + if (!membership) { + return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.')) + } + + await next() +} diff --git a/apps/api/src/lib/list-membership.ts b/apps/api/src/lib/list-membership.ts index 2cbb006..7332346 100644 --- a/apps/api/src/lib/list-membership.ts +++ b/apps/api/src/lib/list-membership.ts @@ -1,3 +1,4 @@ +import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' /** @@ -12,6 +13,7 @@ import type { Database } from '@/lib/prisma' export async function acceptPendingInvitations( db: Database, { userId, email }: { userId: string; email: string }, + events: ListEvents = listEvents, ): Promise { const pending = await db.shoppingListInvitation.findMany({ where: { email, status: 'pending', expiresAt: { gt: new Date() } }, @@ -29,6 +31,8 @@ export async function acceptPendingInvitations( data: { status: 'accepted', acceptedAt: new Date() }, }), ]) + + events.publish({ type: 'member.added', listId: invitation.listId, userId }) } return pending.length diff --git a/apps/api/src/modules/invitations/accept/use-case.test.ts b/apps/api/src/modules/invitations/accept/use-case.test.ts index 7f02b3d..5f7279a 100644 --- a/apps/api/src/modules/invitations/accept/use-case.test.ts +++ b/apps/api/src/modules/invitations/accept/use-case.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'bun:test' +import type { ListEvent } from '@superlist/shared' +import { ListEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' import { AcceptInvitation } from './use-case' @@ -46,6 +48,14 @@ function createDb({ return { db: db as unknown as Database, updates, created } } +function createBus() { + const events = new ListEvents() + const published: ListEvent[] = [] + events.subscribe('list-1', (event) => published.push(event)) + + return { events, published } +} + describe('AcceptInvitation', () => { it('answers 404 for an unknown token', async () => { const { db } = createDb({ invitation: undefined }) @@ -79,7 +89,8 @@ describe('AcceptInvitation', () => { invitation: INVITATION, membership: { id: 'member-1' }, }) - const result = await new AcceptInvitation(db, () => NOW).execute({ + const { events, published } = createBus() + const result = await new AcceptInvitation(db, () => NOW, events).execute({ token: INVITATION.id, userId: 'user-1', email: 'beto@ejemplo.com', @@ -89,6 +100,7 @@ describe('AcceptInvitation', () => { if (!result.ok) throw new Error('expected the use case to succeed') expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' }) expect(updates).toHaveLength(0) + expect(published).toHaveLength(0) }) it('answers 400 and marks expired invitations', async () => { @@ -111,9 +123,10 @@ describe('AcceptInvitation', () => { expect(created).toHaveLength(0) }) - it('grants access and marks the invitation as accepted', async () => { + it('grants access, marks the invitation as accepted and publishes member.added', async () => { const { db, updates, created } = createDb({ invitation: INVITATION }) - const result = await new AcceptInvitation(db, () => NOW).execute({ + const { events, published } = createBus() + const result = await new AcceptInvitation(db, () => NOW, events).execute({ token: INVITATION.id, userId: 'user-1', // Compared in lower case, so the casing of the session email does not matter. @@ -129,5 +142,6 @@ describe('AcceptInvitation', () => { }, ]) expect(updates).toHaveLength(1) + expect(published).toEqual([{ type: 'member.added', listId: 'list-1', userId: 'user-1' }]) }) }) diff --git a/apps/api/src/modules/invitations/accept/use-case.ts b/apps/api/src/modules/invitations/accept/use-case.ts index 47cd443..52aabe1 100644 --- a/apps/api/src/modules/invitations/accept/use-case.ts +++ b/apps/api/src/modules/invitations/accept/use-case.ts @@ -7,6 +7,7 @@ import { type Result, } from '@superlist/shared' +import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' /** Accepts an invitation for the signed-in user, matching it by token and email. */ @@ -14,6 +15,7 @@ export class AcceptInvitation { constructor( private readonly db: Database, private readonly now: () => Date = () => new Date(), + private readonly events: ListEvents = listEvents, ) {} async execute(input: { @@ -66,6 +68,8 @@ export class AcceptInvitation { }), ]) + this.events.publish({ type: 'member.added', listId: invitation.listId, userId: input.userId }) + return Ok({ listId: invitation.list.id, listName: invitation.list.name }) } } diff --git a/apps/api/src/modules/invitations/create/use-case.ts b/apps/api/src/modules/invitations/create/use-case.ts index 5c19dd6..ea1bc77 100644 --- a/apps/api/src/modules/invitations/create/use-case.ts +++ b/apps/api/src/modules/invitations/create/use-case.ts @@ -10,6 +10,7 @@ import { } from '@superlist/shared' import { invitationEmail } from '@/lib/emails/invitation' +import { type ListEvents, listEvents } from '@/lib/events' import { logger } from '@/lib/logger' import { type Email, sendEmail } from '@/lib/mailer' import type { Database } from '@/lib/prisma' @@ -24,6 +25,7 @@ type CreateInvitationDependencies = { mailer?: Mailer now?: () => Date generateToken?: () => string + events?: ListEvents } /** @@ -37,6 +39,7 @@ export class CreateInvitation { private readonly mailer: Mailer private readonly now: () => Date private readonly generateToken: () => string + private readonly events: ListEvents constructor( private readonly db: Database, @@ -45,6 +48,7 @@ export class CreateInvitation { this.mailer = dependencies.mailer ?? sendEmail this.now = dependencies.now ?? (() => new Date()) this.generateToken = dependencies.generateToken ?? (() => randomUUID()) + this.events = dependencies.events ?? listEvents } async execute(input: { @@ -129,6 +133,8 @@ export class CreateInvitation { } if (invitedUser) { + this.events.publish({ type: 'member.added', listId: input.listId, userId: invitedUser.id }) + // Best effort: the person already sees the list, so a mail failure is not fatal. await this.mailer(message).catch((error: unknown) => { logger.warn({ err: error, to: email }, 'could not send the invitation email') @@ -149,6 +155,8 @@ export class CreateInvitation { ) } + this.events.publish({ type: 'invitation.created', listId: input.listId, email }) + return Ok({ status: 'invited', email }) } } diff --git a/apps/api/src/modules/lists/events/route.ts b/apps/api/src/modules/lists/events/route.ts new file mode 100644 index 0000000..0262c72 --- /dev/null +++ b/apps/api/src/modules/lists/events/route.ts @@ -0,0 +1,75 @@ +import type { ListEvent } from '@superlist/shared' +import { Hono } from 'hono' +import { streamSSE } from 'hono/streaming' + +import { requireSession } from '@/lib/auth-session' +import { listEvents } from '@/lib/events' +import { requireListMembership } from '@/lib/list-access' +import { validate } from '@/lib/validate' +import { ListParamsSchema } from '@/modules/lists/schema' +import type { AppEnv } from '@/types' + +/** Maximum silence between frames; a comment heartbeat is sent in between. */ +const HEARTBEAT_MS = 20_000 + +/** + * GET /lists/:listId/events — Server-Sent Events stream with the changes + * happening on a list (items, members, invitations). Members only. + * + * Events are buffered and written as they arrive; while the list is quiet a + * comment heartbeat keeps the connection open through Bun's idle timeout and + * any proxy in between. + */ +export const listEventsRoute = new Hono().get( + '/', + requireSession, + validate.param(ListParamsSchema), + requireListMembership, + (c) => { + const { listId } = c.req.valid('param') + + return streamSSE(c, async (stream) => { + const pending: ListEvent[] = [] + + // Resolves a pending wait as soon as an event is buffered, so nothing has + // to wait for the heartbeat interval. + let wake: (() => void) | undefined + const unsubscribe = listEvents.subscribe(listId, (event) => { + pending.push(event) + wake?.() + }) + + stream.onAbort(() => unsubscribe()) + + const waitForEvent = () => + new Promise((resolve) => { + wake = resolve + }) + + await stream.writeSSE({ event: 'ready', data: JSON.stringify({ listId }) }) + + while (!stream.aborted) { + const event = pending.shift() + + if (event) { + await stream.writeSSE({ event: event.type, data: JSON.stringify(event) }) + continue + } + + let timer: ReturnType | undefined + await Promise.race([ + waitForEvent(), + new Promise((resolve) => { + timer = setTimeout(resolve, HEARTBEAT_MS) + }), + ]) + clearTimeout(timer) + wake = undefined + + if (pending.length === 0 && !stream.aborted) { + await stream.write(': ping\n\n') + } + } + }) + }, +) diff --git a/apps/api/src/modules/lists/index.ts b/apps/api/src/modules/lists/index.ts index 90d39c2..59e5d78 100644 --- a/apps/api/src/modules/lists/index.ts +++ b/apps/api/src/modules/lists/index.ts @@ -3,6 +3,7 @@ import { Hono } from 'hono' import type { AppEnv } from '@/types' import { createListRoute } from './create/route' +import { listEventsRoute } from './events/route' import { getListRoute } from './get/route' import { listItemsModule } from './items' import { listListsRoute } from './list/route' @@ -17,3 +18,4 @@ export const listsModule = new Hono() .route('/', updateListRoute) .route('/', setPrimaryListRoute) .route('/:listId/items', listItemsModule) + .route('/:listId/events', listEventsRoute) diff --git a/apps/api/src/modules/lists/items/create/use-case.test.ts b/apps/api/src/modules/lists/items/create/use-case.test.ts new file mode 100644 index 0000000..b9e7358 --- /dev/null +++ b/apps/api/src/modules/lists/items/create/use-case.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'bun:test' +import type { ListEvent } from '@superlist/shared' + +import { ListEvents } from '@/lib/events' +import type { Database } from '@/lib/prisma' + +import { CreateItem } from './use-case' + +type ItemRow = { + id: string + shoppingListId: string + name: string + completed: boolean + boughtAt: Date | null + quantity: string | null + notes: string | null + order: number + createdAt: Date + updatedAt: Date +} + +const now = new Date('2026-10-16T10:00:00.000Z') + +function itemRow(input: { + name: string + quantity?: string | null + notes?: string | null +}): ItemRow { + return { + id: 'item-1', + shoppingListId: 'list-1', + name: input.name, + completed: false, + boughtAt: null, + quantity: input.quantity ?? null, + notes: input.notes ?? null, + order: 0, + createdAt: now, + updatedAt: now, + } +} + +function createDb(options: { membership: unknown; item: ItemRow }) { + const created: unknown[] = [] + + const db = { + shoppingListMember: { + findUnique: async () => options.membership, + }, + listItem: { + create: async (args: unknown) => { + created.push(args) + return options.item + }, + }, + } + + return { db: db as unknown as Database, created } +} + +function createBus() { + const events = new ListEvents() + const published: ListEvent[] = [] + events.subscribe('list-1', (event) => published.push(event)) + + return { events, published } +} + +describe('CreateItem', () => { + it('answers 404 when the user does not belong to the list', async () => { + const { db, created } = createDb({ membership: null, item: itemRow({ name: 'Leche' }) }) + const { events, published } = createBus() + const result = await new CreateItem(db, events).execute({ + listId: 'list-1', + userId: 'user-1', + name: 'Leche', + }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(404) + expect(created).toHaveLength(0) + expect(published).toHaveLength(0) + }) + + it('creates the item and publishes item.created', async () => { + const { db } = createDb({ + membership: { role: 'collaborator' }, + item: itemRow({ name: 'Leche', quantity: '1 L' }), + }) + const { events, published } = createBus() + const result = await new CreateItem(db, events).execute({ + listId: 'list-1', + userId: 'user-1', + name: 'Leche', + quantity: '1 L', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(result.value.name).toBe('Leche') + expect(published).toEqual([{ type: 'item.created', listId: 'list-1', item: result.value }]) + }) +}) diff --git a/apps/api/src/modules/lists/items/create/use-case.ts b/apps/api/src/modules/lists/items/create/use-case.ts index da81c1a..a6c21cf 100644 --- a/apps/api/src/modules/lists/items/create/use-case.ts +++ b/apps/api/src/modules/lists/items/create/use-case.ts @@ -7,13 +7,17 @@ import { type Result, } from '@superlist/shared' +import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' import { toListItem } from '../serialize' /** Adds an item to a shopping list. Only members can add items. */ export class CreateItem { - constructor(private readonly db: Database) {} + constructor( + private readonly db: Database, + private readonly events: ListEvents = listEvents, + ) {} async execute(input: { listId: string @@ -39,6 +43,9 @@ export class CreateItem { }, }) - return Ok(toListItem(item)) + const created = toListItem(item) + this.events.publish({ type: 'item.created', listId: input.listId, item: created }) + + return Ok(created) } } diff --git a/apps/api/src/modules/lists/items/update/use-case.test.ts b/apps/api/src/modules/lists/items/update/use-case.test.ts index cd15855..f36a361 100644 --- a/apps/api/src/modules/lists/items/update/use-case.test.ts +++ b/apps/api/src/modules/lists/items/update/use-case.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'bun:test' +import type { ListEvent } from '@superlist/shared' +import { ListEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' import { UpdateItem } from './use-case' @@ -53,10 +55,19 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) { return { db: db as unknown as Database, updates } } +function createBus() { + const events = new ListEvents() + const published: ListEvent[] = [] + events.subscribe('list-1', (event) => published.push(event)) + + return { events, published } +} + describe('UpdateItem', () => { it('answers 404 when the user does not belong to the list', async () => { const { db, updates } = createDb({ membership: null, item: itemRow(false, null) }) - const result = await new UpdateItem(db).execute({ + const { events, published } = createBus() + const result = await new UpdateItem(db, events).execute({ listId: 'list-1', itemId: 'item-1', userId: 'user-1', @@ -67,11 +78,13 @@ describe('UpdateItem', () => { if (result.ok) throw new Error('expected the use case to fail') expect(result.error.status).toBe(404) expect(updates).toHaveLength(0) + expect(published).toHaveLength(0) }) it('answers 404 when the item does not belong to the list', async () => { const { db, updates } = createDb({ membership: { role: 'owner' }, item: null }) - const result = await new UpdateItem(db).execute({ + const { events, published } = createBus() + const result = await new UpdateItem(db, events).execute({ listId: 'list-1', itemId: 'item-of-another-list', userId: 'user-1', @@ -82,11 +95,13 @@ describe('UpdateItem', () => { if (result.ok) throw new Error('expected the use case to fail') expect(result.error.status).toBe(404) expect(updates).toHaveLength(0) + expect(published).toHaveLength(0) }) - it('marks the item as bought and records boughtAt', async () => { + it('marks the item as bought and publishes item.updated', async () => { const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) - const result = await new UpdateItem(db).execute({ + const { events, published } = createBus() + const result = await new UpdateItem(db, events).execute({ listId: 'list-1', itemId: 'item-1', userId: 'user-1', @@ -103,14 +118,17 @@ describe('UpdateItem', () => { expect(result.value.completed).toBe(true) expect(result.value.boughtAt).toBe(data.data.boughtAt?.toISOString() ?? null) + + expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }]) }) - it('marks the item back to pending and clears boughtAt', async () => { + it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => { const { db, updates } = createDb({ membership: { role: 'collaborator' }, item: itemRow(true, new Date('2026-10-15T12:00:00.000Z')), }) - const result = await new UpdateItem(db).execute({ + const { events, published } = createBus() + const result = await new UpdateItem(db, events).execute({ listId: 'list-1', itemId: 'item-1', userId: 'user-1', @@ -127,5 +145,7 @@ describe('UpdateItem', () => { expect(result.value.completed).toBe(false) expect(result.value.boughtAt).toBeNull() + + expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }]) }) }) diff --git a/apps/api/src/modules/lists/items/update/use-case.ts b/apps/api/src/modules/lists/items/update/use-case.ts index f1d667b..e33f39d 100644 --- a/apps/api/src/modules/lists/items/update/use-case.ts +++ b/apps/api/src/modules/lists/items/update/use-case.ts @@ -7,6 +7,7 @@ import { type Result, } from '@superlist/shared' +import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' import { toListItem } from '../serialize' @@ -17,7 +18,10 @@ import { toListItem } from '../serialize' * statistics, and is cleared when the item goes back to pending. */ export class UpdateItem { - constructor(private readonly db: Database) {} + constructor( + private readonly db: Database, + private readonly events: ListEvents = listEvents, + ) {} async execute(input: { listId: string @@ -49,6 +53,9 @@ export class UpdateItem { }, }) - return Ok(toListItem(updated)) + const dto = toListItem(updated) + this.events.publish({ type: 'item.updated', listId: input.listId, item: dto }) + + return Ok(dto) } } diff --git a/apps/api/src/modules/lists/update/use-case.ts b/apps/api/src/modules/lists/update/use-case.ts index 52e1494..a78abe5 100644 --- a/apps/api/src/modules/lists/update/use-case.ts +++ b/apps/api/src/modules/lists/update/use-case.ts @@ -7,11 +7,15 @@ import { type ShoppingListSummary, } from '@superlist/shared' +import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' /** Renames a list. Only the owner (`role: owner`) may do it. */ export class UpdateShoppingList { - constructor(private readonly db: Database) {} + constructor( + private readonly db: Database, + private readonly events: ListEvents = listEvents, + ) {} async execute(input: { listId: string @@ -36,6 +40,8 @@ export class UpdateShoppingList { include: { _count: { select: { members: true } } }, }) + this.events.publish({ type: 'list.updated', listId: list.id, name: list.name }) + return Ok({ id: list.id, name: list.name, diff --git a/apps/web/.env.example b/apps/web/.env.example index e062916..665bc74 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1 +1,4 @@ -VITE_API_URL="http://localhost:4100" +# Optional. Vite proxies /api/* to http://localhost:4100 in dev, so leave this +# unset unless the frontend must call the API on a different origin (the client +# always appends /api to it). +# VITE_API_URL="" diff --git a/apps/web/src/components/items/item-list.tsx b/apps/web/src/components/items/item-list.tsx index 1075142..91cc833 100644 --- a/apps/web/src/components/items/item-list.tsx +++ b/apps/web/src/components/items/item-list.tsx @@ -5,6 +5,7 @@ import { Card, CardContent } from '@/components/ui/card' import { Separator } from '@/components/ui/separator' import { Skeleton } from '@/components/ui/skeleton' import { useItems, useUpdateItem } from '@/hooks/use-items' +import { useListEvents } from '@/hooks/use-list-events' import { useToday } from '@/hooks/use-today' import { ApiError } from '@/lib/api-client' import { splitItems } from '@/lib/items' @@ -26,6 +27,9 @@ export function ItemList({ listId }: ItemListProps) { const updateItem = useUpdateItem(listId) const today = useToday() + // Live updates: another member adds or buys an item and this list refreshes. + useListEvents(listId) + if (error) { return ( diff --git a/apps/web/src/hooks/use-list-events.ts b/apps/web/src/hooks/use-list-events.ts new file mode 100644 index 0000000..14f56a9 --- /dev/null +++ b/apps/web/src/hooks/use-list-events.ts @@ -0,0 +1,47 @@ +import { useQueryClient } from '@tanstack/react-query' +import { useEffect } from 'react' + +import { apiBaseUrl } from '@/lib/api-client' +import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events' + +/** + * Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes + * the affected queries whenever another member adds or buys an item, invites + * somebody or renames the list — so the page updates without a reload. + * + * The session cookie is sent via `withCredentials`. `EventSource` reconnects on + * its own; a `ready` event is emitted on every (re)connection, used here to + * reconcile anything missed while disconnected. + */ +export function useListEvents(listId: string) { + const queryClient = useQueryClient() + + useEffect(() => { + const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, { + withCredentials: true, + }) + + const onReady = () => { + queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }) + } + + source.addEventListener('ready', onReady) + + const listeners = LIST_EVENT_TYPES.map((type) => { + const listener = () => { + for (const queryKey of queryKeysForListEvent(type, listId)) { + queryClient.invalidateQueries({ queryKey }) + } + } + + source.addEventListener(type, listener) + return { type, listener } + }) + + return () => { + source.removeEventListener('ready', onReady) + for (const { type, listener } of listeners) source.removeEventListener(type, listener) + source.close() + } + }, [listId, queryClient]) +} diff --git a/apps/web/src/lib/api-client.ts b/apps/web/src/lib/api-client.ts index a39c4ca..c8d9d62 100644 --- a/apps/web/src/lib/api-client.ts +++ b/apps/web/src/lib/api-client.ts @@ -1,6 +1,15 @@ import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared' -const baseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:4100' +/** + * Base URL of the API. Also used to open the SSE streams (`list-events`). + * + * Empty by default: the API is reached through the `/api` prefix on the same + * origin (Vite proxies it in dev, nginx in production). Set `VITE_API_URL` to + * point at another origin — the `/api` suffix is always appended to it. + */ +const origin = import.meta.env.VITE_API_URL || '' + +export const apiBaseUrl = `${origin}/api` /** Error thrown when the API answers with a RFC 9457 Problem Details payload. */ export class ApiError extends Error { @@ -34,7 +43,7 @@ export async function readProblem(response: Response): Promise { /** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */ export async function apiFetch(path: string, init: RequestInit = {}): Promise { - const response = await fetch(`${baseUrl}${path}`, { + const response = await fetch(`${apiBaseUrl}${path}`, { credentials: 'include', ...init, headers: { diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts index f4a94ca..7708122 100644 --- a/apps/web/src/lib/auth-client.ts +++ b/apps/web/src/lib/auth-client.ts @@ -1,11 +1,12 @@ import { createAuthClient } from 'better-auth/react' /** - * BetterAuth browser client. `baseURL` points at the Hono API, which mounts - * BetterAuth under `/api/auth/*`. + * BetterAuth browser client. `baseURL` defaults to the page origin (the API is + * proxied under `/api` in dev and production) and can be overridden with + * `VITE_API_URL`. BetterAuth appends `/api/auth` itself. */ export const authClient = createAuthClient({ - baseURL: import.meta.env.VITE_API_URL ?? 'http://localhost:4100', + baseURL: import.meta.env.VITE_API_URL || window.location.origin, }) export const { signIn, signUp, signOut, useSession } = authClient diff --git a/apps/web/src/lib/list-events.test.ts b/apps/web/src/lib/list-events.test.ts new file mode 100644 index 0000000..6a49cd3 --- /dev/null +++ b/apps/web/src/lib/list-events.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' + +import { queryKeysForListEvent } from './list-events' + +describe('queryKeysForListEvent', () => { + it('refreshes only the item list for item events', () => { + expect(queryKeysForListEvent('item.created', 'list-1')).toEqual([['lists', 'list-1', 'items']]) + expect(queryKeysForListEvent('item.updated', 'list-1')).toEqual([['lists', 'list-1', 'items']]) + }) + + it('refreshes the list detail and the overview for membership and invitations', () => { + for (const type of ['invitation.created', 'member.added', 'list.updated'] as const) { + expect(queryKeysForListEvent(type, 'list-1')).toEqual([['lists', 'list-1'], ['lists']]) + } + }) +}) diff --git a/apps/web/src/lib/list-events.ts b/apps/web/src/lib/list-events.ts new file mode 100644 index 0000000..d113d88 --- /dev/null +++ b/apps/web/src/lib/list-events.ts @@ -0,0 +1,28 @@ +import type { ListEventType } from '@superlist/shared' +import type { QueryKey } from '@tanstack/react-query' + +/** Every event type the SSE stream can emit, in one place for the client. */ +export const LIST_EVENT_TYPES: readonly ListEventType[] = [ + 'item.created', + 'item.updated', + 'invitation.created', + 'member.added', + 'list.updated', +] + +/** + * Query keys a list event invalidates. Item changes only touch the item list; + * membership and invitation changes refresh the list detail and the overview + * (whose summary carries `memberCount`). + */ +export function queryKeysForListEvent(type: ListEventType, listId: string): QueryKey[] { + switch (type) { + case 'item.created': + case 'item.updated': + return [['lists', listId, 'items']] + case 'invitation.created': + case 'member.added': + case 'list.updated': + return [['lists', listId], ['lists']] + } +} diff --git a/apps/web/src/routes/_authenticated/lists/$listId/settings.tsx b/apps/web/src/routes/_authenticated/lists/$listId/settings.tsx index 954c64a..384e4b6 100644 --- a/apps/web/src/routes/_authenticated/lists/$listId/settings.tsx +++ b/apps/web/src/routes/_authenticated/lists/$listId/settings.tsx @@ -16,6 +16,7 @@ import { Input } from '@/components/ui/input' import { Skeleton } from '@/components/ui/skeleton' import { useCreateInvitation } from '@/hooks/use-invitations' import { listQueryOptions, useList } from '@/hooks/use-list' +import { useListEvents } from '@/hooks/use-list-events' import { useRenameList, useSetPrimaryList } from '@/hooks/use-lists' import { ApiError } from '@/lib/api-client' @@ -33,6 +34,9 @@ function ListSettingsPage() { const { listId } = Route.useParams() const { data: list, isPending, error } = useList(listId) + // Live updates: refresh the members and invitations when they change elsewhere. + useListEvents(listId) + if (error) { return (
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index fe7303e..49553cb 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -21,5 +21,10 @@ export default defineConfig({ }, server: { port: 7153, + // Same-origin API in dev, mirroring nginx in production: the browser calls + // `/api/*` on the Vite server and it is forwarded to the Bun API. + proxy: { + '/api': 'http://localhost:4100', + }, }, }) diff --git a/packages/shared/src/events.ts b/packages/shared/src/events.ts new file mode 100644 index 0000000..006045e --- /dev/null +++ b/packages/shared/src/events.ts @@ -0,0 +1,20 @@ +import type { ListItem } from './shopping-list' + +/** Discriminator of the events a list's SSE stream can emit. */ +export type ListEventType = + | 'item.created' + | 'item.updated' + | 'invitation.created' + | 'member.added' + | 'list.updated' + +/** + * Server-Sent Events pushed to the members viewing a list + * (`GET /lists/:listId/events`). `type` is the SSE `event:` name and the whole + * object is the JSON `data:` payload. + */ +export type ListEvent = + | { type: 'item.created' | 'item.updated'; listId: string; item: ListItem } + | { type: 'invitation.created'; listId: string; email: string } + | { type: 'member.added'; listId: string; userId: string } + | { type: 'list.updated'; listId: string; name: string } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 7bbe706..8604b3d 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,3 +1,4 @@ +export * from './events' export * from './problem-details' export * from './result' export * from './shopping-list' diff --git a/turbo.json b/turbo.json index 7255032..8820137 100644 --- a/turbo.json +++ b/turbo.json @@ -4,7 +4,8 @@ "build": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", ".env*"], - "outputs": ["dist/**"] + "outputs": ["dist/**"], + "env": ["VITE_API_URL"] }, "lint": {}, "typecheck": {}, @@ -32,7 +33,8 @@ "NODE_ENV", "RESEND_API_KEY", "MAIL_FROM", - "WEB_APP_URL" + "WEB_APP_URL", + "VITE_API_URL" ] }, "db:generate": {