Compare commits
6 Commits
4ff864a557
...
fbd6942a6e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbd6942a6e | ||
|
|
f87d46c975 | ||
|
|
370e3022c8 | ||
|
|
4035a4bf20 | ||
|
|
4ed6432f60 | ||
|
|
09f9c4fdf0 |
20
.dockerignore
Normal file
20
.dockerignore
Normal file
@@ -0,0 +1,20 @@
|
||||
.git
|
||||
.github
|
||||
**/node_modules
|
||||
**/.turbo
|
||||
**/dist
|
||||
**/build
|
||||
**/coverage
|
||||
**/*.tsbuildinfo
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
# env (examples are kept: they never contain secrets)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# generated files (rebuilt inside the image)
|
||||
apps/api/src/generated
|
||||
apps/web/src/routeTree.gen.ts
|
||||
apps/web/.tanstack
|
||||
@@ -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=""
|
||||
|
||||
53
.github/workflows/ci.yml
vendored
53
.github/workflows/ci.yml
vendored
@@ -1,53 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# Prisma needs a connection string to generate the client; no database is
|
||||
# contacted during lint, typecheck, test or build.
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/superlist?schema=public
|
||||
BETTER_AUTH_SECRET: ci-only-secret-not-used-at-build-time
|
||||
BETTER_AUTH_URL: http://localhost:4100
|
||||
CORS_ORIGIN: http://localhost:7153
|
||||
VITE_API_URL: http://localhost:4100
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Verify
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.0
|
||||
|
||||
# The Prisma CLI runs on Node.
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Generate Prisma client
|
||||
run: bun run db:generate
|
||||
|
||||
- name: Lint and format check
|
||||
run: bun run lint:ci
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Build
|
||||
run: bun run build
|
||||
29
AGENTS.md
29
AGENTS.md
@@ -3,7 +3,8 @@
|
||||
## Status
|
||||
|
||||
Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`,
|
||||
CI on GitHub Actions, Biome as the only JS/TS tool and the text Bun lockfile committed.
|
||||
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
||||
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
||||
|
||||
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
|
||||
there is no Google login and no email verification). The `health` module is the reference example.
|
||||
@@ -46,7 +47,7 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
| `bun run build` | `turbo run build` (API bundle + web production build) |
|
||||
| `bun run lint` | `biome check .` per package via turbo — fails on lint, format or import order |
|
||||
| `bun run lint:fix` | `biome check --write .` across the repo (lint fixes, formatting, imports) |
|
||||
| `bun run lint:ci` | `biome ci .` — whole repo, exactly what CI runs |
|
||||
| `bun run lint:ci` | `biome ci .` — whole repo, works without a git index |
|
||||
| `bun run format` | `biome format --write .` (`format:check` to verify only) |
|
||||
| `bun run typecheck` | `tsc` per package (`apps/web` regenerates the route tree first) |
|
||||
| `bun run test` | `bun test` in the API, `vitest` in web and shared |
|
||||
@@ -73,12 +74,12 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
every task that needs one lists it in `turbo.json`: `db:*` use `env: ["DATABASE_URL"]`, `test` declares the
|
||||
API variables, `dev` uses `passThroughEnv` (they must reach the process but don't change its output).
|
||||
`VITE_*` is covered by Vite framework inference. **When you introduce a new variable, add it to `turbo.json`**
|
||||
or the task will fail (or worse, hit a stale cache) in CI.
|
||||
or the task will fail (or worse, hit a stale cache).
|
||||
- Env files: `cp apps/api/.env.example apps/api/.env` and `cp apps/web/.env.example apps/web/.env` (both
|
||||
gitignored, and `.env.example` at the root documents every variable). Bun loads `.env` automatically; the
|
||||
Prisma CLI does not, which is why `prisma.config.ts` imports `dotenv/config`.
|
||||
- Dev ports: API `4100`, web `7153`. They live in the `.env.example` files, `apps/web/vite.config.ts` and
|
||||
`.github/workflows/ci.yml` — change them together.
|
||||
- Dev ports: API `4100`, web `7153`. They live in the `.env.example` files and `apps/web/vite.config.ts`
|
||||
— change them together.
|
||||
- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and
|
||||
`apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter
|
||||
properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`).
|
||||
@@ -88,8 +89,13 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
PascalCase/camelCase, because BetterAuth and the generated client address models by those names, so a column
|
||||
rename never changes the TypeScript API. Default constraint/index names follow the mapped names, so do not
|
||||
set `map:` unless you have a reason to.
|
||||
- CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`: `bun install --frozen-lockfile` →
|
||||
`db:generate` → `lint:ci` → `typecheck` → `test` → `build`, with Bun 1.4.0 and Node 22 for the Prisma CLI.
|
||||
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
|
||||
`web`; the database is external (Dokploy's), and both join the external `dokploy-network` for Traefik. The
|
||||
`api` image (`apps/api/Dockerfile`) builds the Bun bundle and runs `prisma migrate deploy` before
|
||||
`bun run start`; the `web` image (`apps/web/Dockerfile`) builds with Vite and serves `dist/` with
|
||||
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://api:4100`. Required env vars are interpolated
|
||||
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
||||
in Dokploy. There is no hosted CI.
|
||||
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||
`apps/api/src/generated/`.
|
||||
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
||||
@@ -125,7 +131,10 @@ apps/api/src/modules/alerts/
|
||||
- **Routes never check `result.ok` by hand**: every route ends with `resultJson(c, result)`, which serializes
|
||||
`Ok` as JSON (200 by default, override with `{ status: 201 }`, `204` sends an empty body) and maps `Failure`
|
||||
to the matching RFC 9457 `application/problem+json` response.
|
||||
- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/alerts', alertsModule)`.
|
||||
- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/api/alerts', alertsModule)`.
|
||||
**Every API route is mounted under `/api`** (BetterAuth already owns `/api/auth/*`) because nginx proxies
|
||||
`/api/*` to the API while serving the SPA at the root — an unprefixed path such as `/lists` would be
|
||||
swallowed by the frontend router.
|
||||
|
||||
```ts
|
||||
// apps/api/src/modules/alerts/list/route.ts
|
||||
@@ -246,6 +255,10 @@ apps/web/src/
|
||||
- `apiFetch` returns parsed JSON, sends `credentials: 'include'` (BetterAuth sessions are cookies) and throws
|
||||
`ApiError` carrying the parsed `ProblemDetails` for non-2xx responses; `204` resolves to `undefined`. Error
|
||||
UIs read `error.problem.detail`.
|
||||
- **Same-origin `/api` in every environment.** `apiBaseUrl` is `` `${VITE_API_URL || ''}/api` `` and the SSE
|
||||
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
||||
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
||||
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
||||
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
||||
components — this registry version ships `field` instead of the older `form` component.
|
||||
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
||||
|
||||
27
README.md
27
README.md
@@ -46,15 +46,36 @@ bun run typecheck # tsc
|
||||
bun run test # bun test (api) / vitest (web, shared)
|
||||
```
|
||||
|
||||
CI (`.github/workflows/ci.yml`) runs `db:generate` → `lint:ci` → `typecheck` → `test` → `build` on every push
|
||||
to `main` and every pull request.
|
||||
There is no hosted CI: run these locally (in that order) before pushing. `bun run lint:ci` runs the exact
|
||||
same Biome check as `biome ci` would.
|
||||
|
||||
## Deployment (Dokploy)
|
||||
|
||||
`docker-compose.yml` at the repo root defines the two runtime services — `api` (Bun + nginx-free Hono server)
|
||||
and `web` (static build behind nginx, proxying `/api/*` to the API). The database is external (provided by
|
||||
Dokploy), and both services join the external `dokploy-network` so Traefik can reach them.
|
||||
|
||||
- One public domain: nginx serves the SPA and proxies `/api/*` → `http://api:4100`. All API routes are
|
||||
mounted under `/api` for that reason — never mount a route at the root of the API.
|
||||
- Env vars are interpolated from the Dokploy service env (`docker-compose.yml` marks `DATABASE_URL`,
|
||||
`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN` and `WEB_APP_URL` as required). See `.env.example`.
|
||||
- Point the domain in Dokploy's **Domains** UI at the `web` service, container port `80` (the compose file
|
||||
publishes no host ports on purpose).
|
||||
- Migrations run automatically on API startup (`prisma migrate deploy` before `bun run start`).
|
||||
|
||||
Local smoke test of the same setup:
|
||||
|
||||
```bash
|
||||
docker network create dokploy-network # once, mimics Dokploy's network
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
## Useful scripts
|
||||
|
||||
| Command | Effect |
|
||||
| --------------------- | ------------------------------------------------------------------- |
|
||||
| `bun run lint:fix` | Apply Biome fixes: lint, formatting and import sorting (whole repo) |
|
||||
| `bun run lint:ci` | `biome ci` — check the whole repo exactly as CI does |
|
||||
| `bun run lint:ci` | `biome ci` — whole-repo check, stricter than `lint` |
|
||||
| `bun run format` | Format with Biome (`format:check` to verify only) |
|
||||
| `bun run db:generate` | Regenerate the Prisma client into `apps/api/src/generated` |
|
||||
| `bun run db:migrate` | Create and apply a migration (development) |
|
||||
|
||||
27
apps/api/Dockerfile
Normal file
27
apps/api/Dockerfile
Normal file
@@ -0,0 +1,27 @@
|
||||
# Build context is the repository root (Bun workspace monorepo).
|
||||
FROM oven/bun:1.4.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
# Manifests first so `bun install` only reruns when the lockfile changes.
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
FROM deps AS build
|
||||
COPY . .
|
||||
# `prisma.config.ts` reads DATABASE_URL at load time; generate never connects,
|
||||
# so a placeholder is enough to produce the client in src/generated/.
|
||||
RUN cd apps/api && DATABASE_URL="postgresql://user:pass@localhost:5432/db" bunx prisma generate
|
||||
RUN cd apps/api && bun run build
|
||||
|
||||
# Runtime keeps the full tree: `prisma migrate deploy` runs on startup and
|
||||
# needs the Prisma CLI (devDependency), prisma/ and prisma.config.ts.
|
||||
FROM base AS runtime
|
||||
ENV NODE_ENV=production
|
||||
COPY --from=build /app /app
|
||||
WORKDIR /app/apps/api
|
||||
EXPOSE 4100
|
||||
CMD ["sh", "-c", "bunx prisma migrate deploy && bun run start"]
|
||||
@@ -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)
|
||||
|
||||
@@ -9,5 +9,14 @@ logger.info({ port }, 'api listening')
|
||||
|
||||
export default {
|
||||
port,
|
||||
fetch: app.fetch,
|
||||
fetch(req: Request, server: Bun.Server<unknown>) {
|
||||
// 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)
|
||||
},
|
||||
}
|
||||
|
||||
64
apps/api/src/lib/events.test.ts
Normal file
64
apps/api/src/lib/events.test.ts
Normal file
@@ -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)
|
||||
})
|
||||
})
|
||||
38
apps/api/src/lib/events.ts
Normal file
38
apps/api/src/lib/events.ts
Normal file
@@ -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<string, Set<ListEventListener>>()
|
||||
|
||||
/** Subscribes to one list's events; returns the unsubscribe function. */
|
||||
subscribe(listId: string, listener: ListEventListener): () => void {
|
||||
const listeners = this.listeners.get(listId) ?? new Set<ListEventListener>()
|
||||
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()
|
||||
27
apps/api/src/lib/list-access.ts
Normal file
27
apps/api/src/lib/list-access.ts
Normal file
@@ -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<AppEnv> = 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()
|
||||
}
|
||||
@@ -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<number> {
|
||||
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
|
||||
|
||||
@@ -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' }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
75
apps/api/src/modules/lists/events/route.ts
Normal file
75
apps/api/src/modules/lists/events/route.ts
Normal file
@@ -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<AppEnv>().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<void>((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<typeof setTimeout> | undefined
|
||||
await Promise.race([
|
||||
waitForEvent(),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, HEARTBEAT_MS)
|
||||
}),
|
||||
])
|
||||
clearTimeout(timer)
|
||||
wake = undefined
|
||||
|
||||
if (pending.length === 0 && !stream.aborted) {
|
||||
await stream.write(': ping\n\n')
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -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<AppEnv>()
|
||||
.route('/', updateListRoute)
|
||||
.route('/', setPrimaryListRoute)
|
||||
.route('/:listId/items', listItemsModule)
|
||||
.route('/:listId/events', listEventsRoute)
|
||||
|
||||
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
@@ -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 }])
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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=""
|
||||
|
||||
23
apps/web/Dockerfile
Normal file
23
apps/web/Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
# Build context is the repository root (Bun workspace monorepo).
|
||||
FROM oven/bun:1.4.0 AS build
|
||||
WORKDIR /app
|
||||
|
||||
# Manifests first so `bun install` only reruns when the lockfile changes.
|
||||
COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
# Empty by default: in production the SPA and the API share one origin and the
|
||||
# browser calls `/api/*` (nginx proxies it). Set the build arg to point the
|
||||
# frontend at a different API origin.
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN cd apps/web && bun run build
|
||||
|
||||
FROM nginx:alpine AS runtime
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
@@ -3,6 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||
|
||||
47
apps/web/nginx.conf
Normal file
47
apps/web/nginx.conf
Normal file
@@ -0,0 +1,47 @@
|
||||
# Serves the built SPA and proxies /api/* to the Bun API container.
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
|
||||
# API proxy: no path rewrite, /api/* reaches the API as-is. `proxy_buffering
|
||||
# off` and the long read timeout keep the SSE streams (/lists/:id/events)
|
||||
# flowing in realtime instead of being batched or cut off.
|
||||
location /api/ {
|
||||
proxy_pass http://api:4100;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 1h;
|
||||
proxy_send_timeout 1h;
|
||||
}
|
||||
|
||||
# PWA: hashed build output is safe to cache forever, the service worker and
|
||||
# the app shell must always be revalidated so new releases reach clients.
|
||||
location /assets/ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location = /sw.js {
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
# SPA fallback so deep links (/lists/:id, /invitations, ...) work on reload.
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@
|
||||
"@tanstack/react-query": "^5.104.2",
|
||||
"@tanstack/react-query-devtools": "^5.104.2",
|
||||
"@tanstack/react-router": "^1.170.42",
|
||||
"@tanstack/react-table": "^9.3.1",
|
||||
"better-auth": "^1.7.7",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -48,6 +47,7 @@
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.0.4"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
apps/web/public/apple-touch-icon.png
Normal file
BIN
apps/web/public/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.9 KiB |
14
apps/web/public/favicon.svg
Normal file
14
apps/web/public/favicon.svg
Normal file
@@ -0,0 +1,14 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32" role="img" aria-label="Superlist">
|
||||
<rect width="32" height="32" rx="7" fill="#0a0a0a" />
|
||||
<text
|
||||
x="16"
|
||||
y="17"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="middle"
|
||||
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
|
||||
font-size="15"
|
||||
font-weight="600"
|
||||
letter-spacing="-0.6"
|
||||
fill="#fafafa"
|
||||
>SL</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 431 B |
BIN
apps/web/public/maskable-512x512.png
Normal file
BIN
apps/web/public/maskable-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.9 KiB |
14
apps/web/public/maskable.svg
Normal file
14
apps/web/public/maskable.svg
Normal file
@@ -0,0 +1,14 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
|
||||
<rect width="512" height="512" fill="#0a0a0a" />
|
||||
<text
|
||||
x="256"
|
||||
y="270"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="middle"
|
||||
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
|
||||
font-size="216"
|
||||
font-weight="600"
|
||||
letter-spacing="-9"
|
||||
fill="#fafafa"
|
||||
>SL</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 431 B |
BIN
apps/web/public/pwa-192x192.png
Normal file
BIN
apps/web/public/pwa-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.0 KiB |
BIN
apps/web/public/pwa-512x512.png
Normal file
BIN
apps/web/public/pwa-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
42
apps/web/src/components/install-prompt.tsx
Normal file
42
apps/web/src/components/install-prompt.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { DownloadIcon, SmartphoneIcon, XIcon } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useInstallPrompt } from '@/hooks/use-install-prompt'
|
||||
|
||||
export function InstallPrompt() {
|
||||
const { visible, canInstall, needsManualInstructions, install, dismiss } = useInstallPrompt()
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(4.75rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
|
||||
<div className="bg-card shadow-lg border rounded-xl p-3 flex items-center gap-3 w-full">
|
||||
<div className="bg-primary/10 text-primary rounded-lg p-2">
|
||||
{needsManualInstructions ? (
|
||||
<SmartphoneIcon className="size-4" />
|
||||
) : (
|
||||
<DownloadIcon className="size-4" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">Instalar Superlist</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{needsManualInstructions
|
||||
? 'Toca Compartir y luego «Añadir a pantalla de inicio».'
|
||||
: 'Añádela a tu pantalla de inicio para usarla como una app.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{canInstall && (
|
||||
<Button size="sm" onClick={install}>
|
||||
Instalar
|
||||
</Button>
|
||||
)}
|
||||
<Button size="icon-sm" variant="ghost" aria-label="Cerrar" onClick={dismiss}>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -20,6 +20,23 @@ type CreateItemFormProps = {
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
|
||||
const NEW_ITEM_INPUT_ID = 'new-item-input'
|
||||
|
||||
/**
|
||||
* Puts the cursor in the "add an item" input when the home page is already the one on
|
||||
* screen (the route does not remount, so nothing else would move the focus). When the
|
||||
* user is navigating *to* the home page this is a no-op: the input takes the focus as
|
||||
* soon as it mounts, through `autoFocus`. Either way, tapping "Inicio" always ends with
|
||||
* the focus in the input — and never with the focus on another page's input.
|
||||
*
|
||||
* @param pathname the route the link was clicked from, so only the home input is focused.
|
||||
*/
|
||||
export function focusNewItemInput(pathname: string): void {
|
||||
if (pathname !== '/') return
|
||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||
}
|
||||
|
||||
/** Input to add an item to a list. Submits with Enter or the button. */
|
||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||
const createItem = useCreateItem(listId)
|
||||
@@ -37,6 +54,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
<form onSubmit={onSubmit} className="flex items-start gap-2">
|
||||
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
|
||||
<Input
|
||||
id={NEW_ITEM_INPUT_ID}
|
||||
aria-label="Nuevo artículo"
|
||||
autoComplete="off"
|
||||
placeholder="Añade un artículo…"
|
||||
|
||||
@@ -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 (
|
||||
<Alert variant="destructive">
|
||||
|
||||
@@ -8,7 +8,6 @@ import { SidebarTrigger } from '@/components/ui/sidebar'
|
||||
function titleFor(pathname: string) {
|
||||
if (pathname === '/') return 'Panel'
|
||||
if (pathname.startsWith('/lists')) return 'Listas'
|
||||
if (pathname.startsWith('/tasks')) return 'Tareas'
|
||||
if (pathname.startsWith('/settings')) return 'Ajustes'
|
||||
return 'Superlist'
|
||||
}
|
||||
@@ -20,7 +19,7 @@ export function AppHeader() {
|
||||
return (
|
||||
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
|
||||
<div className="flex w-full items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<SidebarTrigger className="-ml-1 hidden md:inline-flex" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
<h1 className="truncate text-sm font-medium">{title}</h1>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { HomeIcon, ListTodoIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
|
||||
import { HomeIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
|
||||
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { NavUser } from '@/components/layout/nav-user'
|
||||
import {
|
||||
Sidebar,
|
||||
@@ -25,7 +26,6 @@ type NavItem = {
|
||||
const NAV_ITEMS: NavItem[] = [
|
||||
{ title: 'Principal', to: '/', icon: HomeIcon },
|
||||
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
|
||||
{ title: 'Tareas', to: '/tasks', icon: ListTodoIcon },
|
||||
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
|
||||
]
|
||||
|
||||
@@ -43,7 +43,7 @@ export function AppSidebar() {
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton size="lg" asChild>
|
||||
<Link to="/">
|
||||
<Link to="/" onClick={() => focusNewItemInput(pathname)}>
|
||||
<div className="bg-primary text-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg text-sm font-semibold">
|
||||
SL
|
||||
</div>
|
||||
@@ -68,7 +68,10 @@ export function AppSidebar() {
|
||||
isActive={isActive(pathname, item.to)}
|
||||
tooltip={item.title}
|
||||
>
|
||||
<Link to={item.to}>
|
||||
<Link
|
||||
to={item.to}
|
||||
onClick={item.to === '/' ? () => focusNewItemInput(pathname) : undefined}
|
||||
>
|
||||
<item.icon />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
|
||||
74
apps/web/src/components/layout/bottom-nav.tsx
Normal file
74
apps/web/src/components/layout/bottom-nav.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import { HomeIcon, SettingsIcon, ShoppingCartIcon, UserIcon } from 'lucide-react'
|
||||
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
function isActive(pathname: string, to: string) {
|
||||
if (to === '/') return pathname === '/'
|
||||
return pathname === to || pathname.startsWith(`${to}/`)
|
||||
}
|
||||
|
||||
export function BottomNav() {
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||
|
||||
return (
|
||||
<footer className="fixed inset-x-0 bottom-0 z-30 border-t bg-background/95 supports-[backdrop-filter]:bg-background/60 backdrop-blur md:hidden pb-[env(safe-area-inset-bottom)]">
|
||||
<nav className="mx-auto flex h-16 max-w-lg items-center justify-around px-2">
|
||||
<Link
|
||||
to="/"
|
||||
onClick={() => focusNewItemInput(pathname)}
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
|
||||
isActive(pathname, '/')
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<HomeIcon className="size-5" />
|
||||
<span>Inicio</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/lists"
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
|
||||
isActive(pathname, '/lists')
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<ShoppingCartIcon className="size-5" />
|
||||
<span>Listas</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/settings"
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
|
||||
isActive(pathname, '/settings')
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<SettingsIcon className="size-5" />
|
||||
<span>Ajustes</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/settings"
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-1 rounded-md px-2 py-1.5 text-xs transition-colors',
|
||||
isActive(pathname, '/settings')
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
aria-label="Cuenta"
|
||||
>
|
||||
<UserIcon className="size-5" />
|
||||
<span>Cuenta</span>
|
||||
</Link>
|
||||
</nav>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
@@ -2,38 +2,45 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
||||
|
||||
import { useTheme } from '@/components/theme-provider'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 'light', label: 'Claro', icon: SunIcon },
|
||||
{ value: 'dark', label: 'Oscuro', icon: MoonIcon },
|
||||
{ value: 'system', label: 'Sistema', icon: MonitorIcon },
|
||||
{ value: 'light', label: 'Claro', icon: SunIcon, out: '-rotate-90' },
|
||||
{ value: 'dark', label: 'Oscuro', icon: MoonIcon, out: 'rotate-90' },
|
||||
{ value: 'system', label: 'Sistema', icon: MonitorIcon, out: 'rotate-90' },
|
||||
] as const
|
||||
|
||||
type Option = (typeof OPTIONS)[number]
|
||||
|
||||
function nextOption(current: Option['value']): Option {
|
||||
const index = OPTIONS.findIndex((option) => option.value === current)
|
||||
return OPTIONS[(index + 1) % OPTIONS.length]
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { setTheme } = useTheme()
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const current = OPTIONS.find((option) => option.value === theme) ?? OPTIONS[2]
|
||||
const next = nextOption(current.value)
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" aria-label="Cambiar tema">
|
||||
<SunIcon className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||
<MoonIcon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{OPTIONS.map(({ value, label, icon: Icon }) => (
|
||||
<DropdownMenuItem key={value} onClick={() => setTheme(value)}>
|
||||
<Icon />
|
||||
{label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative"
|
||||
aria-label={`Tema: ${current.label} — cambiar a ${next.label}`}
|
||||
onClick={() => setTheme(next.value)}
|
||||
>
|
||||
{OPTIONS.map(({ value, icon: Icon, out }) => (
|
||||
<Icon
|
||||
key={value}
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute size-4 transition-all',
|
||||
value === current.value ? 'scale-100 rotate-0' : `scale-0 ${out}`,
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from 'cn'
|
||||
import * as React from 'react'
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<'table'>) {
|
||||
return (
|
||||
<div data-slot="table-container" className="relative w-full overflow-x-auto">
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn('w-full caption-bottom text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
|
||||
return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn('[&_tr:last-child]:border-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
'border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn('p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn('mt-4 text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow }
|
||||
111
apps/web/src/hooks/use-install-prompt.ts
Normal file
111
apps/web/src/hooks/use-install-prompt.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import * as React from 'react'
|
||||
|
||||
/**
|
||||
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
|
||||
* for it. This is the subset of the event we use.
|
||||
*/
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
readonly platforms: string[]
|
||||
readonly userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>
|
||||
prompt(): Promise<void>
|
||||
}
|
||||
|
||||
const DISMISSED_KEY = 'superlist-install-dismissed'
|
||||
|
||||
function readDismissed() {
|
||||
try {
|
||||
return localStorage.getItem(DISMISSED_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isStandalone() {
|
||||
if (typeof window === 'undefined') return false
|
||||
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
|
||||
return (
|
||||
window.matchMedia('(display-mode: standalone)').matches ||
|
||||
navigatorWithStandalone.standalone === true
|
||||
)
|
||||
}
|
||||
|
||||
function isIosSafari() {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
const ua = navigator.userAgent
|
||||
const isIos = /iphone|ipad|ipod/i.test(ua)
|
||||
// On iOS only Safari can add apps to the home screen, and it never fires
|
||||
// `beforeinstallprompt`, so we detect it to show manual instructions.
|
||||
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
|
||||
return isIos && isSafari
|
||||
}
|
||||
|
||||
export type InstallPromptState = {
|
||||
/** We can trigger the native install dialog. */
|
||||
canInstall: boolean
|
||||
/** iOS Safari: no native prompt, show "Compartir → Añadir a pantalla de inicio". */
|
||||
needsManualInstructions: boolean
|
||||
/** The app is already running as an installed PWA. */
|
||||
isInstalled: boolean
|
||||
/** The user dismissed the banner before (persisted). */
|
||||
isDismissed: boolean
|
||||
install: () => Promise<void>
|
||||
dismiss: () => void
|
||||
/** Show the banner: installable or needing instructions, and not dismissed/installed. */
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
export function useInstallPrompt(): InstallPromptState {
|
||||
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
|
||||
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
|
||||
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
|
||||
const [isIos] = React.useState(isIosSafari)
|
||||
|
||||
React.useEffect(() => {
|
||||
const onBeforeInstallPrompt = (event: Event) => {
|
||||
// Stop Chrome from showing its own mini-infobar so we control the banner.
|
||||
event.preventDefault()
|
||||
setDeferredPrompt(event as BeforeInstallPromptEvent)
|
||||
}
|
||||
|
||||
const onInstalled = () => {
|
||||
setDeferredPrompt(null)
|
||||
setIsInstalled(true)
|
||||
}
|
||||
|
||||
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.addEventListener('appinstalled', onInstalled)
|
||||
return () => {
|
||||
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.removeEventListener('appinstalled', onInstalled)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const install = React.useCallback(async () => {
|
||||
if (!deferredPrompt) return
|
||||
await deferredPrompt.prompt()
|
||||
const { outcome } = await deferredPrompt.userChoice
|
||||
if (outcome === 'accepted') setDeferredPrompt(null)
|
||||
}, [deferredPrompt])
|
||||
|
||||
const dismiss = React.useCallback(() => {
|
||||
setIsDismissed(true)
|
||||
try {
|
||||
localStorage.setItem(DISMISSED_KEY, '1')
|
||||
} catch {
|
||||
// Storage can be unavailable (private mode); the banner just comes back.
|
||||
}
|
||||
}, [])
|
||||
|
||||
const canInstall = deferredPrompt !== null
|
||||
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
|
||||
|
||||
return {
|
||||
canInstall,
|
||||
needsManualInstructions,
|
||||
isInstalled,
|
||||
isDismissed,
|
||||
install,
|
||||
dismiss,
|
||||
visible: !isInstalled && !isDismissed && (canInstall || needsManualInstructions),
|
||||
}
|
||||
}
|
||||
47
apps/web/src/hooks/use-list-events.ts
Normal file
47
apps/web/src/hooks/use-list-events.ts
Normal file
@@ -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])
|
||||
}
|
||||
@@ -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<ProblemDetails> {
|
||||
|
||||
/** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */
|
||||
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||
credentials: 'include',
|
||||
...init,
|
||||
headers: {
|
||||
|
||||
@@ -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
|
||||
|
||||
16
apps/web/src/lib/list-events.test.ts
Normal file
16
apps/web/src/lib/list-events.test.ts
Normal file
@@ -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']])
|
||||
}
|
||||
})
|
||||
})
|
||||
28
apps/web/src/lib/list-events.ts
Normal file
28
apps/web/src/lib/list-events.ts
Normal file
@@ -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']]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createRootRouteWithContext, Link, Outlet } from '@tanstack/react-router'
|
||||
import { lazy } from 'react'
|
||||
|
||||
import { ThemeProvider } from '@/components/theme-provider'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -7,22 +6,6 @@ import { Toaster } from '@/components/ui/sonner'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import type { RouterContext } from '@/lib/query-client'
|
||||
|
||||
const RouterDevtools = import.meta.env.DEV
|
||||
? lazy(() =>
|
||||
import('@tanstack/react-router-devtools').then((mod) => ({
|
||||
default: mod.TanStackRouterDevtools,
|
||||
})),
|
||||
)
|
||||
: () => null
|
||||
|
||||
const QueryDevtools = import.meta.env.DEV
|
||||
? lazy(() =>
|
||||
import('@tanstack/react-query-devtools').then((mod) => ({
|
||||
default: mod.ReactQueryDevtools,
|
||||
})),
|
||||
)
|
||||
: () => null
|
||||
|
||||
export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
component: RootLayout,
|
||||
notFoundComponent: NotFound,
|
||||
@@ -34,8 +17,6 @@ function RootLayout() {
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<Outlet />
|
||||
<Toaster richColors position="top-right" />
|
||||
<QueryDevtools />
|
||||
<RouterDevtools />
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
||||
@@ -64,7 +64,7 @@ function HomePage() {
|
||||
{primaryList.isPrimary && <Badge>Principal</Badge>}
|
||||
</div>
|
||||
|
||||
<CreateItemForm listId={primaryList.id} />
|
||||
<CreateItemForm listId={primaryList.id} autoFocus />
|
||||
|
||||
<ItemList listId={primaryList.id} />
|
||||
</div>
|
||||
|
||||
@@ -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 (
|
||||
<div className="mx-auto w-full max-w-2xl">
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createFileRoute, Navigate, Outlet, useRouterState } from '@tanstack/react-router'
|
||||
|
||||
import { InstallPrompt } from '@/components/install-prompt'
|
||||
import { AppHeader } from '@/components/layout/app-header'
|
||||
import { AppSidebar } from '@/components/layout/app-sidebar'
|
||||
import { BottomNav } from '@/components/layout/bottom-nav'
|
||||
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useSession } from '@/lib/auth-client'
|
||||
@@ -32,9 +33,11 @@ function AuthenticatedLayout() {
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<AppHeader />
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pb-20 md:gap-6 md:p-6 md:pb-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
<BottomNav />
|
||||
<InstallPrompt />
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
)
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useSession } from '@/lib/auth-client'
|
||||
import { signOut, useSession } from '@/lib/auth-client'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/settings')({
|
||||
component: SettingsPage,
|
||||
@@ -24,6 +23,7 @@ type ProfileValues = z.infer<typeof profileSchema>
|
||||
|
||||
function SettingsPage() {
|
||||
const { data: session } = useSession()
|
||||
const navigate = useNavigate()
|
||||
const [saved, setSaved] = useState(false)
|
||||
|
||||
const form = useForm<ProfileValues>({
|
||||
@@ -108,6 +108,24 @@ function SettingsPage() {
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Sesión</CardTitle>
|
||||
<CardDescription>Cierra sesión en este dispositivo.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
await signOut()
|
||||
await navigate({ to: '/sign-in' })
|
||||
}}
|
||||
>
|
||||
Cerrar sesión
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { createColumnHelper, tableFeatures, useTable } from '@tanstack/react-table'
|
||||
import { SearchIcon } from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/tasks')({
|
||||
component: TasksPage,
|
||||
})
|
||||
|
||||
type Task = {
|
||||
title: string
|
||||
list: string
|
||||
status: 'pendiente' | 'en curso' | 'hecha'
|
||||
priority: 'baja' | 'media' | 'alta'
|
||||
}
|
||||
|
||||
const TASKS: Task[] = [
|
||||
{
|
||||
title: 'Diseñar el flujo de registro',
|
||||
list: 'Hoja de ruta Q4',
|
||||
status: 'en curso',
|
||||
priority: 'alta',
|
||||
},
|
||||
{
|
||||
title: 'Escribir la documentación de la API',
|
||||
list: 'Docs',
|
||||
status: 'pendiente',
|
||||
priority: 'media',
|
||||
},
|
||||
{
|
||||
title: 'Revisar migraciones de Prisma',
|
||||
list: 'Backend',
|
||||
status: 'pendiente',
|
||||
priority: 'alta',
|
||||
},
|
||||
{
|
||||
title: 'Publicar el modo oscuro',
|
||||
list: 'Sistema de diseño',
|
||||
status: 'hecha',
|
||||
priority: 'baja',
|
||||
},
|
||||
{ title: 'Migrar a Turborepo', list: 'Infra', status: 'hecha', priority: 'media' },
|
||||
{ title: 'Añadir prueba e2e', list: 'Calidad', status: 'en curso', priority: 'baja' },
|
||||
]
|
||||
|
||||
// `tableFeatures` and the columns live at module scope so row models stay stable.
|
||||
const features = tableFeatures({})
|
||||
const columnHelper = createColumnHelper<typeof features, Task>()
|
||||
|
||||
const columns = columnHelper.columns([
|
||||
columnHelper.accessor('title', { header: 'Tarea' }),
|
||||
columnHelper.accessor('list', { header: 'Lista' }),
|
||||
columnHelper.accessor('status', { header: 'Estado' }),
|
||||
columnHelper.accessor('priority', { header: 'Prioridad' }),
|
||||
])
|
||||
|
||||
const STATUS_VARIANT = {
|
||||
pendiente: 'outline',
|
||||
'en curso': 'secondary',
|
||||
hecha: 'default',
|
||||
} as const
|
||||
|
||||
function TasksPage() {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
const data = useMemo(
|
||||
() =>
|
||||
TASKS.filter((task) =>
|
||||
`${task.title} ${task.list} ${task.status}`.toLowerCase().includes(query.toLowerCase()),
|
||||
),
|
||||
[query],
|
||||
)
|
||||
|
||||
const table = useTable({ features, columns, data })
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tareas</CardTitle>
|
||||
<CardDescription>Todas las tareas de tus listas.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="relative w-full sm:max-w-sm">
|
||||
<SearchIcon className="text-muted-foreground absolute top-2.5 left-2.5 size-4" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Filtrar tareas…"
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder ? null : <table.FlexRender header={header} />}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="text-muted-foreground h-24 text-center"
|
||||
>
|
||||
Ninguna tarea coincide con el filtro.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
{row.getAllCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{cell.column.id === 'status' ? (
|
||||
<Badge variant={STATUS_VARIANT[cell.getValue<Task['status']>()]}>
|
||||
{cell.getValue<Task['status']>()}
|
||||
</Badge>
|
||||
) : (
|
||||
<table.FlexRender cell={cell} />
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import tailwindcss from '@tailwindcss/vite'
|
||||
import { tanstackRouter } from '@tanstack/router-plugin/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
import { VitePWA } from 'vite-plugin-pwa'
|
||||
|
||||
const srcDir = path.resolve(import.meta.dirname, './src')
|
||||
|
||||
@@ -13,6 +14,46 @@ export default defineConfig({
|
||||
tanstackRouter({ target: 'react', autoCodeSplitting: true }),
|
||||
react(),
|
||||
tailwindcss(),
|
||||
VitePWA({
|
||||
// `autoUpdate` pre-caches the app shell and swaps in new releases on the
|
||||
// next navigation. Registration is injected into `index.html` at build
|
||||
// time, so no `virtual:pwa-register` import is needed in the app.
|
||||
registerType: 'autoUpdate',
|
||||
includeAssets: ['favicon.svg', 'apple-touch-icon.png'],
|
||||
manifest: {
|
||||
name: 'Superlist — Listas de compras compartidas',
|
||||
short_name: 'Superlist',
|
||||
description: 'Listas de compras compartidas con las personas de tu hogar.',
|
||||
lang: 'es',
|
||||
start_url: '/',
|
||||
scope: '/',
|
||||
display: 'standalone',
|
||||
orientation: 'portrait',
|
||||
theme_color: '#ffffff',
|
||||
background_color: '#ffffff',
|
||||
icons: [
|
||||
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
|
||||
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
|
||||
{
|
||||
src: 'maskable-512x512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'maskable',
|
||||
},
|
||||
],
|
||||
},
|
||||
workbox: {
|
||||
// Pre-cache the app shell (JS/CSS/HTML + self-hosted Geist fonts).
|
||||
globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'],
|
||||
// SPA fallback so deep links work offline, but never swallow API calls.
|
||||
navigateFallback: 'index.html',
|
||||
navigateFallbackDenylist: [/^\/api\//],
|
||||
},
|
||||
devOptions: {
|
||||
// The service worker is only built for `vite build`; verify with `preview`.
|
||||
enabled: false,
|
||||
},
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
@@ -21,5 +62,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',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
65
docker-compose.yml
Normal file
65
docker-compose.yml
Normal file
@@ -0,0 +1,65 @@
|
||||
# Dokploy deployment: the API and the static frontend behind nginx.
|
||||
# The database is external (Dokploy's), and the containers join the shared
|
||||
# `dokploy-network` so Dokploy's Traefik can reach them via the Domains UI.
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/api/Dockerfile
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# Required: no sensible default for any of these.
|
||||
DATABASE_URL: ${DATABASE_URL:?Set DATABASE_URL in the Dokploy env}
|
||||
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:?Set BETTER_AUTH_SECRET in the Dokploy env}
|
||||
BETTER_AUTH_URL: ${BETTER_AUTH_URL:?Set BETTER_AUTH_URL in the Dokploy env}
|
||||
CORS_ORIGIN: ${CORS_ORIGIN:?Set CORS_ORIGIN in the Dokploy env}
|
||||
WEB_APP_URL: ${WEB_APP_URL:?Set WEB_APP_URL in the Dokploy env}
|
||||
# Optional: sensible defaults when unset.
|
||||
NODE_ENV: ${NODE_ENV:-production}
|
||||
PORT: ${PORT:-4100}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||
MAIL_FROM: ${MAIL_FROM:-}
|
||||
expose:
|
||||
- "4100"
|
||||
networks:
|
||||
- dokploy-network
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"bun",
|
||||
"-e",
|
||||
"fetch(`http://localhost:${PORT:-4100}/api/health`).then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/web/Dockerfile
|
||||
args:
|
||||
# Empty = same origin (nginx proxies /api/*). Only set this if the
|
||||
# frontend must call the API on a different origin.
|
||||
VITE_API_URL: ${VITE_API_URL:-}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
expose:
|
||||
- "80"
|
||||
networks:
|
||||
- dokploy-network
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO", "/dev/null", "http://127.0.0.1/"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
|
||||
networks:
|
||||
dokploy-network:
|
||||
external: true
|
||||
20
packages/shared/src/events.ts
Normal file
20
packages/shared/src/events.ts
Normal file
@@ -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 }
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from './events'
|
||||
export * from './problem-details'
|
||||
export * from './result'
|
||||
export * from './shopping-list'
|
||||
|
||||
@@ -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": {
|
||||
|
||||
Reference in New Issue
Block a user