Compare commits
11 Commits
feat/passw
...
feat/obser
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9c6ab92e3 | ||
|
|
dd9cf4ce43 | ||
|
|
3411b4b145 | ||
|
|
eace15b140 | ||
|
|
aa170de8d1 | ||
|
|
7ed4d27844 | ||
| f3d9996b11 | |||
|
|
6830c827d7 | ||
|
|
cc0611b6a0 | ||
|
|
9159dd9c9b | ||
| 01769314cb |
23
.env.example
23
.env.example
@@ -11,13 +11,25 @@ BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
||||
BETTER_AUTH_URL="http://localhost:4100"
|
||||
# "development" enables pretty logs, "production" emits JSON
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console.
|
||||
# OPENOBSERVE_URL="http://localhost:5080"
|
||||
# Optional: organization (defaults to "default") and stream (defaults to "superlist")
|
||||
# OPENOBSERVE_ORG="default"
|
||||
# OPENOBSERVE_STREAM="superlist"
|
||||
# OpenObserve user email and password (sent as Basic auth)
|
||||
# OPENOBSERVE_USER="root@example.com"
|
||||
# OPENOBSERVE_PASSWORD=""
|
||||
# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000)
|
||||
# METRICS_EXPORT_INTERVAL_MS="15000"
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||
# public origin users open in the browser.
|
||||
WEB_APP_URL="http://localhost:7153"
|
||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||
@@ -27,6 +39,13 @@ WEB_APP_URL="http://localhost:7153"
|
||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GEMINI_TIMEOUT_MS="8000"
|
||||
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||
# GROQ_API_KEY=""
|
||||
# Optional: model id
|
||||
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GROQ_TIMEOUT_MS="8000"
|
||||
|
||||
# --- apps/web ---
|
||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||
|
||||
60
AGENTS.md
60
AGENTS.md
@@ -6,15 +6,16 @@ Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web
|
||||
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, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
|
||||
there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
|
||||
through the Gemini API). The `health` module is the reference example.
|
||||
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, passkeys,
|
||||
shopping lists, list items and invitations exist; there is no Google login and no email verification; the
|
||||
`voice` module splits dictated text with Groq, or Gemma 4 through the Gemini API when Groq is not configured).
|
||||
The `health` module is the reference example.
|
||||
|
||||
## Stack (source of truth: `STACK.md`)
|
||||
|
||||
- Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file)
|
||||
- Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for
|
||||
validation, **Pino** for logging, **BetterAuth** for auth
|
||||
validation, **LogTape** for logging (shipped to **OpenObserve**), **BetterAuth** for auth
|
||||
- Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui**
|
||||
- Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** ·
|
||||
forms: **React Hook Form + Zod**
|
||||
@@ -100,7 +101,9 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
||||
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
||||
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
||||
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
||||
in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and
|
||||
in Dokploy. `WEB_APP_URL` is not only used for email links: it is also the WebAuthn relying-party origin, so
|
||||
it must be the exact public URL of the web app. The dictation variables (`GROQ_API_KEY`, `GROQ_MODEL`, `GROQ_TIMEOUT_MS`, `GEMINI_API_KEY`, `GEMINI_MODEL`,
|
||||
`GEMINI_TIMEOUT_MS`) are optional (Groq wins when its key is set) and
|
||||
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. 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/`.
|
||||
@@ -194,9 +197,26 @@ export class CreateAlert {
|
||||
(`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`.
|
||||
- Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that
|
||||
uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them.
|
||||
- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as
|
||||
`c.get('logger')` (already enriched with the request id); never `console.log` in the backend. Level comes from
|
||||
`LOG_LEVEL`, defaulting to `debug` (pretty) outside production and `info` (JSON) in production.
|
||||
- **Logging: LogTape** — root logger (`superlist` category) exported from `apps/api/src/lib/logger.ts`, reachable
|
||||
from handlers as `c.get('logger')`; never `console.log` in the backend. The call shape is
|
||||
`logger.info('message {prop}', { prop })` (message first, properties second; pass errors as `{ error }`).
|
||||
`configureLogging()` runs once in `src/index.ts` (tests never call it, so logging is silent there) and
|
||||
`dispose()` flushes on SIGINT/SIGTERM. Sinks: console (`@logtape/pretty` outside production, JSON lines in
|
||||
production) plus OpenObserve over OTLP/HTTP (`@logtape/otel`, `/api/<org>/v1/logs`, Basic auth, `stream-name`
|
||||
header) when `OPENOBSERVE_URL` is set (`OPENOBSERVE_ORG`, `OPENOBSERVE_STREAM`, `OPENOBSERVE_USER`,
|
||||
`OPENOBSERVE_PASSWORD`). Level comes from `LOG_LEVEL` (`debug` in dev, `info` in production; `warn` is accepted
|
||||
for `warning`). The request middleware in `app.ts` wraps each request in `withContext({ requestId })`, so every
|
||||
record logged during it carries the request id, and logs one `superlist.http` record per request with
|
||||
`method`, `path`, `route` (the Hono pattern, e.g. `/api/lists/:listId`), `status`, `durationMs`, `userId` and
|
||||
`userAgent` — `error` for 5xx, `warning` for 4xx, `debug` for `/api/health`, `info` otherwise. SSE routes
|
||||
return their `Response` immediately, so their duration is the time to open the stream.
|
||||
- **Metrics: OpenTelemetry SDK** (`apps/api/src/lib/metrics.ts`), pushed to OpenObserve over OTLP/HTTP
|
||||
(`/api/<org>/v1/metrics`, cumulative temporality) every `METRICS_EXPORT_INTERVAL_MS` (15 s) when
|
||||
`OPENOBSERVE_URL` is set; otherwise the global meter is a no-op. The same request middleware records
|
||||
`http.server.request.duration` (histogram, seconds; attributes `http.request.method`, `http.route`,
|
||||
`http.response.status_code`) and `http.server.active_requests`. Always use the route pattern
|
||||
(`routePath(c, -1)`), never the raw path, as an attribute. The OpenObserve settings live in
|
||||
`lib/openobserve.ts`, shared by logs and metrics. Dashboard guide: `docs/openobserve-dashboard.md` (importable JSON: `docs/openobserve-dashboard.json`).
|
||||
- Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound`
|
||||
(both in `apps/api/src/lib/problem-details.ts`).
|
||||
- `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on)
|
||||
@@ -207,6 +227,15 @@ export class CreateAlert {
|
||||
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
|
||||
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
|
||||
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
|
||||
- **Passkeys**: the separate `@better-auth/passkey` package (installed in both apps) adds WebAuthn sign-in.
|
||||
Pin it to the exact same version as `better-auth` (currently `1.7.7`): its peer dependencies
|
||||
(`better-call`, `@better-auth/core`) are version-locked, so a newer passkey package breaks the API.
|
||||
`lib/passkey-config.ts` derives `rpID` and `origin` from `WEB_APP_URL`, **not** from `BETTER_AUTH_URL`:
|
||||
WebAuthn runs in the browser, where the web origin is `:7153` in dev and the public web domain in
|
||||
production. Sign-in is username-less, so the plugin is configured with `residentKey: 'required'`.
|
||||
Passkeys are bound to the domain: those registered on `localhost` do not work in production (and vice
|
||||
versa). The `Passkey`/`passkeys` Prisma model is mapped by hand like the rest of the schema; the plugin
|
||||
also runs `prisma migrate deploy` before starting in production.
|
||||
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
||||
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
||||
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
||||
@@ -215,9 +244,10 @@ export class CreateAlert {
|
||||
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
||||
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
||||
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
||||
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema and follow the
|
||||
naming convention above (`users`, `sessions`, `accounts`, `verifications` with snake_case columns); regenerate
|
||||
them with the BetterAuth CLI rather than by hand if the auth config changes, then re-apply the mapping.
|
||||
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`, `Passkey`) are already in the schema and
|
||||
follow the naming convention above (`users`, `sessions`, `accounts`, `verifications`, `passkeys` with
|
||||
snake_case columns); regenerate them with the BetterAuth CLI rather than by hand if the auth config changes,
|
||||
then re-apply the mapping. `Passkey` comes from the `@better-auth/passkey` plugin, not the core CLI.
|
||||
|
||||
## Shared package (`@superlist/shared`)
|
||||
|
||||
@@ -268,6 +298,14 @@ apps/web/src/
|
||||
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`).
|
||||
- **Icon badge**: the installed PWA shows the pending items of the primary list on its icon through the Badging
|
||||
API (`lib/app-badge.ts`). `hooks/use-app-badge.ts`, mounted by the authenticated layout, follows that list's
|
||||
SSE stream even from other pages (the shared `lib/list-events-stream.ts` avoids opening a second stream) and
|
||||
re-syncs on foreground. It only runs in standalone mode; iOS additionally needs notification permission,
|
||||
requested from the settings card (`components/settings/app-badge-card.tsx`) because WebKit only grants
|
||||
badging alongside notifications. Chrome on Android does not support numeric badges (notifications show a
|
||||
dot), so this is a progressive enhancement. Updating the badge while the app is closed would need Web Push,
|
||||
which is not implemented.
|
||||
- **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
|
||||
|
||||
@@ -4,7 +4,7 @@ Monorepo with a Bun + Hono API and a React + Vite admin app.
|
||||
|
||||
| Workspace | What it is |
|
||||
| ----------------- | ----------------------------------------------------------------------- |
|
||||
| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, Pino logging |
|
||||
| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, LogTape logging |
|
||||
| `apps/web` | React + Vite + TypeScript frontend, shadcn/ui, TanStack Router + Query |
|
||||
| `packages/shared` | `@superlist/shared` — Result pattern and RFC 9457 Problem Details types |
|
||||
|
||||
|
||||
4
STACK.md
4
STACK.md
@@ -1,8 +1,8 @@
|
||||
- Monorepo con TURBO
|
||||
- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con Pino
|
||||
- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con LogTape (consola + OpenObserve vía OTLP)
|
||||
- Salidas del backend según RFC 9457 (Problem Details)
|
||||
- Frontend en React con vite y typescript. Componentes Shadcn
|
||||
- Rutas del frontend con TanStack Router usando file-based routing
|
||||
- Estado del servidor en el frontend con TanStack Query
|
||||
- Formularios del frontend con React Hook Form + Zod
|
||||
- BetterAuth para autenticación
|
||||
- BetterAuth para autenticación (email + contraseña, OTP por correo y passkeys/WebAuthn)
|
||||
|
||||
@@ -4,13 +4,25 @@ CORS_ORIGIN="http://localhost:7153"
|
||||
BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
||||
BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console.
|
||||
# OPENOBSERVE_URL="http://localhost:5080"
|
||||
# Optional: organization (defaults to "default") and stream (defaults to "superlist")
|
||||
# OPENOBSERVE_ORG="default"
|
||||
# OPENOBSERVE_STREAM="superlist"
|
||||
# OpenObserve user email and password (sent as Basic auth)
|
||||
# OPENOBSERVE_USER="root@example.com"
|
||||
# OPENOBSERVE_PASSWORD=""
|
||||
# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000)
|
||||
# METRICS_EXPORT_INTERVAL_MS="15000"
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||
# public origin users open in the browser.
|
||||
WEB_APP_URL="http://localhost:7153"
|
||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||
@@ -20,3 +32,10 @@ WEB_APP_URL="http://localhost:7153"
|
||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GEMINI_TIMEOUT_MS="8000"
|
||||
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||
# GROQ_API_KEY=""
|
||||
# Optional: model id
|
||||
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||
# Optional: timeout of the model request, in milliseconds
|
||||
# GROQ_TIMEOUT_MS="8000"
|
||||
|
||||
@@ -16,15 +16,21 @@
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@logtape/logtape": "^2.4.2",
|
||||
"@logtape/otel": "^2.4.2",
|
||||
"@logtape/pretty": "^2.4.2",
|
||||
"@opentelemetry/api": "1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "0.208.0",
|
||||
"@opentelemetry/resources": "2.2.0",
|
||||
"@opentelemetry/sdk-metrics": "2.2.0",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@superlist/shared": "workspace:*",
|
||||
"better-auth": "^1.7.7",
|
||||
"hono": "^4.13.13",
|
||||
"pg": "^8.23.1",
|
||||
"pino": "^10.4.0",
|
||||
"pino-pretty": "^13.2.0",
|
||||
"resend": "^6.32.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "passkeys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT,
|
||||
"public_key" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"credential_id" TEXT NOT NULL,
|
||||
"counter" INTEGER NOT NULL,
|
||||
"device_type" TEXT NOT NULL,
|
||||
"backed_up" BOOLEAN NOT NULL,
|
||||
"transports" TEXT,
|
||||
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
|
||||
"aaguid" TEXT,
|
||||
|
||||
CONSTRAINT "passkeys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "passkeys_user_id_idx" ON "passkeys"("user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "passkeys_credential_id_idx" ON "passkeys"("credential_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "passkeys" ADD CONSTRAINT "passkeys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "shopping_list_members" ADD COLUMN "icon" TEXT,
|
||||
ADD COLUMN "is_pinned" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "pinned_order" INTEGER;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "shopping_list_members_user_id_is_pinned_idx" ON "shopping_list_members"("user_id", "is_pinned");
|
||||
@@ -34,6 +34,7 @@ model User {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
sessions Session[]
|
||||
accounts Account[]
|
||||
passkeys Passkey[]
|
||||
ownedLists ShoppingList[] @relation("ListOwner")
|
||||
memberships ShoppingListMember[]
|
||||
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
||||
@@ -90,6 +91,29 @@ model Verification {
|
||||
@@map("verifications")
|
||||
}
|
||||
|
||||
// WebAuthn credentials registered through the BetterAuth passkey plugin.
|
||||
// `credentialID` is the raw credential id and `publicKey` the stored public key;
|
||||
// the plugin reads and writes these rows directly, so keep the column names it
|
||||
// expects (mapped to snake_case like the rest of the schema).
|
||||
model Passkey {
|
||||
id String @id
|
||||
name String?
|
||||
publicKey String @map("public_key")
|
||||
userId String @map("user_id")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
credentialID String @map("credential_id")
|
||||
counter Int
|
||||
deviceType String @map("device_type")
|
||||
backedUp Boolean @map("backed_up")
|
||||
transports String?
|
||||
createdAt DateTime? @default(now()) @map("created_at")
|
||||
aaguid String?
|
||||
|
||||
@@index([userId])
|
||||
@@index([credentialID])
|
||||
@@map("passkeys")
|
||||
}
|
||||
|
||||
// --- Domain models ----------------------------------------------------------
|
||||
|
||||
/// A collaborative shopping list. Membership (and therefore access) lives in
|
||||
@@ -144,11 +168,18 @@ model ShoppingListMember {
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
role ListRole @default(collaborator)
|
||||
isPrimary Boolean @default(false) @map("is_primary")
|
||||
/// Per user: the list is pinned to the always-visible bar (at most 4 per user).
|
||||
isPinned Boolean @default(false) @map("is_pinned")
|
||||
/// Position among the user's pinned lists (pin order); null when not pinned.
|
||||
pinnedOrder Int? @map("pinned_order")
|
||||
/// Per user: key of the icon chosen for the list (see `LIST_ICONS` in `@superlist/shared`).
|
||||
icon String?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([listId, userId])
|
||||
@@index([userId, isPrimary])
|
||||
@@index([userId, isPinned])
|
||||
@@map("shopping_list_members")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { withContext } from '@logtape/logtape'
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { requestId } from 'hono/request-id'
|
||||
import { routePath } from 'hono/route'
|
||||
import { secureHeaders } from 'hono/secure-headers'
|
||||
|
||||
import { auth } from '@/lib/auth'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { httpMetrics } from '@/lib/metrics'
|
||||
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||
import { healthModule } from '@/modules/health'
|
||||
import { invitationsModule } from '@/modules/invitations'
|
||||
import { listsModule } from '@/modules/lists'
|
||||
import { voiceModule } from '@/modules/voice'
|
||||
import type { AppEnv } from '@/types'
|
||||
import type { AppEnv, SessionUser } from '@/types'
|
||||
|
||||
const httpLogger = logger.getChild('http')
|
||||
|
||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||
.split(',')
|
||||
@@ -24,20 +29,53 @@ export function createApp() {
|
||||
app.use(cors({ origin: allowedOrigins, credentials: true }))
|
||||
app.use(requestId())
|
||||
app.use(async (c, next) => {
|
||||
const requestLogger = logger.child({ requestId: c.get('requestId') })
|
||||
c.set('logger', requestLogger)
|
||||
const requestId = c.get('requestId')
|
||||
c.set('logger', httpLogger.with({ requestId }))
|
||||
|
||||
const http = httpMetrics()
|
||||
const method = c.req.method
|
||||
http.activeRequests.add(1, { 'http.request.method': method })
|
||||
|
||||
const start = performance.now()
|
||||
await next()
|
||||
requestLogger.info(
|
||||
{
|
||||
method: c.req.method,
|
||||
try {
|
||||
// Every record logged while the request runs (module loggers included)
|
||||
// inherits the requestId through LogTape's implicit context.
|
||||
await withContext({ requestId }, next)
|
||||
} finally {
|
||||
http.activeRequests.add(-1, { 'http.request.method': method })
|
||||
}
|
||||
const elapsedMs = performance.now() - start
|
||||
const durationMs = Math.round(elapsedMs * 10) / 10
|
||||
|
||||
const status = c.res.status
|
||||
const route = routePath(c, -1)
|
||||
// SSE streams (/events) return their Response right away, so for them this is
|
||||
// the time to open the stream, not the lifetime of the connection.
|
||||
http.duration.record(elapsedMs / 1000, {
|
||||
'http.request.method': method,
|
||||
// The Hono pattern (/api/lists/:listId), never the raw path, to keep cardinality low.
|
||||
'http.route': route,
|
||||
'http.response.status_code': status,
|
||||
})
|
||||
|
||||
const userId = (c.get('user') as SessionUser | undefined)?.id
|
||||
const properties = {
|
||||
requestId,
|
||||
method,
|
||||
path: c.req.path,
|
||||
status: c.res.status,
|
||||
durationMs: Math.round(performance.now() - start),
|
||||
},
|
||||
'request',
|
||||
)
|
||||
route,
|
||||
status,
|
||||
durationMs,
|
||||
userAgent: c.req.header('user-agent'),
|
||||
...(userId && { userId }),
|
||||
}
|
||||
const message = '{method} {path} {status} in {durationMs} ms'
|
||||
|
||||
if (status >= 500) httpLogger.error(message, properties)
|
||||
else if (status >= 400) httpLogger.warn(message, properties)
|
||||
// The container healthcheck hits /api/health every 10 s.
|
||||
else if (c.req.path === '/api/health') httpLogger.debug(message, properties)
|
||||
else httpLogger.info(message, properties)
|
||||
})
|
||||
|
||||
// Every API route lives under /api: in production nginx serves the SPA on the
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
import { dispose } from '@logtape/logtape'
|
||||
|
||||
import { createApp } from '@/app'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { configureLogging, logger } from '@/lib/logger'
|
||||
import { configureMetrics, shutdownMetrics } from '@/lib/metrics'
|
||||
|
||||
await configureLogging()
|
||||
const metricsEnabled = configureMetrics()
|
||||
|
||||
const port = Number(process.env.PORT ?? 4100)
|
||||
|
||||
const app = createApp()
|
||||
|
||||
logger.info({ port }, 'api listening')
|
||||
logger.info('api listening on port {port}', { port, metricsEnabled })
|
||||
|
||||
// Flush buffered logs and the last metrics batch before exiting.
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.once(signal, async () => {
|
||||
await Promise.allSettled([shutdownMetrics(), dispose()])
|
||||
process.exit(0)
|
||||
})
|
||||
}
|
||||
|
||||
export default {
|
||||
port,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { passkey } from '@better-auth/passkey'
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
@@ -6,6 +7,7 @@ import { passwordResetEmail } from '@/lib/emails/password-reset'
|
||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { sendEmail } from '@/lib/mailer'
|
||||
import { passkeyConfig } from '@/lib/passkey-config'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
@@ -53,10 +55,19 @@ export const auth = betterAuth({
|
||||
to: email,
|
||||
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
|
||||
}).catch((error: unknown) => {
|
||||
logger.error({ err: error, to: email }, 'failed to send the password reset email')
|
||||
logger.error('failed to send the password reset email', { error, to: email })
|
||||
})
|
||||
},
|
||||
}),
|
||||
// Passkeys (Face ID, Touch ID, Windows Hello, security keys). Sign-in is
|
||||
// username-less, so credentials must be discoverable: `residentKey` is
|
||||
// required instead of the plugin's `preferred` default.
|
||||
passkey({
|
||||
...passkeyConfig,
|
||||
authenticatorSelection: {
|
||||
residentKey: 'required',
|
||||
},
|
||||
}),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
|
||||
@@ -6,9 +6,21 @@
|
||||
* key in the browser bundle):
|
||||
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`.
|
||||
* - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default.
|
||||
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default.
|
||||
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included).
|
||||
*
|
||||
* Gemma 4 writes out its reasoning before answering, which takes from 5 to over 30
|
||||
* seconds, so the request asks for `thinkingLevel: 'minimal'` (about a second). The API
|
||||
* also answers 5xx now and then, fast; those calls are retried once.
|
||||
*/
|
||||
|
||||
import {
|
||||
type GenerateInput,
|
||||
ModelError,
|
||||
postJson,
|
||||
readTimeout,
|
||||
type TextGenerator,
|
||||
} from './text-generator'
|
||||
|
||||
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
|
||||
|
||||
/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
|
||||
@@ -24,90 +36,38 @@ export type GeminiConfig = {
|
||||
|
||||
/** Reads the configuration from the environment, with the defaults above. */
|
||||
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||
const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10)
|
||||
|
||||
return {
|
||||
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
||||
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
||||
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS,
|
||||
timeoutMs: readTimeout(env.GEMINI_TIMEOUT_MS, DEFAULT_GEMINI_TIMEOUT_MS),
|
||||
} satisfies GeminiConfig
|
||||
}
|
||||
|
||||
/** Why a call failed, short enough to log (it never includes the prompt). */
|
||||
export type GeminiFailureReason =
|
||||
| 'missing-key'
|
||||
| 'timeout'
|
||||
| 'rate-limited'
|
||||
| `http-${number}`
|
||||
| 'network'
|
||||
| 'empty-response'
|
||||
|
||||
export class GeminiError extends Error {
|
||||
constructor(readonly reason: GeminiFailureReason) {
|
||||
super(`Gemini request failed: ${reason}`)
|
||||
this.name = 'GeminiError'
|
||||
}
|
||||
}
|
||||
|
||||
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
||||
export type GeminiTurn = { role: 'user' | 'model'; text: string }
|
||||
|
||||
export type GenerateInput = {
|
||||
systemInstruction: string
|
||||
turns: GeminiTurn[]
|
||||
}
|
||||
|
||||
type GenerateContentResponse = {
|
||||
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
||||
}
|
||||
|
||||
/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */
|
||||
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
||||
|
||||
export class GeminiClient implements TextGenerator {
|
||||
constructor(
|
||||
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
||||
private readonly fetchFn: typeof fetch = fetch,
|
||||
) {}
|
||||
|
||||
/** The model's text answer. Throws `GeminiError` on any failure. */
|
||||
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||
if (!this.config.apiKey) throw new GeminiError('missing-key')
|
||||
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchFn(
|
||||
const body = (await postJson(
|
||||
this.fetchFn,
|
||||
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||
{ 'x-goog-api-key': this.config.apiKey },
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
|
||||
body: JSON.stringify({
|
||||
systemInstruction: { parts: [{ text: systemInstruction }] },
|
||||
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
||||
generationConfig: { temperature: 0 },
|
||||
}),
|
||||
signal: AbortSignal.timeout(this.config.timeoutMs),
|
||||
generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
|
||||
},
|
||||
)
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : ''
|
||||
throw new GeminiError(
|
||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network',
|
||||
)
|
||||
}
|
||||
|
||||
if (response.status === 429) throw new GeminiError('rate-limited')
|
||||
if (!response.ok) throw new GeminiError(`http-${response.status}`)
|
||||
|
||||
let body: GenerateContentResponse
|
||||
try {
|
||||
body = (await response.json()) as GenerateContentResponse
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : ''
|
||||
throw new GeminiError(
|
||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response',
|
||||
)
|
||||
}
|
||||
this.config.timeoutMs,
|
||||
)) as GenerateContentResponse
|
||||
|
||||
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
||||
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
||||
@@ -116,7 +76,7 @@ export class GeminiClient implements TextGenerator {
|
||||
.join('')
|
||||
.trim()
|
||||
|
||||
if (!text) throw new GeminiError('empty-response')
|
||||
if (!text) throw new ModelError('empty-response')
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
79
apps/api/src/lib/groq.ts
Normal file
79
apps/api/src/lib/groq.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Minimal client for Groq's OpenAI-compatible `chat/completions` endpoint, called with
|
||||
* `fetch` — no SDK. Groq answers in about a second, which suits dictation. The model is
|
||||
* a reasoning one (gpt-oss): Groq returns its reasoning apart, so `content` is the answer.
|
||||
*
|
||||
* Configuration (backend only — never prefix these with `VITE_`, or Vite would put the
|
||||
* key in the browser bundle):
|
||||
* - `GROQ_API_KEY`: Groq API key (`gsk_…`). Without it every call fails with `missing-key`.
|
||||
* - `GROQ_MODEL`: model id, `openai/gpt-oss-120b` by default.
|
||||
* - `GROQ_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included).
|
||||
*/
|
||||
|
||||
import {
|
||||
type GenerateInput,
|
||||
ModelError,
|
||||
postJson,
|
||||
readTimeout,
|
||||
type TextGenerator,
|
||||
} from './text-generator'
|
||||
|
||||
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions'
|
||||
|
||||
export const DEFAULT_GROQ_MODEL = 'openai/gpt-oss-120b'
|
||||
|
||||
export const DEFAULT_GROQ_TIMEOUT_MS = 8000
|
||||
|
||||
export type GroqConfig = {
|
||||
apiKey: string | undefined
|
||||
model: string
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
/** Reads the configuration from the environment, with the defaults above. */
|
||||
export function groqConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||
return {
|
||||
apiKey: env.GROQ_API_KEY?.trim() || undefined,
|
||||
model: env.GROQ_MODEL?.trim() || DEFAULT_GROQ_MODEL,
|
||||
timeoutMs: readTimeout(env.GROQ_TIMEOUT_MS, DEFAULT_GROQ_TIMEOUT_MS),
|
||||
} satisfies GroqConfig
|
||||
}
|
||||
|
||||
type ChatCompletionResponse = {
|
||||
choices?: { message?: { content?: string | null } }[]
|
||||
}
|
||||
|
||||
export class GroqClient implements TextGenerator {
|
||||
constructor(
|
||||
private readonly config: GroqConfig = groqConfigFromEnv(),
|
||||
private readonly fetchFn: typeof fetch = fetch,
|
||||
) {}
|
||||
|
||||
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||
|
||||
const body = (await postJson(
|
||||
this.fetchFn,
|
||||
GROQ_API_URL,
|
||||
{ authorization: `Bearer ${this.config.apiKey}` },
|
||||
{
|
||||
model: this.config.model,
|
||||
messages: [
|
||||
{ role: 'system', content: systemInstruction },
|
||||
...turns.map(({ role, text }) => ({
|
||||
role: role === 'model' ? 'assistant' : 'user',
|
||||
content: text,
|
||||
})),
|
||||
],
|
||||
temperature: 0,
|
||||
},
|
||||
this.config.timeoutMs,
|
||||
)) as ChatCompletionResponse
|
||||
|
||||
const text = body.choices?.[0]?.message?.content?.trim()
|
||||
if (!text) throw new ModelError('empty-response')
|
||||
|
||||
return text
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,99 @@
|
||||
import { pino } from 'pino'
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
|
||||
import {
|
||||
configure,
|
||||
getConsoleSink,
|
||||
getLogger,
|
||||
isLogLevel,
|
||||
jsonLinesFormatter,
|
||||
type Logger,
|
||||
type LogLevel,
|
||||
type Sink,
|
||||
} from '@logtape/logtape'
|
||||
import { getOpenTelemetrySink } from '@logtape/otel'
|
||||
import { getPrettyFormatter } from '@logtape/pretty'
|
||||
|
||||
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||
|
||||
export type { Logger } from '@logtape/logtape'
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production'
|
||||
|
||||
/**
|
||||
* Single logger instance for the whole API. Import it wherever you need to log —
|
||||
* never use `console.log` in the backend.
|
||||
* Root logger of the API (category `superlist`). Import it wherever you need to
|
||||
* log — never use `console.log` in the backend. Inside a request, prefer
|
||||
* `c.get('logger')`; either way every record emitted while the request runs
|
||||
* carries its `requestId` (see `withContext` in `app.ts`).
|
||||
*
|
||||
* LogTape loggers are inert until `configureLogging()` runs (from `index.ts`),
|
||||
* so tests that import modules using it stay silent.
|
||||
*/
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'),
|
||||
...(isProduction
|
||||
? {}
|
||||
: {
|
||||
transport: {
|
||||
target: 'pino-pretty',
|
||||
options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' },
|
||||
export const logger: Logger = getLogger(['superlist'])
|
||||
|
||||
/** Accepts LogTape levels plus Pino-style aliases (`warn`) for `LOG_LEVEL`. */
|
||||
function resolveLevel(value: string | undefined): LogLevel {
|
||||
const level = value?.trim().toLowerCase()
|
||||
if (level === 'warn') return 'warning'
|
||||
if (level && isLogLevel(level)) return level
|
||||
|
||||
return isProduction ? 'info' : 'debug'
|
||||
}
|
||||
|
||||
/**
|
||||
* Ships logs to OpenObserve over OTLP/HTTP (`/api/<org>/v1/logs`), routed to a
|
||||
* stream by the `stream-name` header. Returns `null` when it is not configured.
|
||||
*/
|
||||
function openObserveSink(): Sink | null {
|
||||
const config = getOpenObserveConfig()
|
||||
if (!config) return null
|
||||
|
||||
return getOpenTelemetrySink({
|
||||
serviceName: SERVICE_NAME,
|
||||
// Nested property objects become JSON instead of util.inspect output.
|
||||
objectRenderer: 'json',
|
||||
otlpExporterConfig: {
|
||||
url: `${config.otlpBaseUrl}/v1/logs`,
|
||||
headers: { Authorization: config.authorization, 'stream-name': config.logStream },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures LogTape once, at startup: console output (pretty in development,
|
||||
* JSON lines in production) plus OpenObserve when `OPENOBSERVE_URL` is set.
|
||||
* Call `dispose()` from `@logtape/logtape` on shutdown to flush pending records.
|
||||
*/
|
||||
export async function configureLogging(): Promise<void> {
|
||||
const consoleSink = getConsoleSink({
|
||||
formatter: isProduction
|
||||
? jsonLinesFormatter
|
||||
: getPrettyFormatter({
|
||||
properties: true,
|
||||
categoryWidth: 16,
|
||||
wordWrap: false,
|
||||
// Interpolate strings bare ("GET /api/lists") instead of quoted.
|
||||
value: 'bare',
|
||||
}),
|
||||
})
|
||||
const openObserve = openObserveSink()
|
||||
|
||||
export type Logger = typeof logger
|
||||
const sinks: Record<string, Sink> = { console: consoleSink }
|
||||
if (openObserve) sinks.openObserve = openObserve
|
||||
|
||||
await configure({
|
||||
sinks,
|
||||
contextLocalStorage: new AsyncLocalStorage(),
|
||||
loggers: [
|
||||
{
|
||||
category: ['superlist'],
|
||||
sinks: Object.keys(sinks),
|
||||
lowestLevel: resolveLevel(process.env.LOG_LEVEL),
|
||||
},
|
||||
{ category: ['logtape', 'meta'], sinks: ['console'], lowestLevel: 'warning' },
|
||||
],
|
||||
})
|
||||
|
||||
if (openObserve) {
|
||||
logger.info('shipping logs to OpenObserve at {url}', { url: process.env.OPENOBSERVE_URL })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,17 +24,18 @@ function getClient(): Resend | null {
|
||||
|
||||
/**
|
||||
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
|
||||
* it logs the message with Pino instead of sending it, so invitation links are
|
||||
* it logs the message instead of sending it, so invitation links are
|
||||
* still discoverable in the terminal.
|
||||
*/
|
||||
export async function sendEmail(email: Email): Promise<void> {
|
||||
const resend = getClient()
|
||||
|
||||
if (!resend) {
|
||||
logger.info(
|
||||
{ to: email.to, subject: email.subject, text: email.text },
|
||||
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
|
||||
)
|
||||
logger.info('email not sent (RESEND_API_KEY is not set) — logging payload instead', {
|
||||
to: email.to,
|
||||
subject: email.subject,
|
||||
text: email.text,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
92
apps/api/src/lib/metrics.ts
Normal file
92
apps/api/src/lib/metrics.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { type Histogram, metrics, type UpDownCounter } from '@opentelemetry/api'
|
||||
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
|
||||
import { resourceFromAttributes } from '@opentelemetry/resources'
|
||||
import {
|
||||
AggregationTemporality,
|
||||
AggregationType,
|
||||
MeterProvider,
|
||||
PeriodicExportingMetricReader,
|
||||
} from '@opentelemetry/sdk-metrics'
|
||||
|
||||
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||
|
||||
const DEFAULT_EXPORT_INTERVAL_MS = 15_000
|
||||
|
||||
/** Bucket bounds (seconds) of the request duration histogram: 5 ms … 10 s. */
|
||||
const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
|
||||
|
||||
let provider: MeterProvider | null = null
|
||||
|
||||
/**
|
||||
* Starts exporting metrics to OpenObserve (`/api/<org>/v1/metrics`) every
|
||||
* `METRICS_EXPORT_INTERVAL_MS` (15 s by default). Without `OPENOBSERVE_URL` the
|
||||
* global meter stays a no-op, so instruments cost nothing in tests or locally.
|
||||
*/
|
||||
export function configureMetrics(): boolean {
|
||||
const config = getOpenObserveConfig()
|
||||
if (!config) return false
|
||||
|
||||
const exporter = new OTLPMetricExporter({
|
||||
url: `${config.otlpBaseUrl}/v1/metrics`,
|
||||
headers: { Authorization: config.authorization },
|
||||
// Cumulative is what OpenObserve's PromQL (rate, histogram_quantile) expects.
|
||||
temporalityPreference: AggregationTemporality.CUMULATIVE,
|
||||
})
|
||||
|
||||
provider = new MeterProvider({
|
||||
resource: resourceFromAttributes({ 'service.name': SERVICE_NAME }),
|
||||
views: [
|
||||
{
|
||||
instrumentName: 'http.server.request.duration',
|
||||
aggregation: {
|
||||
type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
|
||||
options: { boundaries: DURATION_BUCKETS },
|
||||
},
|
||||
},
|
||||
],
|
||||
readers: [
|
||||
new PeriodicExportingMetricReader({
|
||||
exporter,
|
||||
exportIntervalMillis:
|
||||
Number(process.env.METRICS_EXPORT_INTERVAL_MS) || DEFAULT_EXPORT_INTERVAL_MS,
|
||||
}),
|
||||
],
|
||||
})
|
||||
metrics.setGlobalMeterProvider(provider)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/** Flushes the last batch and stops the exporter (call on shutdown). */
|
||||
export async function shutdownMetrics(): Promise<void> {
|
||||
await provider?.shutdown()
|
||||
}
|
||||
|
||||
type HttpInstruments = {
|
||||
duration: Histogram
|
||||
activeRequests: UpDownCounter
|
||||
}
|
||||
|
||||
let http: HttpInstruments | null = null
|
||||
|
||||
/**
|
||||
* HTTP server instruments, following the OpenTelemetry semantic conventions.
|
||||
* Created lazily so they bind to the provider set by `configureMetrics()`.
|
||||
*/
|
||||
export function httpMetrics(): HttpInstruments {
|
||||
if (!http) {
|
||||
const meter = metrics.getMeter(SERVICE_NAME)
|
||||
http = {
|
||||
duration: meter.createHistogram('http.server.request.duration', {
|
||||
description: 'Duration of HTTP server requests.',
|
||||
unit: 's',
|
||||
}),
|
||||
activeRequests: meter.createUpDownCounter('http.server.active_requests', {
|
||||
description: 'Number of HTTP server requests in flight.',
|
||||
unit: '{request}',
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
return http
|
||||
}
|
||||
17
apps/api/src/lib/model.ts
Normal file
17
apps/api/src/lib/model.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { GeminiClient, geminiConfigFromEnv } from './gemini'
|
||||
import { GroqClient, groqConfigFromEnv } from './groq'
|
||||
import type { TextGenerator } from './text-generator'
|
||||
|
||||
/**
|
||||
* The model the API asks: Groq when `GROQ_API_KEY` is set (fast and steady), Gemini /
|
||||
* Gemma otherwise. Without any key the Gemini client fails with `missing-key` and
|
||||
* callers fall back to their own non-AI path.
|
||||
*/
|
||||
export function createTextGenerator(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): TextGenerator {
|
||||
const groq = groqConfigFromEnv(env)
|
||||
if (groq.apiKey) return new GroqClient(groq)
|
||||
|
||||
return new GeminiClient(geminiConfigFromEnv(env))
|
||||
}
|
||||
30
apps/api/src/lib/openobserve.ts
Normal file
30
apps/api/src/lib/openobserve.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/** Service name reported to OpenObserve for logs and metrics. */
|
||||
export const SERVICE_NAME = 'superlist-api'
|
||||
|
||||
export type OpenObserveConfig = {
|
||||
/** Base of the OTLP/HTTP endpoints: `<OPENOBSERVE_URL>/api/<org>` (append `/v1/logs`, `/v1/metrics`). */
|
||||
otlpBaseUrl: string
|
||||
/** Basic auth (user email + password) for every OTLP request. */
|
||||
authorization: string
|
||||
/** Stream that receives the logs (`stream-name` header); metrics get one stream per metric. */
|
||||
logStream: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the OpenObserve settings from the environment, or `null` when
|
||||
* `OPENOBSERVE_URL` is not set (logs and metrics then stay local).
|
||||
*/
|
||||
export function getOpenObserveConfig(): OpenObserveConfig | null {
|
||||
const baseUrl = process.env.OPENOBSERVE_URL?.trim().replace(/\/+$/, '')
|
||||
if (!baseUrl) return null
|
||||
|
||||
const org = process.env.OPENOBSERVE_ORG || 'default'
|
||||
const user = process.env.OPENOBSERVE_USER ?? ''
|
||||
const password = process.env.OPENOBSERVE_PASSWORD ?? ''
|
||||
|
||||
return {
|
||||
otlpBaseUrl: `${baseUrl}/api/${org}`,
|
||||
authorization: `Basic ${btoa(`${user}:${password}`)}`,
|
||||
logStream: process.env.OPENOBSERVE_STREAM || 'superlist',
|
||||
}
|
||||
}
|
||||
37
apps/api/src/lib/passkey-config.test.ts
Normal file
37
apps/api/src/lib/passkey-config.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
|
||||
import { passkeyOrigins } from './passkey-config'
|
||||
|
||||
describe('passkeyOrigins', () => {
|
||||
test('keeps the development port in the origin but not in the RP ID', () => {
|
||||
expect(passkeyOrigins('http://localhost:7153')).toEqual({
|
||||
origin: 'http://localhost:7153',
|
||||
rpID: 'localhost',
|
||||
})
|
||||
})
|
||||
|
||||
test('normalises trailing slashes and paths to a bare origin', () => {
|
||||
expect(passkeyOrigins('https://superlist.app/')).toEqual({
|
||||
origin: 'https://superlist.app',
|
||||
rpID: 'superlist.app',
|
||||
})
|
||||
expect(passkeyOrigins('https://superlist.app/settings')).toEqual({
|
||||
origin: 'https://superlist.app',
|
||||
rpID: 'superlist.app',
|
||||
})
|
||||
})
|
||||
|
||||
test('uses a subdomain as the RP ID', () => {
|
||||
expect(passkeyOrigins('https://app.superlist.app')).toEqual({
|
||||
origin: 'https://app.superlist.app',
|
||||
rpID: 'app.superlist.app',
|
||||
})
|
||||
})
|
||||
|
||||
test('falls back to localhost when the URL is invalid', () => {
|
||||
expect(passkeyOrigins('not a url')).toEqual({
|
||||
origin: 'http://localhost:7153',
|
||||
rpID: 'localhost',
|
||||
})
|
||||
})
|
||||
})
|
||||
30
apps/api/src/lib/passkey-config.ts
Normal file
30
apps/api/src/lib/passkey-config.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { webAppUrl } from '@/lib/web-app-url'
|
||||
|
||||
const FALLBACK_ORIGIN = 'http://localhost:7153'
|
||||
|
||||
/**
|
||||
* WebAuthn ceremonies happen in the browser, so the relying party is the public
|
||||
* web origin, not the API one: in development the web runs on :7153 while the
|
||||
* API listens on :4100. `WEB_APP_URL` is already the canonical public URL of
|
||||
* the frontend (used for invitation links), so derive both values from it.
|
||||
*
|
||||
* The RP ID must be a registrable suffix of the origin and cannot include the
|
||||
* port; `new URL().hostname` does the right thing for both `localhost` and a
|
||||
* production domain.
|
||||
*/
|
||||
export function passkeyOrigins(webUrl: string) {
|
||||
let origin: string
|
||||
|
||||
try {
|
||||
origin = new URL(webUrl).origin
|
||||
} catch {
|
||||
origin = FALLBACK_ORIGIN
|
||||
}
|
||||
|
||||
return { origin, rpID: new URL(origin).hostname }
|
||||
}
|
||||
|
||||
export const passkeyConfig = {
|
||||
...passkeyOrigins(webAppUrl),
|
||||
rpName: 'Superlist',
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export function errorHandler(error: Error, c: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
logger.error({ err: error, path: c.req.path }, 'unhandled error')
|
||||
logger.error('unhandled error on {path}', { error, path: c.req.path })
|
||||
|
||||
return problemResponse(
|
||||
c,
|
||||
|
||||
89
apps/api/src/lib/text-generator.ts
Normal file
89
apps/api/src/lib/text-generator.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* What every model client shares: the prompt shape, the `TextGenerator` contract and the
|
||||
* HTTP call with its deadline, retry and error reasons. The clients themselves
|
||||
* (`gemini.ts`, `groq.ts`) only build the request body and read the answer.
|
||||
*/
|
||||
|
||||
/** Attempts per call when the API answers 5xx (those fail fast and often pass on retry). */
|
||||
const MAX_ATTEMPTS = 2
|
||||
|
||||
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
||||
export type ModelTurn = { role: 'user' | 'model'; text: string }
|
||||
|
||||
export type GenerateInput = {
|
||||
systemInstruction: string
|
||||
turns: ModelTurn[]
|
||||
}
|
||||
|
||||
/** Something that answers a prompt with text: a model client, or a fake in tests. */
|
||||
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
||||
|
||||
/** Why a call failed, short enough to log (it never includes the prompt). */
|
||||
export type ModelFailureReason =
|
||||
| 'missing-key'
|
||||
| 'timeout'
|
||||
| 'rate-limited'
|
||||
| `http-${number}`
|
||||
| 'network'
|
||||
| 'empty-response'
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(readonly reason: ModelFailureReason) {
|
||||
super(`Model request failed: ${reason}`)
|
||||
this.name = 'ModelError'
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a positive number of milliseconds, or `fallback` when it is missing or invalid. */
|
||||
export function readTimeout(value: string | undefined, fallback: number): number {
|
||||
const timeout = Number.parseInt(value ?? '', 10)
|
||||
|
||||
return Number.isFinite(timeout) && timeout > 0 ? timeout : fallback
|
||||
}
|
||||
|
||||
function isAbort(error: unknown): boolean {
|
||||
const name = error instanceof Error ? error.name : ''
|
||||
|
||||
return name === 'TimeoutError' || name === 'AbortError'
|
||||
}
|
||||
|
||||
/**
|
||||
* POSTs `body` as JSON and returns the parsed answer. A 5xx is retried once, all attempts
|
||||
* within one `timeoutMs` deadline so a retry never makes the user wait longer. Throws
|
||||
* `ModelError` on any failure.
|
||||
*/
|
||||
export async function postJson(
|
||||
fetchFn: typeof fetch,
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
body: unknown,
|
||||
timeoutMs: number,
|
||||
): Promise<unknown> {
|
||||
const init = {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
}
|
||||
|
||||
let response: Response | undefined
|
||||
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
response = await fetchFn(url, init)
|
||||
} catch (error) {
|
||||
throw new ModelError(isAbort(error) ? 'timeout' : 'network')
|
||||
}
|
||||
|
||||
if (response.status < 500) break
|
||||
}
|
||||
|
||||
if (!response) throw new ModelError('network')
|
||||
if (response.status === 429) throw new ModelError('rate-limited')
|
||||
if (!response.ok) throw new ModelError(`http-${response.status}`)
|
||||
|
||||
try {
|
||||
return await response.json()
|
||||
} catch (error) {
|
||||
throw new ModelError(isAbort(error) ? 'timeout' : 'empty-response')
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export class CreateInvitation {
|
||||
|
||||
// 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')
|
||||
logger.warn('could not send the invitation email', { error, to: email })
|
||||
})
|
||||
|
||||
return Ok({ status: 'added', email })
|
||||
@@ -148,7 +148,7 @@ export class CreateInvitation {
|
||||
} catch (error) {
|
||||
// Without the email the invitee cannot know about the list: undo everything.
|
||||
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
|
||||
logger.error({ err: error, to: email }, 'failed to send the invitation email')
|
||||
logger.error('failed to send the invitation email', { error, to: email })
|
||||
|
||||
return Failure(
|
||||
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
|
||||
|
||||
@@ -33,12 +33,14 @@ function createDb({
|
||||
name: input.data.name,
|
||||
createdAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||
_count: { members: membershipsOnCreate },
|
||||
_count: { members: membershipsOnCreate, items: 0 },
|
||||
members: [
|
||||
{
|
||||
id: 'member-1',
|
||||
role: 'owner',
|
||||
isPrimary: input.data.members.create.isPrimary,
|
||||
isPinned: false,
|
||||
icon: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -65,6 +67,9 @@ describe('CreateShoppingList', () => {
|
||||
name: 'Compra semanal',
|
||||
role: 'owner',
|
||||
isPrimary: true,
|
||||
isPinned: false,
|
||||
icon: null,
|
||||
pendingCount: 0,
|
||||
memberCount: 1,
|
||||
createdAt: '2026-10-15T00:00:00.000Z',
|
||||
updatedAt: '2026-10-15T00:00:00.000Z',
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
|
||||
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toSummary } from '../serialize'
|
||||
import { summaryCountInclude, toSummary } from '../serialize'
|
||||
|
||||
/** Creates a shopping list owned by the user. The first list becomes primary. */
|
||||
export class CreateShoppingList {
|
||||
@@ -29,7 +29,7 @@ export class CreateShoppingList {
|
||||
},
|
||||
},
|
||||
include: {
|
||||
_count: { select: { members: true } },
|
||||
...summaryCountInclude,
|
||||
members: { where: { userId: input.userId } },
|
||||
},
|
||||
})
|
||||
@@ -44,6 +44,8 @@ export class CreateShoppingList {
|
||||
toSummary({
|
||||
role: membership.role,
|
||||
isPrimary: membership.isPrimary,
|
||||
isPinned: membership.isPinned,
|
||||
icon: membership.icon,
|
||||
list: {
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { listEventsRoute } from './events/route'
|
||||
import { getListRoute } from './get/route'
|
||||
import { listItemsModule } from './items'
|
||||
import { listListsRoute } from './list/route'
|
||||
import { updateListPreferencesRoute } from './preferences/route'
|
||||
import { setPrimaryListRoute } from './set-primary/route'
|
||||
import { updateListRoute } from './update/route'
|
||||
|
||||
@@ -17,5 +18,6 @@ export const listsModule = new Hono<AppEnv>()
|
||||
.route('/', getListRoute)
|
||||
.route('/', updateListRoute)
|
||||
.route('/', setPrimaryListRoute)
|
||||
.route('/', updateListPreferencesRoute)
|
||||
.route('/:listId/items', listItemsModule)
|
||||
.route('/:listId/events', listEventsRoute)
|
||||
|
||||
60
apps/api/src/modules/lists/list/use-case.test.ts
Normal file
60
apps/api/src/modules/lists/list/use-case.test.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { ListShoppingLists } from './use-case'
|
||||
|
||||
describe('ListShoppingLists', () => {
|
||||
it('returns the pending count and the user preferences of each list', async () => {
|
||||
const queries: unknown[] = []
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findMany: async (args: unknown) => {
|
||||
queries.push(args)
|
||||
|
||||
return [
|
||||
{
|
||||
role: 'owner',
|
||||
isPrimary: false,
|
||||
isPinned: true,
|
||||
icon: 'unknown-icon',
|
||||
list: {
|
||||
id: 'list-1',
|
||||
name: 'Verdulería',
|
||||
createdAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-11-02T00:00:00.000Z'),
|
||||
_count: { members: 1, items: 4 },
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const result = await new ListShoppingLists(db as unknown as Database).execute({
|
||||
userId: 'user-1',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
id: 'list-1',
|
||||
name: 'Verdulería',
|
||||
role: 'owner',
|
||||
isPrimary: false,
|
||||
isPinned: true,
|
||||
icon: null,
|
||||
pendingCount: 4,
|
||||
memberCount: 1,
|
||||
createdAt: '2026-11-01T00:00:00.000Z',
|
||||
updatedAt: '2026-11-02T00:00:00.000Z',
|
||||
},
|
||||
])
|
||||
expect(queries[0]).toMatchObject({
|
||||
include: {
|
||||
list: { include: { _count: { select: { items: { where: { completed: false } } } } } },
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -2,27 +2,27 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '
|
||||
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
/** Lists every shopping list the user belongs to (owned or shared). */
|
||||
import { summaryCountInclude, toSummary } from '../serialize'
|
||||
|
||||
/**
|
||||
* Lists every shopping list the user belongs to (owned or shared): the primary
|
||||
* one first, then the pinned ones in pin order, then the rest, newest first.
|
||||
*/
|
||||
export class ListShoppingLists {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
|
||||
const memberships = await this.db.shoppingListMember.findMany({
|
||||
where: { userId: input.userId },
|
||||
include: { list: { include: { _count: { select: { members: true } } } } },
|
||||
orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }],
|
||||
include: { list: { include: summaryCountInclude } },
|
||||
orderBy: [
|
||||
{ isPrimary: 'desc' },
|
||||
{ isPinned: 'desc' },
|
||||
{ pinnedOrder: { sort: 'asc', nulls: 'last' } },
|
||||
{ list: { createdAt: 'desc' } },
|
||||
],
|
||||
})
|
||||
|
||||
const lists = memberships.map((membership) => ({
|
||||
id: membership.list.id,
|
||||
name: membership.list.name,
|
||||
role: membership.role,
|
||||
isPrimary: membership.isPrimary,
|
||||
memberCount: membership.list._count.members,
|
||||
createdAt: membership.list.createdAt.toISOString(),
|
||||
updatedAt: membership.list.updatedAt.toISOString(),
|
||||
}))
|
||||
|
||||
return Ok(lists)
|
||||
return Ok(memberships.map(toSummary))
|
||||
}
|
||||
}
|
||||
|
||||
30
apps/api/src/modules/lists/preferences/route.ts
Normal file
30
apps/api/src/modules/lists/preferences/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { ListParamsSchema } from '../schema'
|
||||
import { UpdateListPreferencesSchema } from './schema'
|
||||
import { UpdateListPreferences } from './use-case'
|
||||
|
||||
/** PATCH /lists/:listId/preferences — pins the list or changes its icon (per user). */
|
||||
export const updateListPreferencesRoute = new Hono<AppEnv>().patch(
|
||||
'/:listId/preferences',
|
||||
requireSession,
|
||||
validate.param(ListParamsSchema),
|
||||
validate.json(UpdateListPreferencesSchema),
|
||||
async (c) => {
|
||||
const { listId } = c.req.valid('param')
|
||||
const body = c.req.valid('json')
|
||||
const result = await new UpdateListPreferences(prisma).execute({
|
||||
listId,
|
||||
userId: c.get('user').id,
|
||||
...body,
|
||||
})
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
)
|
||||
14
apps/api/src/modules/lists/preferences/schema.ts
Normal file
14
apps/api/src/modules/lists/preferences/schema.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ListIconSchema } from '@superlist/shared'
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Body of `PATCH /lists/:listId/preferences`: the user's own settings for the list. */
|
||||
export const UpdateListPreferencesSchema = z
|
||||
.object({
|
||||
isPinned: z.boolean().optional(),
|
||||
icon: ListIconSchema.nullable().optional(),
|
||||
})
|
||||
.refine((body) => body.isPinned !== undefined || body.icon !== undefined, {
|
||||
message: 'Indica al menos una preferencia para actualizar',
|
||||
})
|
||||
|
||||
export type UpdateListPreferencesInput = z.infer<typeof UpdateListPreferencesSchema>
|
||||
147
apps/api/src/modules/lists/preferences/use-case.test.ts
Normal file
147
apps/api/src/modules/lists/preferences/use-case.test.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { UpdateListPreferences } from './use-case'
|
||||
|
||||
type Membership = {
|
||||
role: 'owner' | 'collaborator'
|
||||
isPrimary: boolean
|
||||
isPinned: boolean
|
||||
icon: string | null
|
||||
}
|
||||
|
||||
function createDb({
|
||||
membership,
|
||||
pinnedCount = 0,
|
||||
maxPinnedOrder = null,
|
||||
}: {
|
||||
membership: Membership | null
|
||||
pinnedCount?: number
|
||||
maxPinnedOrder?: number | null
|
||||
}) {
|
||||
const updates: Array<{ data: Record<string, unknown> }> = []
|
||||
|
||||
const tx = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => membership,
|
||||
aggregate: async () => ({
|
||||
_count: { _all: pinnedCount },
|
||||
_max: { pinnedOrder: maxPinnedOrder },
|
||||
}),
|
||||
update: async (args: { data: Record<string, unknown> }) => {
|
||||
updates.push(args)
|
||||
|
||||
return {
|
||||
...membership,
|
||||
...args.data,
|
||||
list: {
|
||||
id: 'list-1',
|
||||
name: 'Casa de fin de semana',
|
||||
createdAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-11-01T00:00:00.000Z'),
|
||||
_count: { members: 2, items: 3 },
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const db = { $transaction: async (fn: (client: typeof tx) => unknown) => fn(tx) }
|
||||
|
||||
return { db: db as unknown as Database, updates }
|
||||
}
|
||||
|
||||
const collaborator: Membership = {
|
||||
role: 'collaborator',
|
||||
isPrimary: false,
|
||||
isPinned: false,
|
||||
icon: null,
|
||||
}
|
||||
|
||||
describe('UpdateListPreferences', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, updates } = createDb({ membership: null })
|
||||
const result = await new UpdateListPreferences(db).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
isPinned: true,
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('pins the list after the last pinned one and returns its pending count', async () => {
|
||||
const { db, updates } = createDb({
|
||||
membership: collaborator,
|
||||
pinnedCount: 2,
|
||||
maxPinnedOrder: 5,
|
||||
})
|
||||
const result = await new UpdateListPreferences(db).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
isPinned: true,
|
||||
icon: 'park',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(updates[0]?.data).toEqual({ isPinned: true, pinnedOrder: 6, icon: 'park' })
|
||||
expect(result.value).toMatchObject({
|
||||
isPinned: true,
|
||||
icon: 'park',
|
||||
pendingCount: 3,
|
||||
memberCount: 2,
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses to pin more than four lists', async () => {
|
||||
const { db, updates } = createDb({
|
||||
membership: collaborator,
|
||||
pinnedCount: 4,
|
||||
maxPinnedOrder: 4,
|
||||
})
|
||||
const result = await new UpdateListPreferences(db).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
isPinned: true,
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(409)
|
||||
expect(updates).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('unpins the list and clears its position', async () => {
|
||||
const { db, updates } = createDb({ membership: { ...collaborator, isPinned: true } })
|
||||
const result = await new UpdateListPreferences(db).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
isPinned: false,
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(updates[0]?.data).toEqual({ isPinned: false, pinnedOrder: null })
|
||||
})
|
||||
|
||||
it('changes only the icon of an already pinned list', async () => {
|
||||
const { db, updates } = createDb({
|
||||
membership: { ...collaborator, isPinned: true, icon: 'carrot' },
|
||||
})
|
||||
const result = await new UpdateListPreferences(db).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
isPinned: true,
|
||||
icon: null,
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(updates[0]?.data).toEqual({ icon: null })
|
||||
expect(result.value.icon).toBeNull()
|
||||
})
|
||||
})
|
||||
76
apps/api/src/modules/lists/preferences/use-case.ts
Normal file
76
apps/api/src/modules/lists/preferences/use-case.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
Failure,
|
||||
type ListIcon,
|
||||
MAX_PINNED_LISTS,
|
||||
Ok,
|
||||
type ProblemDetails,
|
||||
problems,
|
||||
type Result,
|
||||
type ShoppingListSummary,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { summaryCountInclude, toSummary } from '../serialize'
|
||||
|
||||
/**
|
||||
* Updates the user's own settings for a list: whether it is pinned to the
|
||||
* always-visible bar and which icon it shows. Any member may do it, because
|
||||
* the settings are per user (like the primary list), not shared with the list.
|
||||
*/
|
||||
export class UpdateListPreferences {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
userId: string
|
||||
isPinned?: boolean
|
||||
icon?: ListIcon | null
|
||||
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
|
||||
const where = { listId_userId: { listId: input.listId, userId: input.userId } }
|
||||
|
||||
return this.db.$transaction(async (tx) => {
|
||||
const membership = await tx.shoppingListMember.findUnique({ where })
|
||||
|
||||
if (!membership) {
|
||||
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||
}
|
||||
|
||||
const data: { isPinned?: boolean; pinnedOrder?: number | null; icon?: ListIcon | null } = {}
|
||||
|
||||
if (input.icon !== undefined) data.icon = input.icon
|
||||
|
||||
if (input.isPinned === true && !membership.isPinned) {
|
||||
const pinned = await tx.shoppingListMember.aggregate({
|
||||
where: { userId: input.userId, isPinned: true },
|
||||
_count: { _all: true },
|
||||
_max: { pinnedOrder: true },
|
||||
})
|
||||
|
||||
if (pinned._count._all >= MAX_PINNED_LISTS) {
|
||||
return Failure(
|
||||
problems.conflict(
|
||||
`Puedes fijar hasta ${MAX_PINNED_LISTS} listas. Desfija otra para fijar esta.`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
data.isPinned = true
|
||||
data.pinnedOrder = (pinned._max.pinnedOrder ?? 0) + 1
|
||||
}
|
||||
|
||||
if (input.isPinned === false && membership.isPinned) {
|
||||
data.isPinned = false
|
||||
data.pinnedOrder = null
|
||||
}
|
||||
|
||||
const updated = await tx.shoppingListMember.update({
|
||||
where,
|
||||
data,
|
||||
include: { list: { include: summaryCountInclude } },
|
||||
})
|
||||
|
||||
return Ok(toSummary(updated))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,17 @@
|
||||
import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared'
|
||||
import {
|
||||
type ListIcon,
|
||||
ListIconSchema,
|
||||
type ListMember,
|
||||
type ShoppingListDetail,
|
||||
type ShoppingListSummary,
|
||||
} from '@superlist/shared'
|
||||
|
||||
/** Reads a stored icon key; unknown keys (e.g. one removed from the set) fall back to none. */
|
||||
export function toListIcon(icon: string | null): ListIcon | null {
|
||||
const parsed = ListIconSchema.safeParse(icon)
|
||||
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
|
||||
type ListRow = {
|
||||
id: string
|
||||
@@ -10,16 +23,29 @@ type ListRow = {
|
||||
type MemberRow = {
|
||||
role: 'owner' | 'collaborator'
|
||||
isPrimary: boolean
|
||||
list: ListRow & { _count: { members: number } }
|
||||
isPinned: boolean
|
||||
icon: string | null
|
||||
list: ListRow & { _count: { members: number; items: number } }
|
||||
}
|
||||
|
||||
/** Maps a membership (with its list and member count) to the summary DTO. */
|
||||
/**
|
||||
* Prisma `include` for a summary: the member count plus the pending items
|
||||
* (`items` counts only the ones not bought yet).
|
||||
*/
|
||||
export const summaryCountInclude = {
|
||||
_count: { select: { members: true, items: { where: { completed: false } } } },
|
||||
} as const
|
||||
|
||||
/** Maps a membership (with its list, member and pending counts) to the summary DTO. */
|
||||
export function toSummary(member: MemberRow): ShoppingListSummary {
|
||||
return {
|
||||
id: member.list.id,
|
||||
name: member.list.name,
|
||||
role: member.role,
|
||||
isPrimary: member.isPrimary,
|
||||
isPinned: member.isPinned,
|
||||
icon: toListIcon(member.icon),
|
||||
pendingCount: member.list._count.items,
|
||||
memberCount: member.list._count.members,
|
||||
createdAt: member.list.createdAt.toISOString(),
|
||||
updatedAt: member.list.updatedAt.toISOString(),
|
||||
@@ -29,6 +55,8 @@ export function toSummary(member: MemberRow): ShoppingListSummary {
|
||||
type DetailRow = {
|
||||
role: 'owner' | 'collaborator'
|
||||
isPrimary: boolean
|
||||
isPinned: boolean
|
||||
icon: string | null
|
||||
list: ListRow & {
|
||||
members: Array<{
|
||||
id: string
|
||||
@@ -65,6 +93,8 @@ export function toDetail(member: DetailRow): ShoppingListDetail {
|
||||
name: member.list.name,
|
||||
role: member.role,
|
||||
isPrimary: member.isPrimary,
|
||||
isPinned: member.isPinned,
|
||||
icon: toListIcon(member.icon),
|
||||
members,
|
||||
invitations: member.list.invitations.map((invitation) => ({
|
||||
id: invitation.id,
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { summaryCountInclude, toSummary } from '../serialize'
|
||||
|
||||
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||
export class UpdateShoppingList {
|
||||
constructor(
|
||||
@@ -37,19 +39,11 @@ export class UpdateShoppingList {
|
||||
const list = await this.db.shoppingList.update({
|
||||
where: { id: input.listId },
|
||||
data: { name: input.name },
|
||||
include: { _count: { select: { members: true } } },
|
||||
include: summaryCountInclude,
|
||||
})
|
||||
|
||||
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
||||
|
||||
return Ok({
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
role: membership.role,
|
||||
isPrimary: membership.isPrimary,
|
||||
memberCount: list._count.members,
|
||||
createdAt: list.createdAt.toISOString(),
|
||||
updatedAt: list.updatedAt.toISOString(),
|
||||
})
|
||||
return Ok(toSummary({ ...membership, list }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
||||
|
||||
import type { GeminiTurn, GenerateInput } from '@/lib/gemini'
|
||||
import type { GenerateInput, ModelTurn } from '@/lib/text-generator'
|
||||
|
||||
/** What the model is told to do. Gemma accepts it as `systemInstruction`. */
|
||||
export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense.
|
||||
@@ -8,6 +8,7 @@ Recibís la transcripción de lo que alguien dictó y respondés SOLO con un arr
|
||||
|
||||
Reglas:
|
||||
- Un elemento por producto.
|
||||
- La transcripción casi nunca trae comas: los productos nombrados uno tras otro son elementos distintos ("azúcar leche y café" son 3), salvo que juntos formen un solo producto ("dulce de leche", "queso crema", "pan rallado").
|
||||
- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg.
|
||||
- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes".
|
||||
- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".
|
||||
@@ -18,7 +19,7 @@ Reglas:
|
||||
|
||||
/** The conversation sent to the model: the few-shot examples, then the transcript. */
|
||||
export function buildSplitPrompt(text: string): GenerateInput {
|
||||
const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
|
||||
const examples: ModelTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
|
||||
{ role: 'user' as const, text: said },
|
||||
{ role: 'model' as const, text: JSON.stringify(items) },
|
||||
])
|
||||
|
||||
@@ -52,6 +52,10 @@ beforeEach(() => {
|
||||
process.env.GEMINI_API_KEY = 'test-key'
|
||||
process.env.GEMINI_MODEL = 'gemma-test'
|
||||
process.env.GEMINI_TIMEOUT_MS = '50'
|
||||
// `bun test` loads `.env`: a real Groq key there would take over these Gemini tests.
|
||||
delete process.env.GROQ_API_KEY
|
||||
delete process.env.GROQ_MODEL
|
||||
delete process.env.GROQ_TIMEOUT_MS
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -120,6 +124,32 @@ describe('POST /api/voice/split', () => {
|
||||
expect(JSON.stringify(warnings)).toContain('invalid-json')
|
||||
})
|
||||
|
||||
it('asks for minimal thinking and retries a 5xx once', async () => {
|
||||
let calls = 0
|
||||
const fetchMock = mockFetch(async () =>
|
||||
++calls === 1
|
||||
? new Response('{}', { status: 500 })
|
||||
: modelAnswer('["Azúcar", "Leche", "Café"]'),
|
||||
)
|
||||
|
||||
const response = await split({ text: 'azúcar leche y café' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
|
||||
expect(sent.generationConfig.thinkingConfig).toEqual({ thinkingLevel: 'minimal' })
|
||||
})
|
||||
|
||||
it('falls back when the model answers 5xx twice', async () => {
|
||||
const fetchMock = mockFetch(async () => new Response('{}', { status: 503 }))
|
||||
|
||||
const response = await split({ text: 'pan y leche' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['pan', 'leche'] })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(JSON.stringify(warnings)).toContain('http-503')
|
||||
})
|
||||
|
||||
it('falls back without calling the model when there is no API key', async () => {
|
||||
delete process.env.GEMINI_API_KEY
|
||||
const fetchMock = mockFetch(async () => modelAnswer('[]'))
|
||||
@@ -149,3 +179,67 @@ describe('POST /api/voice/split', () => {
|
||||
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/voice/split with Groq', () => {
|
||||
beforeEach(() => {
|
||||
process.env.GROQ_API_KEY = 'gsk_test'
|
||||
process.env.GROQ_MODEL = 'llama-test'
|
||||
process.env.GROQ_TIMEOUT_MS = '50'
|
||||
})
|
||||
|
||||
function groqAnswer(content: string) {
|
||||
return Response.json({ choices: [{ message: { role: 'assistant', content } }] })
|
||||
}
|
||||
|
||||
it('asks Groq instead of Gemini when its key is set', async () => {
|
||||
const fetchMock = mockFetch(async () => groqAnswer('["Azúcar", "Leche", "Café"]'))
|
||||
|
||||
const response = await split({ text: 'azúcar leche y café' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||
expect(warnings).toHaveLength(0)
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] ?? []
|
||||
expect(url).toBe('https://api.groq.com/openai/v1/chat/completions')
|
||||
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer gsk_test')
|
||||
const sent = JSON.parse(String(init?.body))
|
||||
expect(sent.model).toBe('llama-test')
|
||||
expect(sent.temperature).toBe(0)
|
||||
expect(sent.messages[0]).toEqual({
|
||||
role: 'system',
|
||||
content: expect.stringContaining('array JSON'),
|
||||
})
|
||||
expect(sent.messages[2].role).toBe('assistant')
|
||||
expect(sent.messages.at(-1)).toEqual({ role: 'user', content: 'azúcar leche y café' })
|
||||
})
|
||||
|
||||
it('retries a 5xx once', async () => {
|
||||
let calls = 0
|
||||
const fetchMock = mockFetch(async () =>
|
||||
++calls === 1 ? new Response('{}', { status: 502 }) : groqAnswer('["Pan"]'),
|
||||
)
|
||||
|
||||
const response = await split({ text: 'pan' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['Pan'] })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('falls back when Groq is rate limited (429)', async () => {
|
||||
mockFetch(async () => new Response('{}', { status: 429 }))
|
||||
|
||||
const response = await split({ text: 'pan y queso' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||
expect(JSON.stringify(warnings)).toContain('rate-limited')
|
||||
})
|
||||
|
||||
it('falls back when Groq answers with no content', async () => {
|
||||
mockFetch(async () => groqAnswer(''))
|
||||
|
||||
const response = await split({ text: 'pan, queso' })
|
||||
|
||||
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||
expect(JSON.stringify(warnings)).toContain('empty-response')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { GeminiClient } from '@/lib/gemini'
|
||||
import { createTextGenerator } from '@/lib/model'
|
||||
import { resultJson } from '@/lib/result-json'
|
||||
import { validate } from '@/lib/validate'
|
||||
import type { AppEnv } from '@/types'
|
||||
@@ -16,7 +16,9 @@ export const splitVoiceRoute = new Hono<AppEnv>().post(
|
||||
validate.json(SplitVoiceSchema),
|
||||
async (c) => {
|
||||
const { text } = c.req.valid('json')
|
||||
const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text })
|
||||
const result = await new SplitVoiceText(createTextGenerator(), c.get('logger')).execute({
|
||||
text,
|
||||
})
|
||||
|
||||
return resultJson(c, result)
|
||||
},
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
type VoiceSplitResponse,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { GeminiError, type TextGenerator } from '@/lib/gemini'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
import { ModelError, type TextGenerator } from '@/lib/text-generator'
|
||||
|
||||
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
||||
import { buildSplitPrompt } from './prompt'
|
||||
@@ -36,7 +36,7 @@ export class SplitVoiceText {
|
||||
try {
|
||||
answer = await this.model.generate(buildSplitPrompt(text))
|
||||
} catch (error) {
|
||||
return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error')
|
||||
return this.fallback(text, error instanceof ModelError ? error.reason : 'unexpected-error')
|
||||
}
|
||||
|
||||
const items = parseModelItems(answer)
|
||||
@@ -47,7 +47,10 @@ export class SplitVoiceText {
|
||||
}
|
||||
|
||||
private fallback(text: string, reason: string): Result<VoiceSplitResponse, ProblemDetails> {
|
||||
this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split')
|
||||
this.logger.warn('voice split: using the fallback split ({reason})', {
|
||||
reason,
|
||||
textLength: text.length,
|
||||
})
|
||||
|
||||
return Ok({ items: fallbackSplit(text) })
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@hookform/resolvers": "^5.9.1",
|
||||
"@superlist/shared": "workspace:*",
|
||||
|
||||
10
apps/web/src/components/app-badge.tsx
Normal file
10
apps/web/src/components/app-badge.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { useAppBadge } from '@/hooks/use-app-badge'
|
||||
|
||||
/**
|
||||
* Keeps the installed app's icon badge in sync with the primary list. It renders
|
||||
* nothing: the icon lives outside the page.
|
||||
*/
|
||||
export function AppBadge() {
|
||||
useAppBadge()
|
||||
return null
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export function InstallPrompt() {
|
||||
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="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(var(--bottom-nav-height,4.5rem)+0.25rem+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 ? (
|
||||
|
||||
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon, XIcon } from 'lucide-react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { refocusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||
import { DICTATION_MESSAGES } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type DictateFabProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating microphone for a list that already has items. An empty list dictates from
|
||||
* its central card; this repeats that experience on a bottom sheet so the rows stay
|
||||
* on screen. The tap opens the sheet and starts listening in the same gesture, which
|
||||
* is what Safari needs to grant the microphone.
|
||||
*/
|
||||
export function DictateFab({ listId }: DictateFabProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
// "Escribir a mano" moves the focus to the composer once the sheet is gone.
|
||||
const focusInput = useRef(false)
|
||||
|
||||
const { listening, busy, processing, supported, heard, message, start, stop } = useDictateItems(
|
||||
listId,
|
||||
{
|
||||
onFinish: (added) => added && setOpen(false),
|
||||
// Closing the sheet while it listened can still end in a rejection: show it.
|
||||
onMessage: (detail) => {
|
||||
if (!open) toast.error(detail)
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: busy
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
aria-label="Dictar ítems"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
className="fixed right-4 bottom-[calc(var(--bottom-nav-height,4.5rem)+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
|
||||
onClick={() => {
|
||||
setOpen(true)
|
||||
// Called right in the click, before any state update, so the browser still
|
||||
// treats the microphone request as the user's.
|
||||
start()
|
||||
}}
|
||||
>
|
||||
<MicIcon className="size-6" />
|
||||
</Button>
|
||||
|
||||
<Sheet
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next)
|
||||
// Leaving the sheet ends the dictation: what was heard is delivered, like
|
||||
// "Detener". While the permission is still being asked it just cancels, and
|
||||
// with a request in flight it is a no-op.
|
||||
if (!next) stop()
|
||||
}}
|
||||
>
|
||||
<SheetContent
|
||||
side="bottom"
|
||||
showCloseButton={false}
|
||||
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!focusInput.current) return
|
||||
focusInput.current = false
|
||||
event.preventDefault()
|
||||
refocusNewItemInput()
|
||||
}}
|
||||
>
|
||||
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<SheetTitle className="text-lg font-semibold">Dictar ítems</SheetTitle>
|
||||
<SheetClose asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="size-11 rounded-full"
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<XIcon className="size-5" />
|
||||
</Button>
|
||||
</SheetClose>
|
||||
</div>
|
||||
<SheetDescription className="text-muted-foreground mt-1">
|
||||
Di los ítems con una pausa entre cada uno y los añadimos a la lista.
|
||||
</SheetDescription>
|
||||
|
||||
<div className="flex flex-col items-center gap-3 pt-6 pb-2">
|
||||
{supported ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant={listening ? 'default' : 'secondary'}
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
disabled={busy}
|
||||
className="relative h-12 rounded-full px-6 text-base"
|
||||
onClick={() => {
|
||||
if (listening) stop()
|
||||
else start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2Icon className="size-5 animate-spin" />
|
||||
) : listening ? (
|
||||
<SquareIcon className="size-5 fill-current" />
|
||||
) : (
|
||||
<MicIcon className="size-5" />
|
||||
)}
|
||||
{processing ? 'Procesando…' : listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-muted-foreground max-w-xs text-center text-sm">
|
||||
{DICTATION_MESSAGES.unsupported}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-11 rounded-full px-5"
|
||||
onClick={() => {
|
||||
focusInput.current = true
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
Escribir a mano
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||
|
||||
type DictateItemsButtonProps = {
|
||||
listId: string
|
||||
@@ -15,27 +13,10 @@ type DictateItemsButtonProps = {
|
||||
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||
*/
|
||||
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const { addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||
onDictationRejected: (_, detail) => setMessage(detail),
|
||||
})
|
||||
|
||||
const dictation = useMicrophoneDictation({
|
||||
onPhrases: async (phrases) => {
|
||||
const understood = await addDictation(phrases.join('\n'))
|
||||
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
|
||||
},
|
||||
onError: setMessage,
|
||||
})
|
||||
|
||||
const listening = dictation.status === 'listening'
|
||||
const busy = dictation.status === 'requesting' || processing
|
||||
const { listening, busy, processing, heard, message, start, stop } = useDictateItems(listId)
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.status === 'requesting'
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
@@ -50,9 +31,8 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
disabled={busy}
|
||||
className="relative rounded-full"
|
||||
onClick={() => {
|
||||
setMessage(null)
|
||||
if (listening) dictation.stop()
|
||||
else dictation.start()
|
||||
if (listening) stop()
|
||||
else start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
@@ -65,24 +45,7 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
|
||||
{listening && (
|
||||
<p className="text-primary flex items-center gap-2 font-medium">
|
||||
<span className="relative flex size-2.5" aria-hidden="true">
|
||||
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||
</span>
|
||||
Micrófono activo, te escuchamos
|
||||
</p>
|
||||
)}
|
||||
{listening && dictation.heard && (
|
||||
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
|
||||
)}
|
||||
{listening && !dictation.heard && (
|
||||
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
|
||||
)}
|
||||
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
|
||||
</div>
|
||||
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type DictationFeedbackProps = {
|
||||
/** Whether the microphone is listening right now. */
|
||||
listening: boolean
|
||||
/** What has been heard so far, one phrase per item. */
|
||||
heard: string
|
||||
/** Why the last dictation did not deliver anything, in Spanish. */
|
||||
message: string | null
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Live state of a dictation: that we are listening, the phrases heard so far and the
|
||||
* last error. Shared by the empty list's card and the floating button's sheet so both
|
||||
* tell the same thing.
|
||||
*/
|
||||
export function DictationFeedback({
|
||||
listening,
|
||||
heard,
|
||||
message,
|
||||
className,
|
||||
}: DictationFeedbackProps) {
|
||||
return (
|
||||
<div aria-live="polite" className={cn('flex flex-col items-center gap-1 text-sm', className)}>
|
||||
{listening && (
|
||||
<p className="text-primary flex items-center gap-2 font-medium">
|
||||
<span className="relative flex size-2.5" aria-hidden="true">
|
||||
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||
</span>
|
||||
Micrófono activo, te escuchamos
|
||||
</p>
|
||||
)}
|
||||
{listening && heard && <p className="text-muted-foreground max-w-xs text-center">{heard}</p>}
|
||||
{listening && !heard && (
|
||||
<p className="text-muted-foreground text-center">
|
||||
Di «nuevo ítem» o haz una pausa entre artículos.
|
||||
</p>
|
||||
)}
|
||||
{message && !listening && <p className="text-destructive max-w-xs text-center">{message}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { ApiError } from '@/lib/api-client'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { DictateFab } from './dictate-fab'
|
||||
import { DictateItemsButton } from './dictate-items-button'
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemSheet } from './item-sheet'
|
||||
@@ -109,7 +110,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4 pb-16">
|
||||
{pending.length > 0 && (
|
||||
<Card className="py-0">
|
||||
<ul className="divide-y">
|
||||
@@ -146,6 +147,9 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
|
||||
{/* An empty list dictates from its central card; with items, from this button. */}
|
||||
<DictateFab listId={listId} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppLogo } from '@/components/app-logo'
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||
import { NavUser } from '@/components/layout/nav-user'
|
||||
import { PinnedListsSidebarGroup } from '@/components/layout/pinned-lists'
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -60,6 +61,7 @@ export function AppSidebar() {
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
<PinnedListsSidebarGroup />
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Link, useRouterState } from '@tanstack/react-router'
|
||||
|
||||
import { focusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items'
|
||||
import { PinnedListsBar } from '@/components/layout/pinned-lists'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function BottomNav() {
|
||||
@@ -9,6 +10,7 @@ export function BottomNav() {
|
||||
|
||||
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)]">
|
||||
<PinnedListsBar />
|
||||
<nav className="mx-auto flex h-18 max-w-lg items-center justify-around px-2">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const active = isNavItemActive(pathname, item.to)
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { CheckIcon, ChevronDownIcon, ListIcon, StarIcon } from 'lucide-react'
|
||||
|
||||
import { ListGlyph } from '@/components/lists/list-glyph'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -27,12 +28,14 @@ type ListSwitcherProps = {
|
||||
*/
|
||||
export function ListSwitcher({ list }: ListSwitcherProps) {
|
||||
const { data: lists } = useLists()
|
||||
const icon = lists?.find((option) => option.id === list.id)?.icon
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<DropdownMenu>
|
||||
<h1 className="flex min-w-0">
|
||||
<DropdownMenuTrigger className="focus-visible:ring-ring/50 -ml-1 flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-left text-xl leading-tight font-bold outline-none focus-visible:ring-3">
|
||||
{icon && <ListGlyph list={{ name: list.name, icon }} className="mr-1" />}
|
||||
<span className="truncate">{list.name}</span>
|
||||
<ChevronDownIcon className="size-5 shrink-0" aria-hidden />
|
||||
<span className="sr-only">: cambiar de lista</span>
|
||||
@@ -70,6 +73,7 @@ export function ListSwitcher({ list }: ListSwitcherProps) {
|
||||
function ListOption({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||
return (
|
||||
<>
|
||||
<ListGlyph list={list} className="text-muted-foreground size-4" />
|
||||
<span className="min-w-0 flex-1 truncate">{list.name}</span>
|
||||
{list.isPrimary && <StarIcon aria-label="Principal" className="text-muted-foreground" />}
|
||||
{current && <CheckIcon aria-label="Lista actual" className="text-primary" />}
|
||||
|
||||
183
apps/web/src/components/layout/pinned-lists.tsx
Normal file
183
apps/web/src/components/layout/pinned-lists.tsx
Normal file
@@ -0,0 +1,183 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import { CheckIcon } from 'lucide-react'
|
||||
import type { ComponentProps } from 'react'
|
||||
|
||||
import { ListGlyph } from '@/components/lists/list-glyph'
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
} from '@/components/ui/sidebar'
|
||||
import { pickPrimaryList, useLists, usePinnedLists } from '@/hooks/use-lists'
|
||||
import { usePendingCount } from '@/hooks/use-pending-count'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/** The list the current page shows: the primary one on `/`, the one in the URL under `/lists/:id`. */
|
||||
function useCurrentListId(): string | undefined {
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||
const { data: lists } = useLists()
|
||||
|
||||
if (pathname === '/') return lists ? pickPrimaryList(lists)?.id : undefined
|
||||
|
||||
return /^\/lists\/([^/]+)/.exec(pathname)?.[1]
|
||||
}
|
||||
|
||||
function pendingLabel(list: ShoppingListSummary, count: number) {
|
||||
return `${list.name}: ${count === 0 ? 'nada pendiente' : `${count} ${count === 1 ? 'pendiente' : 'pendientes'}`}`
|
||||
}
|
||||
|
||||
/** Opens a list where the app expects it: the primary one on the home page, the rest on their own page. */
|
||||
function PinnedListLink({
|
||||
list,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ComponentProps<'a'> & { list: ShoppingListSummary }) {
|
||||
return list.isPrimary ? (
|
||||
<Link to="/" className={className} {...props}>
|
||||
{children}
|
||||
</Link>
|
||||
) : (
|
||||
<Link to="/lists/$listId" params={{ listId: list.id }} className={className} {...props}>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile: the pinned lists as chips above the bottom navigation, each with its
|
||||
* icon and the number of items still to buy, so the other lists stay in sight
|
||||
* while shopping from one. Renders nothing when no list is pinned.
|
||||
*
|
||||
* It is exactly 4.5rem tall (as the navigation itself), which is what the
|
||||
* authenticated layout adds to `--bottom-nav-height` while lists are pinned.
|
||||
*/
|
||||
export function PinnedListsBar() {
|
||||
const pinned = usePinnedLists()
|
||||
const currentListId = useCurrentListId()
|
||||
|
||||
if (pinned.length === 0) return null
|
||||
|
||||
return (
|
||||
<nav aria-label="Listas fijadas" className="mx-auto max-w-lg px-3 pt-2.5">
|
||||
<ul className="bg-muted/60 flex gap-1 rounded-2xl border p-1">
|
||||
{pinned.map((list) => (
|
||||
<li key={list.id} className="min-w-0 flex-1">
|
||||
<PinnedChip list={list} current={list.id === currentListId} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
function PinnedChip({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||
const count = usePendingCount(list)
|
||||
|
||||
return (
|
||||
<PinnedListLink
|
||||
list={list}
|
||||
aria-current={current ? 'page' : undefined}
|
||||
aria-label={pendingLabel(list, count)}
|
||||
className={cn(
|
||||
'relative flex h-13 flex-col items-center justify-center gap-0.5 rounded-xl px-1 text-[11px] leading-tight transition-colors',
|
||||
current
|
||||
? 'bg-background text-foreground font-medium shadow-xs'
|
||||
: count > 0
|
||||
? 'text-foreground hover:bg-background/60'
|
||||
: 'text-muted-foreground hover:bg-background/60',
|
||||
)}
|
||||
>
|
||||
<span className="relative">
|
||||
<ListGlyph list={list} />
|
||||
<PendingBadge count={count} current={current} className="absolute -top-1.5 left-3.5" />
|
||||
</span>
|
||||
<span className="w-full truncate text-center">{list.name}</span>
|
||||
</PinnedListLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PendingBadge({
|
||||
count,
|
||||
current,
|
||||
className,
|
||||
}: {
|
||||
count: number
|
||||
current: boolean
|
||||
className?: string
|
||||
}) {
|
||||
if (count === 0) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'bg-muted text-muted-foreground flex size-4 items-center justify-center rounded-full border',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-2.5" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'flex h-4.5 min-w-4.5 items-center justify-center rounded-full px-1 text-[10px] font-semibold tabular-nums',
|
||||
// The open list is already in front of the user; the others are the ones to remember.
|
||||
current ? 'bg-primary text-primary-foreground' : 'bg-destructive text-white',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{count > 99 ? '99+' : count}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Desktop: the pinned lists as a sidebar group, with the pending count (a dot when collapsed). */
|
||||
export function PinnedListsSidebarGroup() {
|
||||
const pinned = usePinnedLists()
|
||||
const currentListId = useCurrentListId()
|
||||
|
||||
if (pinned.length === 0) return null
|
||||
|
||||
return (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Fijadas</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{pinned.map((list) => (
|
||||
<PinnedSidebarItem key={list.id} list={list} current={list.id === currentListId} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
)
|
||||
}
|
||||
|
||||
function PinnedSidebarItem({ list, current }: { list: ShoppingListSummary; current: boolean }) {
|
||||
const count = usePendingCount(list)
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild isActive={current} tooltip={pendingLabel(list, count)}>
|
||||
<PinnedListLink list={list}>
|
||||
<ListGlyph list={list} className="size-4" />
|
||||
<span>{list.name}</span>
|
||||
{count > 0 && !current && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="bg-destructive absolute top-1 right-1 hidden size-2 rounded-full group-data-[collapsible=icon]:block"
|
||||
/>
|
||||
)}
|
||||
</PinnedListLink>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuBadge className={cn(count > 0 && !current && 'text-destructive')}>
|
||||
{count === 0 ? <CheckIcon className="size-3.5" aria-label="Nada pendiente" /> : count}
|
||||
</SidebarMenuBadge>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { MAX_PINNED_LISTS } from '@superlist/shared'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
|
||||
import { PinIcon, PinOffIcon, SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
|
||||
|
||||
import { ListGlyph } from '@/components/lists/list-glyph'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { useSetPrimaryList } from '@/hooks/use-lists'
|
||||
import { usePinnedLists, useSetPrimaryList, useUpdateListPreferences } from '@/hooks/use-lists'
|
||||
|
||||
type ListCardProps = {
|
||||
list: ShoppingListSummary
|
||||
@@ -18,20 +20,34 @@ export function ListCard({ list }: ListCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-1 p-4">
|
||||
<Link to="/lists/$listId" params={{ listId: list.id }} className="min-w-0 flex-1">
|
||||
<Link
|
||||
to="/lists/$listId"
|
||||
params={{ listId: list.id }}
|
||||
className="flex min-w-0 flex-1 items-center gap-3"
|
||||
>
|
||||
<span className="bg-muted text-muted-foreground flex size-10 shrink-0 items-center justify-center rounded-lg">
|
||||
<ListGlyph list={list} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-medium">{list.name}</span>
|
||||
{list.isPrimary && <Badge>Principal</Badge>}
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-xs">
|
||||
<div className="text-muted-foreground mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs whitespace-nowrap">
|
||||
<span className="flex items-center gap-1">
|
||||
<UsersIcon className="size-3.5" />
|
||||
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
|
||||
</span>
|
||||
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
|
||||
<span>
|
||||
{list.pendingCount} {list.pendingCount === 1 ? 'pendiente' : 'pendientes'}
|
||||
</span>
|
||||
</div>
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
<PinButton list={list} />
|
||||
|
||||
{!list.isPrimary && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -53,3 +69,24 @@ export function ListCard({ list }: ListCardProps) {
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
/** Pins or unpins the list to the always-visible bar (disabled once the limit is reached). */
|
||||
function PinButton({ list }: ListCardProps) {
|
||||
const updatePreferences = useUpdateListPreferences(list.id)
|
||||
const pinnedCount = usePinnedLists().length
|
||||
const limitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-pressed={list.isPinned}
|
||||
aria-label={list.isPinned ? `Desfijar ${list.name}` : `Fijar ${list.name} en la barra`}
|
||||
title={limitReached ? `Puedes fijar hasta ${MAX_PINNED_LISTS} listas` : undefined}
|
||||
disabled={limitReached || updatePreferences.isPending}
|
||||
onClick={() => updatePreferences.mutate({ isPinned: !list.isPinned })}
|
||||
>
|
||||
{list.isPinned ? <PinOffIcon className="size-4" /> : <PinIcon className="size-4" />}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
29
apps/web/src/components/lists/list-glyph.tsx
Normal file
29
apps/web/src/components/lists/list-glyph.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
|
||||
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type ListGlyphProps = {
|
||||
list: Pick<ShoppingListSummary, 'name' | 'icon'>
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** The icon the user picked for a list, or the first letter of its name when there is none. */
|
||||
export function ListGlyph({ list, className }: ListGlyphProps) {
|
||||
if (list.icon) {
|
||||
const { icon: Icon } = LIST_ICON_OPTIONS[list.icon]
|
||||
return <Icon aria-hidden className={cn('size-5 shrink-0', className)} />
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center text-sm leading-none font-semibold uppercase',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{list.name.trim().charAt(0) || '?'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
94
apps/web/src/components/lists/list-preferences-card.tsx
Normal file
94
apps/web/src/components/lists/list-preferences-card.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import { LIST_ICONS, MAX_PINNED_LISTS, type ShoppingListDetail } from '@superlist/shared'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { usePinnedLists, useUpdateListPreferences } from '@/hooks/use-lists'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { LIST_ICON_OPTIONS } from '@/lib/list-icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type ListPreferencesCardProps = {
|
||||
list: Pick<ShoppingListDetail, 'id' | 'name' | 'isPinned' | 'icon'>
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's own settings for a list: pin it to the always-visible bar and pick
|
||||
* its icon. Every member has their own, so it is shown to collaborators too.
|
||||
*/
|
||||
export function ListPreferencesCard({ list }: ListPreferencesCardProps) {
|
||||
const updatePreferences = useUpdateListPreferences(list.id)
|
||||
const pinnedCount = usePinnedLists().length
|
||||
const pinLimitReached = !list.isPinned && pinnedCount >= MAX_PINNED_LISTS
|
||||
const error = updatePreferences.error
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Acceso rápido</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-5">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos guardar el cambio.'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<label htmlFor="pin-list" className="flex items-start gap-3">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium">Fijar en la barra</span>
|
||||
<span className="text-muted-foreground block text-sm">
|
||||
{pinLimitReached
|
||||
? `Ya tienes ${MAX_PINNED_LISTS} listas fijadas. Desfija otra para fijar esta.`
|
||||
: `Siempre visible con sus pendientes, en cualquier pantalla. Hasta ${MAX_PINNED_LISTS} listas.`}
|
||||
</span>
|
||||
</span>
|
||||
<Switch
|
||||
id="pin-list"
|
||||
className="mt-1"
|
||||
checked={list.isPinned}
|
||||
disabled={pinLimitReached}
|
||||
onCheckedChange={(checked) => updatePreferences.mutate({ isPinned: checked })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<fieldset className="flex flex-col gap-2">
|
||||
<legend className="mb-2 text-sm font-medium">Ícono</legend>
|
||||
<div className="grid grid-cols-6 gap-2 sm:grid-cols-9">
|
||||
{LIST_ICONS.map((key) => {
|
||||
const { icon: Icon, label } = LIST_ICON_OPTIONS[key]
|
||||
const selected = list.icon === key
|
||||
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
// Tapping the selected icon again clears it (back to the initial).
|
||||
onClick={() => updatePreferences.mutate({ icon: selected ? null : key })}
|
||||
className={cn(
|
||||
'focus-visible:ring-ring/50 flex aspect-square min-h-11 items-center justify-center rounded-lg border outline-none transition-colors focus-visible:ring-3',
|
||||
selected
|
||||
? 'border-primary bg-primary/10 text-primary border-2'
|
||||
: 'text-muted-foreground hover:bg-muted hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" />
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
Sin ícono se muestra la inicial: «{list.name.trim().charAt(0).toUpperCase()}».
|
||||
</p>
|
||||
</fieldset>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
76
apps/web/src/components/settings/app-badge-card.tsx
Normal file
76
apps/web/src/components/settings/app-badge-card.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { BellRingIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { refreshAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||
import { isIos, isStandalone } from '@/lib/platform'
|
||||
|
||||
type Permission = NotificationPermission | 'unsupported'
|
||||
|
||||
function readPermission(): Permission {
|
||||
return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission
|
||||
}
|
||||
|
||||
/**
|
||||
* Explains the icon badge and, on iOS, asks for the notification permission the
|
||||
* system requires before showing it. Elsewhere the badge works without asking.
|
||||
*/
|
||||
export function AppBadgeCard() {
|
||||
const [permission, setPermission] = useState(readPermission)
|
||||
const supported = supportsAppBadge()
|
||||
const installed = isStandalone()
|
||||
const needsPermission = supported && installed && isIos() && permission === 'default'
|
||||
|
||||
const enable = async () => {
|
||||
if (typeof Notification === 'undefined') return
|
||||
|
||||
const result = await Notification.requestPermission()
|
||||
setPermission(result)
|
||||
if (result === 'granted') refreshAppBadge()
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Indicador en el ícono</CardTitle>
|
||||
<CardDescription>
|
||||
Muestra cuántos artículos quedan por comprar en tu lista principal, en el ícono de la app
|
||||
instalada. Se actualiza solo cuando agregas o compras artículos, aquí o desde otro móvil.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
{!supported ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Este navegador no permite mostrar números en el ícono. En Android, Chrome solo muestra
|
||||
un punto cuando la app tiene avisos.
|
||||
</p>
|
||||
) : !installed ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Abre Superlist desde su ícono (la app instalada) para activar el indicador.
|
||||
</p>
|
||||
) : needsPermission ? (
|
||||
<>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
En iPhone y iPad, el sistema pide permiso de avisos para mostrar el número en el
|
||||
ícono. No enviamos notificaciones: solo usamos el permiso para el indicador.
|
||||
</p>
|
||||
<Button size="sm" className="self-start" onClick={enable}>
|
||||
<BellRingIcon className="size-4" />
|
||||
Activar indicador
|
||||
</Button>
|
||||
</>
|
||||
) : permission === 'denied' ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Bloqueaste los avisos para Superlist. Actívalos en los ajustes de iOS para ver el número
|
||||
en el ícono.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Activo: el número sigue a los artículos pendientes de tu lista principal.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
@@ -0,0 +1,336 @@
|
||||
import {
|
||||
FingerprintIcon,
|
||||
KeyRoundIcon,
|
||||
MoreHorizontalIcon,
|
||||
PencilIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
} from 'lucide-react'
|
||||
import { type FormEvent, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
type Passkey,
|
||||
useAddPasskey,
|
||||
useDeletePasskey,
|
||||
usePasskeys,
|
||||
useUpdatePasskey,
|
||||
} from '@/hooks/use-passkeys'
|
||||
|
||||
const DEFAULT_NAME = 'Este dispositivo'
|
||||
const createdOnFormat = new Intl.DateTimeFormat('es', { dateStyle: 'medium' })
|
||||
|
||||
function passkeyLabel(passkey: Passkey) {
|
||||
return passkey.name?.trim() || 'Passkey sin nombre'
|
||||
}
|
||||
|
||||
function passkeyDetails(passkey: Passkey) {
|
||||
const created = passkey.createdAt ? new Date(passkey.createdAt) : null
|
||||
|
||||
if (!created || Number.isNaN(created.getTime())) return 'Passkey de acceso'
|
||||
|
||||
return `Creada el ${createdOnFormat.format(created)}`
|
||||
}
|
||||
|
||||
export function PasskeysCard() {
|
||||
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
||||
const passkeys = usePasskeys()
|
||||
const addPasskey = useAddPasskey()
|
||||
const updatePasskey = useUpdatePasskey()
|
||||
const deletePasskey = useDeletePasskey()
|
||||
|
||||
const [addOpen, setAddOpen] = useState(false)
|
||||
const [newName, setNewName] = useState(DEFAULT_NAME)
|
||||
const [renaming, setRenaming] = useState<Passkey | null>(null)
|
||||
const [renameName, setRenameName] = useState('')
|
||||
const [deleting, setDeleting] = useState<Passkey | null>(null)
|
||||
|
||||
const openAdd = () => {
|
||||
setNewName(DEFAULT_NAME)
|
||||
setAddOpen(true)
|
||||
}
|
||||
|
||||
const openRename = (passkey: Passkey) => {
|
||||
setRenameName(passkeyLabel(passkey))
|
||||
setRenaming(passkey)
|
||||
}
|
||||
|
||||
const onAdd = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
|
||||
try {
|
||||
await addPasskey.mutateAsync(newName.trim() || DEFAULT_NAME)
|
||||
setAddOpen(false)
|
||||
toast.success('Passkey creada.')
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'No pudimos crear la passkey.')
|
||||
}
|
||||
}
|
||||
|
||||
const onRename = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (!renaming) return
|
||||
|
||||
try {
|
||||
await updatePasskey.mutateAsync({ id: renaming.id, name: renameName.trim() || DEFAULT_NAME })
|
||||
setRenaming(null)
|
||||
toast.success('Passkey renombrada.')
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'No pudimos renombrar la passkey.')
|
||||
}
|
||||
}
|
||||
|
||||
const onDelete = async () => {
|
||||
if (!deleting) return
|
||||
|
||||
try {
|
||||
await deletePasskey.mutateAsync(deleting.id)
|
||||
setDeleting(null)
|
||||
toast.success('Passkey eliminada.')
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'No pudimos eliminar la passkey.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<CardTitle>Passkeys</CardTitle>
|
||||
<CardDescription>
|
||||
Entra con Face ID, Touch ID o Windows Hello, sin escribir tu contraseña.
|
||||
</CardDescription>
|
||||
</div>
|
||||
{supportsPasskeys && (
|
||||
<Button variant="outline" size="sm" onClick={openAdd} disabled={addPasskey.isPending}>
|
||||
<PlusIcon />
|
||||
Añadir
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!supportsPasskeys ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Este navegador no admite passkeys. Prueba con uno más reciente o con la app instalada.
|
||||
</p>
|
||||
) : passkeys.isPending ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-14 w-full" />
|
||||
<Skeleton className="h-14 w-full" />
|
||||
</div>
|
||||
) : passkeys.isError ? (
|
||||
<div className="flex flex-col items-start gap-2">
|
||||
<p className="text-destructive text-sm">
|
||||
{passkeys.error instanceof Error
|
||||
? passkeys.error.message
|
||||
: 'No pudimos cargar tus passkeys.'}
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void passkeys.refetch()}>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
) : passkeys.data.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-center">
|
||||
<KeyRoundIcon className="text-muted-foreground size-6" />
|
||||
<p className="text-sm font-medium">Todavía no tienes passkeys</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Añade una para entrar sin escribir tu contraseña.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y rounded-lg border">
|
||||
{passkeys.data.map((passkey) => (
|
||||
<li key={passkey.id} className="flex items-center gap-3 px-3 py-3">
|
||||
<span className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
|
||||
<FingerprintIcon className="size-4" />
|
||||
</span>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="truncate text-sm font-medium">{passkeyLabel(passkey)}</p>
|
||||
{passkey.backedUp && (
|
||||
<Badge variant="secondary" className="shrink-0">
|
||||
Sincronizada
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground truncate text-xs">
|
||||
{passkeyDetails(passkey)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Acciones de ${passkeyLabel(passkey)}`}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40">
|
||||
<DropdownMenuItem onClick={() => openRename(passkey)}>
|
||||
<PencilIcon />
|
||||
Renombrar
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(passkey)}>
|
||||
<Trash2Icon />
|
||||
Eliminar
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<Dialog
|
||||
open={addOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!addPasskey.isPending) setAddOpen(open)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Añadir passkey</DialogTitle>
|
||||
<DialogDescription>
|
||||
Tu dispositivo te pedirá Face ID, Touch ID, Windows Hello o tu llave de seguridad.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onAdd} className="flex flex-col gap-4">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="new-passkey-name">Nombre</FieldLabel>
|
||||
<Input
|
||||
id="new-passkey-name"
|
||||
value={newName}
|
||||
onChange={(event) => setNewName(event.target.value)}
|
||||
maxLength={60}
|
||||
autoFocus
|
||||
/>
|
||||
<FieldDescription>Te ayuda a reconocerla si añades más de una.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setAddOpen(false)}
|
||||
disabled={addPasskey.isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={addPasskey.isPending}>
|
||||
{addPasskey.isPending ? 'Creando…' : 'Crear passkey'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={renaming !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !updatePasskey.isPending) setRenaming(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Renombrar passkey</DialogTitle>
|
||||
<DialogDescription>
|
||||
Elige un nombre que te ayude a reconocer este dispositivo o llave.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onRename} className="flex flex-col gap-4">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rename-passkey">Nombre</FieldLabel>
|
||||
<Input
|
||||
id="rename-passkey"
|
||||
value={renameName}
|
||||
onChange={(event) => setRenameName(event.target.value)}
|
||||
maxLength={60}
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setRenaming(null)}
|
||||
disabled={updatePasskey.isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={updatePasskey.isPending}>
|
||||
{updatePasskey.isPending ? 'Guardando…' : 'Guardar'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !deletePasskey.isPending) setDeleting(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Eliminar passkey</DialogTitle>
|
||||
<DialogDescription>
|
||||
{deleting
|
||||
? `«${passkeyLabel(deleting)}» dejará de servir para iniciar sesión.`
|
||||
: 'Esta passkey dejará de servir para iniciar sesión.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDeleting(null)}
|
||||
disabled={deletePasskey.isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={() => void onDelete()}
|
||||
disabled={deletePasskey.isPending}
|
||||
>
|
||||
{deletePasskey.isPending ? 'Eliminando…' : 'Eliminar passkey'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
88
apps/web/src/hooks/use-app-badge.ts
Normal file
88
apps/web/src/hooks/use-app-badge.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
|
||||
import { useListEvents } from '@/hooks/use-list-events'
|
||||
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
|
||||
import { APP_BADGE_REFRESH_EVENT, setAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||
import { countPendingItems } from '@/lib/items'
|
||||
import { isStandalone } from '@/lib/platform'
|
||||
|
||||
/**
|
||||
* Keeps the number on the installed app's icon equal to the items still to buy
|
||||
* in the primary list — the list the home page opens. It follows that list's SSE
|
||||
* stream even from other pages, so a change made by another member updates the
|
||||
* badge too, and re-syncs whenever the app comes back to the foreground (iOS
|
||||
* suspends the page, and with it the stream, in the background).
|
||||
*
|
||||
* Only runs in the installed app: browsers show the badge nowhere else.
|
||||
*/
|
||||
export function useAppBadge() {
|
||||
const queryClient = useQueryClient()
|
||||
const active = isStandalone() && supportsAppBadge()
|
||||
|
||||
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: active })
|
||||
const primaryList = lists ? pickPrimaryList(lists) : undefined
|
||||
const listId = primaryList?.id
|
||||
|
||||
const { data: items } = useQuery({
|
||||
...itemsQueryOptions(listId ?? ''),
|
||||
enabled: active && Boolean(listId),
|
||||
})
|
||||
const deletingIds = usePendingDeletions()
|
||||
|
||||
// Permission can be granted while the app is open (see the settings card); the
|
||||
// data does not change, so the effect is nudged through this event.
|
||||
const [refreshToken, setRefreshToken] = useState(0)
|
||||
useEffect(() => {
|
||||
const refresh = () => setRefreshToken((token) => token + 1)
|
||||
window.addEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||
return () => window.removeEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
|
||||
// Re-run after a permission change even though the data is the same.
|
||||
void refreshToken
|
||||
|
||||
// Lists still loading: keep whatever the badge already shows instead of
|
||||
// flickering to zero (or clearing) on every launch.
|
||||
if (!lists) return
|
||||
|
||||
if (!listId) {
|
||||
void setAppBadge(0)
|
||||
return
|
||||
}
|
||||
|
||||
if (!items) return
|
||||
|
||||
void setAppBadge(countPendingItems(items, deletingIds))
|
||||
}, [active, lists, listId, items, deletingIds, refreshToken])
|
||||
|
||||
// The icon outlives the page: signing out should not leave somebody else's
|
||||
// pending items on it.
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
return () => void setAppBadge(0)
|
||||
}, [active])
|
||||
|
||||
// Remote additions to the primary list while another page is open.
|
||||
useListEvents(active ? listId : undefined)
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
|
||||
const refresh = () => {
|
||||
if (document.visibilityState !== 'visible') return
|
||||
void queryClient.invalidateQueries({ queryKey: ['lists'] })
|
||||
if (listId) void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', refresh)
|
||||
window.addEventListener('online', refresh)
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', refresh)
|
||||
window.removeEventListener('online', refresh)
|
||||
}
|
||||
}, [active, listId, queryClient])
|
||||
}
|
||||
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type UseDictateItemsOptions = {
|
||||
/**
|
||||
* The dictation finished: `added` says whether anything made it to the list, so a
|
||||
* sheet can close on success and stay open to show why nothing was added.
|
||||
*/
|
||||
onFinish?: (added: boolean) => void
|
||||
/**
|
||||
* A message was set (an error, or a dictation the API limits rejected). A surface that
|
||||
* may already be closed uses this to show it somewhere else, e.g. as a toast.
|
||||
*/
|
||||
onMessage?: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation of items into a list, shared by the empty list's card and the floating
|
||||
* button: the microphone listens until the user stops it and the transcript goes
|
||||
* through `addDictation` (split by the API, undoable). Errors and limits stay in
|
||||
* `message` so each surface can show them where it fits.
|
||||
*/
|
||||
export function useDictateItems(
|
||||
listId: string,
|
||||
{ onFinish, onMessage }: UseDictateItemsOptions = {},
|
||||
) {
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
// A rejected dictation is reported from a callback, so the outcome of `addDictation`
|
||||
// is read from here once it resolves.
|
||||
const rejected = useRef(false)
|
||||
|
||||
const showMessage = (detail: string) => {
|
||||
setMessage(detail)
|
||||
onMessage?.(detail)
|
||||
}
|
||||
|
||||
const { addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||
onDictationRejected: (_, detail) => {
|
||||
rejected.current = true
|
||||
showMessage(detail)
|
||||
},
|
||||
})
|
||||
|
||||
const dictation = useMicrophoneDictation({
|
||||
onPhrases: async (phrases) => {
|
||||
rejected.current = false
|
||||
const understood = await addDictation(phrases.join('\n'))
|
||||
if (!rejected.current && understood === 0) showMessage(DICTATION_MESSAGES.empty)
|
||||
onFinish?.(understood > 0 && !rejected.current)
|
||||
},
|
||||
onError: (detail) => {
|
||||
showMessage(detail)
|
||||
onFinish?.(false)
|
||||
},
|
||||
})
|
||||
|
||||
const listening = dictation.status === 'listening'
|
||||
|
||||
return {
|
||||
listening,
|
||||
/** Asking for the microphone or splitting the transcript: no new dictation yet. */
|
||||
busy: dictation.status === 'requesting' || processing,
|
||||
processing,
|
||||
supported: dictation.supported,
|
||||
/** What has been heard so far, shown while listening. */
|
||||
heard: dictation.heard,
|
||||
message,
|
||||
start: () => {
|
||||
setMessage(null)
|
||||
dictation.start()
|
||||
},
|
||||
stop: dictation.stop,
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import {
|
||||
canDictate,
|
||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||
isIosStandalone,
|
||||
type SpeechRecognitionConstructor,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||
@@ -21,10 +20,8 @@ const ERROR_MESSAGES: Record<string, string> = {
|
||||
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
||||
* unsupported (the keyboard's own dictation still works).
|
||||
*/
|
||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined' || isIosStandalone()) return null
|
||||
|
||||
return getBrowserSpeechRecognition()
|
||||
function getSpeechRecognition() {
|
||||
return canDictate() ? getBrowserSpeechRecognition() : null
|
||||
}
|
||||
|
||||
type UseDictationOptions = {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as React from 'react'
|
||||
|
||||
import { isIos, isStandalone } from '@/lib/platform'
|
||||
|
||||
/**
|
||||
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
|
||||
* for it. This is the subset of the event we use.
|
||||
@@ -20,23 +22,13 @@ function readDismissed() {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
const isSafari =
|
||||
/safari/i.test(navigator.userAgent) && !/crios|fxios|edgios/i.test(navigator.userAgent)
|
||||
return isIos() && isSafari
|
||||
}
|
||||
|
||||
export type InstallPromptState = {
|
||||
@@ -58,7 +50,7 @@ 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)
|
||||
const [isIosSafariDevice] = React.useState(isIosSafari)
|
||||
|
||||
React.useEffect(() => {
|
||||
const onBeforeInstallPrompt = (event: Event) => {
|
||||
@@ -97,7 +89,7 @@ export function useInstallPrompt(): InstallPromptState {
|
||||
}, [])
|
||||
|
||||
const canInstall = deferredPrompt !== null
|
||||
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
|
||||
const needsManualInstructions = isIosSafariDevice && !deferredPrompt && !isInstalled
|
||||
|
||||
return {
|
||||
canInstall,
|
||||
|
||||
@@ -1,47 +1,35 @@
|
||||
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'
|
||||
import { queryKeysForListEvent } from '@/lib/list-events'
|
||||
import { subscribeToListEvents } from '@/lib/list-events-stream'
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Follows 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.
|
||||
* reconcile anything missed while disconnected. The connection is shared with
|
||||
* any other subscriber of the same list (see `list-events-stream.ts`).
|
||||
*
|
||||
* Pass `undefined` to follow nothing (e.g. while the primary list is unknown).
|
||||
*/
|
||||
export function useListEvents(listId: string) {
|
||||
export function useListEvents(listId: string | undefined) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
useEffect(() => {
|
||||
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
if (!listId) return
|
||||
|
||||
const onReady = () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||
}
|
||||
|
||||
source.addEventListener('ready', onReady)
|
||||
|
||||
const listeners = LIST_EVENT_TYPES.map((type) => {
|
||||
const listener = () => {
|
||||
return subscribeToListEvents(listId, {
|
||||
onEvent: (type) => {
|
||||
for (const queryKey of queryKeysForListEvent(type, listId)) {
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
void queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
}
|
||||
|
||||
source.addEventListener(type, listener)
|
||||
return { type, listener }
|
||||
},
|
||||
onReady: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||
},
|
||||
})
|
||||
|
||||
return () => {
|
||||
source.removeEventListener('ready', onReady)
|
||||
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
|
||||
source.close()
|
||||
}
|
||||
}, [listId, queryClient])
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import type {
|
||||
ShoppingListDetail,
|
||||
ShoppingListSummary,
|
||||
UpdateListPreferencesRequest,
|
||||
} from '@superlist/shared'
|
||||
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
import { apiFetch } from '@/lib/api-client'
|
||||
@@ -18,6 +22,61 @@ export function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSumma
|
||||
return lists.find((list) => list.isPrimary) ?? lists[0]
|
||||
}
|
||||
|
||||
/** The lists pinned to the always-visible bar, in the API's order. */
|
||||
export function pickPinnedLists(lists: ShoppingListSummary[]): ShoppingListSummary[] {
|
||||
return lists.filter((list) => list.isPinned)
|
||||
}
|
||||
|
||||
export function usePinnedLists(): ShoppingListSummary[] {
|
||||
const { data: lists } = useLists()
|
||||
return lists ? pickPinnedLists(lists) : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Pins/unpins a list or changes its icon (the user's own settings). The change is
|
||||
* applied to the cached lists and list detail right away and rolled back if the
|
||||
* API refuses it (e.g. a fifth pinned list).
|
||||
*/
|
||||
export function useUpdateListPreferences(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const listsKey = listsQueryOptions().queryKey
|
||||
const detailKey = ['lists', listId]
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input: UpdateListPreferencesRequest) =>
|
||||
apiFetch<ShoppingListSummary>(`/lists/${listId}/preferences`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
onMutate: async (input) => {
|
||||
await queryClient.cancelQueries({ queryKey: listsKey, exact: true })
|
||||
await queryClient.cancelQueries({ queryKey: detailKey, exact: true })
|
||||
|
||||
const previousLists = queryClient.getQueryData<ShoppingListSummary[]>(listsKey)
|
||||
const previousDetail = queryClient.getQueryData<ShoppingListDetail>(detailKey)
|
||||
|
||||
queryClient.setQueryData<ShoppingListSummary[]>(listsKey, (lists) =>
|
||||
lists?.map((list) => (list.id === listId ? { ...list, ...input } : list)),
|
||||
)
|
||||
queryClient.setQueryData<ShoppingListDetail>(detailKey, (detail) =>
|
||||
detail ? { ...detail, ...input } : detail,
|
||||
)
|
||||
|
||||
return { previousLists, previousDetail }
|
||||
},
|
||||
onError: (_error, _input, context) => {
|
||||
queryClient.setQueryData(listsKey, context?.previousLists)
|
||||
queryClient.setQueryData(detailKey, context?.previousDetail)
|
||||
},
|
||||
// `exact`: only the collection and this list's detail, not every list's items.
|
||||
onSettled: () =>
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: listsKey, exact: true }),
|
||||
queryClient.invalidateQueries({ queryKey: detailKey, exact: true }),
|
||||
]),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateList() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ type UseMicrophoneDictationOptions = {
|
||||
* capture. Unmounting aborts the recognition.
|
||||
*/
|
||||
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||
const [supported] = useState(() => getSpeechRecognition() !== null)
|
||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||
// What has been heard so far, shown while listening.
|
||||
const [heard, setHeard] = useState('')
|
||||
@@ -150,5 +151,5 @@ export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDict
|
||||
/** Stops listening; what was heard so far is delivered. */
|
||||
const stop = useCallback(() => endRef.current?.(true), [])
|
||||
|
||||
return { status, heard, start, stop }
|
||||
return { status, heard, supported, start, stop }
|
||||
}
|
||||
|
||||
76
apps/web/src/hooks/use-passkeys.ts
Normal file
76
apps/web/src/hooks/use-passkeys.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
import { authClient } from '@/lib/auth-client'
|
||||
|
||||
export type Passkey = NonNullable<
|
||||
Awaited<ReturnType<typeof authClient.passkey.listUserPasskeys>>['data']
|
||||
>[number]
|
||||
|
||||
const PASSKEYS_QUERY_KEY = ['passkeys'] as const
|
||||
|
||||
export const passkeysQueryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: PASSKEYS_QUERY_KEY,
|
||||
queryFn: async () => {
|
||||
const { data, error } = await authClient.passkey.listUserPasskeys()
|
||||
|
||||
if (error) throw new Error(error.message ?? 'No pudimos cargar tus passkeys.')
|
||||
|
||||
return data ?? []
|
||||
},
|
||||
})
|
||||
|
||||
export function usePasskeys() {
|
||||
return useQuery(passkeysQueryOptions())
|
||||
}
|
||||
|
||||
function toError(error: { message?: string } | null, fallback: string) {
|
||||
return new Error(error?.message ?? fallback)
|
||||
}
|
||||
|
||||
export function useAddPasskey() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (name: string) => {
|
||||
const { data, error } = await authClient.passkey.addPasskey({ name })
|
||||
|
||||
if (error) throw toError(error, 'No pudimos crear la passkey.')
|
||||
|
||||
return data
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdatePasskey() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ id, name }: { id: string; name: string }) => {
|
||||
const { error } = await authClient.passkey.updatePasskey({ id, name })
|
||||
|
||||
if (error) throw toError(error, 'No pudimos renombrar la passkey.')
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeletePasskey() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const { error } = await authClient.passkey.deletePasskey({ id })
|
||||
|
||||
if (error) throw toError(error, 'No pudimos eliminar la passkey.')
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||
},
|
||||
})
|
||||
}
|
||||
22
apps/web/src/hooks/use-pending-count.ts
Normal file
22
apps/web/src/hooks/use-pending-count.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { ShoppingListSummary } from '@superlist/shared'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
|
||||
import { useListEvents } from '@/hooks/use-list-events'
|
||||
import { countPendingItems } from '@/lib/items'
|
||||
|
||||
/**
|
||||
* Items still to buy in a list, kept live from any page: it reads the list's
|
||||
* items (so optimistic changes and deletions waiting for undo count the same as
|
||||
* on the list itself) and follows its SSE stream, shared with any other
|
||||
* subscriber of that list. Until the items load it falls back to the count
|
||||
* the lists endpoint returned.
|
||||
*/
|
||||
export function usePendingCount(list: Pick<ShoppingListSummary, 'id' | 'pendingCount'>): number {
|
||||
const { data: items } = useQuery(itemsQueryOptions(list.id))
|
||||
const deletingIds = usePendingDeletions()
|
||||
|
||||
useListEvents(list.id)
|
||||
|
||||
return items ? countPendingItems(items, deletingIds) : list.pendingCount
|
||||
}
|
||||
56
apps/web/src/lib/app-badge.test.ts
Normal file
56
apps/web/src/lib/app-badge.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { setAppBadge, supportsAppBadge } from './app-badge'
|
||||
|
||||
type BadgingNavigator = Navigator & {
|
||||
setAppBadge?: (contents?: number) => Promise<void>
|
||||
clearAppBadge?: () => Promise<void>
|
||||
}
|
||||
|
||||
const badging = navigator as BadgingNavigator
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(badging, 'setAppBadge')
|
||||
Reflect.deleteProperty(badging, 'clearAppBadge')
|
||||
})
|
||||
|
||||
describe('supportsAppBadge', () => {
|
||||
it('is false when the browser has no Badging API', () => {
|
||||
expect(supportsAppBadge()).toBe(false)
|
||||
})
|
||||
|
||||
it('is true when setAppBadge is available', () => {
|
||||
badging.setAppBadge = () => Promise.resolve()
|
||||
|
||||
expect(supportsAppBadge()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setAppBadge', () => {
|
||||
it('shows the count on the icon', async () => {
|
||||
const set = vi.fn(() => Promise.resolve())
|
||||
badging.setAppBadge = set
|
||||
badging.clearAppBadge = () => Promise.resolve()
|
||||
|
||||
await setAppBadge(4)
|
||||
|
||||
expect(set).toHaveBeenCalledWith(4)
|
||||
})
|
||||
|
||||
it('clears the badge when nothing is pending', async () => {
|
||||
const clear = vi.fn(() => Promise.resolve())
|
||||
badging.setAppBadge = () => Promise.resolve()
|
||||
badging.clearAppBadge = clear
|
||||
|
||||
await setAppBadge(0)
|
||||
|
||||
expect(clear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('ignores a rejected call (not installed, permission denied)', async () => {
|
||||
badging.setAppBadge = () => Promise.reject(new Error('NotAllowedError'))
|
||||
badging.clearAppBadge = () => Promise.resolve()
|
||||
|
||||
await expect(setAppBadge(2)).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
39
apps/web/src/lib/app-badge.ts
Normal file
39
apps/web/src/lib/app-badge.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Name of the window event used to ask `useAppBadge` for a fresh sync (for
|
||||
* example right after the user grants notification permission, which the
|
||||
* effect cannot observe on its own).
|
||||
*/
|
||||
export const APP_BADGE_REFRESH_EVENT = 'superlist:app-badge-refresh'
|
||||
|
||||
/** Whether this browser can show a badge on the installed app's icon. */
|
||||
export function supportsAppBadge(): boolean {
|
||||
return typeof navigator !== 'undefined' && 'setAppBadge' in navigator
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `count` on the icon of the installed app (Badging API). Zero removes
|
||||
* the badge. Browsers without support, calls made from a tab instead of the
|
||||
* installed app, and platforms where the permission is missing (iOS needs
|
||||
* notifications allowed) reject the promise; the badge simply stays as it was.
|
||||
*/
|
||||
export function setAppBadge(count: number): Promise<void> {
|
||||
if (!supportsAppBadge()) return Promise.resolve()
|
||||
|
||||
const value = Math.max(0, Math.trunc(count))
|
||||
const request =
|
||||
value > 0
|
||||
? navigator.setAppBadge(value)
|
||||
: navigator.clearAppBadge
|
||||
? navigator.clearAppBadge()
|
||||
: Promise.resolve()
|
||||
|
||||
return request.catch(() => {
|
||||
// Not installed, permission denied or document not fully active: a badge is
|
||||
// a hint, never something worth breaking a render or logging an error for.
|
||||
})
|
||||
}
|
||||
|
||||
/** Asks the badge sync to run again, even when no data changed. */
|
||||
export function refreshAppBadge() {
|
||||
if (typeof window !== 'undefined') window.dispatchEvent(new Event(APP_BADGE_REFRESH_EVENT))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { passkeyClient } from '@better-auth/passkey/client'
|
||||
import { emailOTPClient } from 'better-auth/client/plugins'
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
|
||||
@@ -8,7 +9,7 @@ import { createAuthClient } from 'better-auth/react'
|
||||
*/
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||
plugins: [emailOTPClient()],
|
||||
plugins: [emailOTPClient(), passkeyClient()],
|
||||
})
|
||||
|
||||
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { quantityLabel, splitItems } from './items'
|
||||
import { countPendingItems, quantityLabel, splitItems } from './items'
|
||||
|
||||
function item(overrides: Partial<ListItem>): ListItem {
|
||||
return {
|
||||
@@ -86,6 +86,28 @@ describe('splitItems', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('countPendingItems', () => {
|
||||
it('counts only the items still to buy', () => {
|
||||
const items = [
|
||||
item({ id: 'a' }),
|
||||
item({ id: 'b' }),
|
||||
item({ id: 'c', completed: true, boughtAt: new Date(2026, 9, 15, 9, 0).toISOString() }),
|
||||
]
|
||||
|
||||
expect(countPendingItems(items)).toBe(2)
|
||||
})
|
||||
|
||||
it('ignores items that are already hidden by a pending deletion', () => {
|
||||
const items = [item({ id: 'a' }), item({ id: 'b' })]
|
||||
|
||||
expect(countPendingItems(items, new Set(['b']))).toBe(1)
|
||||
})
|
||||
|
||||
it('is zero for an empty list', () => {
|
||||
expect(countPendingItems([])).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('quantityLabel', () => {
|
||||
it('shows quantities with a unit, litres in capitals', () => {
|
||||
expect(quantityLabel('2 l')).toBe('2 L')
|
||||
|
||||
@@ -40,6 +40,24 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
|
||||
return { pending, boughtToday }
|
||||
}
|
||||
|
||||
/**
|
||||
* How many items are still to buy. `hidden` holds ids that are already gone
|
||||
* from the UI (a deletion waiting for undo), so a row the user no longer sees
|
||||
* never counts.
|
||||
*/
|
||||
export function countPendingItems(
|
||||
items: ListItem[],
|
||||
hidden: ReadonlySet<string> = new Set(),
|
||||
): number {
|
||||
let count = 0
|
||||
|
||||
for (const item of items) {
|
||||
if (!item.completed && !hidden.has(item.id)) count++
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */
|
||||
const BARE_WEIGHT_FROM = 50
|
||||
|
||||
|
||||
66
apps/web/src/lib/list-events-stream.ts
Normal file
66
apps/web/src/lib/list-events-stream.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type { ListEventType } from '@superlist/shared'
|
||||
|
||||
import { apiBaseUrl } from './api-client'
|
||||
import { LIST_EVENT_TYPES } from './list-events'
|
||||
|
||||
type Subscriber = {
|
||||
onEvent: (type: ListEventType) => void
|
||||
onReady: () => void
|
||||
}
|
||||
|
||||
type Stream = {
|
||||
source: EventSource
|
||||
subscribers: Set<Subscriber>
|
||||
}
|
||||
|
||||
/**
|
||||
* One `EventSource` per list, shared by every hook that needs it: the item list
|
||||
* and the app badge both follow the primary list, and opening two streams to the
|
||||
* same endpoint would only duplicate requests and invalidations.
|
||||
*/
|
||||
const streams = new Map<string, Stream>()
|
||||
|
||||
function createStream(listId: string): Stream {
|
||||
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
const stream: Stream = { source, subscribers: new Set() }
|
||||
|
||||
for (const type of LIST_EVENT_TYPES) {
|
||||
source.addEventListener(type, () => {
|
||||
for (const subscriber of stream.subscribers) subscriber.onEvent(type)
|
||||
})
|
||||
}
|
||||
|
||||
// Emitted on every (re)connection: anything missed while disconnected has to
|
||||
// be fetched again.
|
||||
source.addEventListener('ready', () => {
|
||||
for (const subscriber of stream.subscribers) subscriber.onReady()
|
||||
})
|
||||
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows a list's stream while at least one subscriber exists. The connection
|
||||
* opens with the first one and closes with the last; returns the unsubscribe.
|
||||
*/
|
||||
export function subscribeToListEvents(listId: string, subscriber: Subscriber): () => void {
|
||||
let stream = streams.get(listId)
|
||||
|
||||
if (!stream) {
|
||||
stream = createStream(listId)
|
||||
streams.set(listId, stream)
|
||||
}
|
||||
|
||||
stream.subscribers.add(subscriber)
|
||||
|
||||
return () => {
|
||||
stream.subscribers.delete(subscriber)
|
||||
|
||||
if (stream.subscribers.size === 0) {
|
||||
stream.source.close()
|
||||
streams.delete(listId)
|
||||
}
|
||||
}
|
||||
}
|
||||
45
apps/web/src/lib/list-icons.ts
Normal file
45
apps/web/src/lib/list-icons.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { ListIcon } from '@superlist/shared'
|
||||
import {
|
||||
AppleIcon,
|
||||
BabyIcon,
|
||||
BeefIcon,
|
||||
CarrotIcon,
|
||||
CroissantIcon,
|
||||
DogIcon,
|
||||
FishIcon,
|
||||
GiftIcon,
|
||||
HammerIcon,
|
||||
HouseIcon,
|
||||
type LucideIcon,
|
||||
MilkIcon,
|
||||
ParkIcon,
|
||||
PillIcon,
|
||||
ShirtIcon,
|
||||
ShoppingCartIcon,
|
||||
TreesIcon,
|
||||
WineIcon,
|
||||
} from 'lucide-react'
|
||||
|
||||
/**
|
||||
* The icons a list can show, in picker order. Keys come from `LIST_ICONS` in
|
||||
* `@superlist/shared` (the API validates them); the labels are for screen readers.
|
||||
*/
|
||||
export const LIST_ICON_OPTIONS: Record<ListIcon, { icon: LucideIcon; label: string }> = {
|
||||
'shopping-cart': { icon: ShoppingCartIcon, label: 'Carrito' },
|
||||
carrot: { icon: CarrotIcon, label: 'Zanahoria' },
|
||||
apple: { icon: AppleIcon, label: 'Manzana' },
|
||||
house: { icon: HouseIcon, label: 'Casa' },
|
||||
trees: { icon: TreesIcon, label: 'Árboles' },
|
||||
park: { icon: ParkIcon, label: 'Parque' },
|
||||
beef: { icon: BeefIcon, label: 'Carne' },
|
||||
fish: { icon: FishIcon, label: 'Pescado' },
|
||||
milk: { icon: MilkIcon, label: 'Leche' },
|
||||
croissant: { icon: CroissantIcon, label: 'Panadería' },
|
||||
wine: { icon: WineIcon, label: 'Bebidas' },
|
||||
pill: { icon: PillIcon, label: 'Farmacia' },
|
||||
baby: { icon: BabyIcon, label: 'Bebé' },
|
||||
dog: { icon: DogIcon, label: 'Mascotas' },
|
||||
shirt: { icon: ShirtIcon, label: 'Ropa' },
|
||||
hammer: { icon: HammerIcon, label: 'Ferretería' },
|
||||
gift: { icon: GiftIcon, label: 'Regalos' },
|
||||
}
|
||||
@@ -26,6 +26,9 @@ const EXPECTED: Record<
|
||||
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
|
||||
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
|
||||
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' },
|
||||
Azúcar: { name: 'Azúcar', amount: null, unit: null, notes: null },
|
||||
Leche: { name: 'Leche', amount: null, unit: null, notes: null },
|
||||
Café: { name: 'Café', amount: null, unit: null, notes: null },
|
||||
}
|
||||
|
||||
describe('dictation few-shot examples', () => {
|
||||
|
||||
20
apps/web/src/lib/platform.ts
Normal file
20
apps/web/src/lib/platform.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/** iOS or iPadOS (which reports a desktop Mac user agent). */
|
||||
export function isIos() {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
|
||||
return (
|
||||
/iphone|ipad|ipod/i.test(navigator.userAgent) ||
|
||||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
|
||||
)
|
||||
}
|
||||
|
||||
/** The app is running as an installed PWA instead of in a browser tab. */
|
||||
export 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
|
||||
)
|
||||
}
|
||||
@@ -32,3 +32,16 @@ export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
export function isIosStandalone(): boolean {
|
||||
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this browser can dictate a phrase without asking for the microphone first
|
||||
* (the input's microphone). An iOS home-screen app exposes `webkitSpeechRecognition`
|
||||
* but that flow does not work there, so it counts as unsupported (the keyboard's own
|
||||
* dictation still works). Dictating several items does work there, because it asks
|
||||
* for the microphone with `getUserMedia` first, so it checks `getSpeechRecognition()`.
|
||||
*/
|
||||
export function canDictate(): boolean {
|
||||
if (typeof window === 'undefined' || isIosStandalone()) return false
|
||||
|
||||
return getSpeechRecognition() !== null
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { FingerprintIcon } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
@@ -10,7 +11,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { signIn } from '@/lib/auth-client'
|
||||
import { authClient, signIn } from '@/lib/auth-client'
|
||||
|
||||
export const Route = createFileRoute('/(auth)/sign-in')({
|
||||
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
||||
@@ -26,16 +27,69 @@ const signInSchema = z.object({
|
||||
|
||||
type SignInValues = z.infer<typeof signInSchema>
|
||||
|
||||
const PASSKEY_ERROR_MESSAGE = 'No pudimos iniciar tu sesión con passkey.'
|
||||
|
||||
/** The user dismissed the system sheet: not worth showing an error for. */
|
||||
function isPasskeyCancellation(error: unknown) {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
error.code === 'AUTH_CANCELLED'
|
||||
)
|
||||
}
|
||||
|
||||
function SignInPage() {
|
||||
const navigate = useNavigate()
|
||||
const { redirect } = Route.useSearch()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [passkeyPending, setPasskeyPending] = useState(false)
|
||||
const conditionalUiStarted = useRef(false)
|
||||
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
||||
|
||||
const form = useForm<SignInValues>({
|
||||
resolver: zodResolver(signInSchema),
|
||||
defaultValues: { email: '', password: '' },
|
||||
})
|
||||
|
||||
const completeSignIn = useCallback(async () => {
|
||||
if (redirect) {
|
||||
window.location.assign(redirect)
|
||||
return
|
||||
}
|
||||
|
||||
await navigate({ to: '/' })
|
||||
}, [navigate, redirect])
|
||||
|
||||
// Conditional UI: the browser offers the user's passkeys in the email field's
|
||||
// autofill. Guarded with a ref because StrictMode mounts effects twice in dev
|
||||
// and a second ceremony would abort the first one.
|
||||
useEffect(() => {
|
||||
if (conditionalUiStarted.current || !supportsPasskeys) return
|
||||
if (typeof window.PublicKeyCredential.isConditionalMediationAvailable !== 'function') return
|
||||
|
||||
conditionalUiStarted.current = true
|
||||
|
||||
void (async () => {
|
||||
if (!(await window.PublicKeyCredential.isConditionalMediationAvailable())) return
|
||||
|
||||
try {
|
||||
const { error: passkeyError } = await authClient.signIn.passkey({ autoFill: true })
|
||||
|
||||
if (passkeyError) {
|
||||
if (!isPasskeyCancellation(passkeyError)) {
|
||||
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
await completeSignIn()
|
||||
} catch {
|
||||
setError(PASSKEY_ERROR_MESSAGE)
|
||||
}
|
||||
})()
|
||||
}, [completeSignIn, supportsPasskeys])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setError(null)
|
||||
|
||||
@@ -46,13 +100,30 @@ function SignInPage() {
|
||||
return
|
||||
}
|
||||
|
||||
if (redirect) {
|
||||
window.location.assign(redirect)
|
||||
await completeSignIn()
|
||||
})
|
||||
|
||||
const onPasskeySignIn = async () => {
|
||||
setError(null)
|
||||
setPasskeyPending(true)
|
||||
|
||||
try {
|
||||
const { error: passkeyError } = await authClient.signIn.passkey()
|
||||
|
||||
if (passkeyError) {
|
||||
if (!isPasskeyCancellation(passkeyError)) {
|
||||
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
await navigate({ to: '/' })
|
||||
})
|
||||
await completeSignIn()
|
||||
} catch {
|
||||
setError(PASSKEY_ERROR_MESSAGE)
|
||||
} finally {
|
||||
setPasskeyPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
@@ -77,7 +148,9 @@ function SignInPage() {
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
// `webauthn` lets the browser offer passkeys in autofill
|
||||
// (conditional UI); `username` is what login forms use.
|
||||
autoComplete="username webauthn"
|
||||
placeholder="ada@ejemplo.com"
|
||||
{...form.register('email')}
|
||||
/>
|
||||
@@ -107,11 +180,31 @@ function SignInPage() {
|
||||
<FieldError errors={[form.formState.errors.password]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting || passkeyPending}>
|
||||
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
{supportsPasskeys && (
|
||||
<>
|
||||
<div className="flex items-center gap-3" aria-hidden>
|
||||
<span className="bg-border h-px flex-1" />
|
||||
<span className="text-muted-foreground text-xs uppercase">o</span>
|
||||
<span className="bg-border h-px flex-1" />
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onPasskeySignIn}
|
||||
disabled={passkeyPending || form.formState.isSubmitting}
|
||||
>
|
||||
<FingerprintIcon />
|
||||
{passkeyPending ? 'Esperando a tu passkey…' : 'Entrar con passkey'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="text-muted-foreground text-center text-sm">
|
||||
¿Todavía no tienes cuenta?{' '}
|
||||
<Link
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { ListPreferencesCard } from '@/components/lists/list-preferences-card'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -77,6 +78,8 @@ function ListSettingsPage() {
|
||||
|
||||
{!list.isPrimary && <SetPrimaryButton listId={list.id} />}
|
||||
|
||||
<ListPreferencesCard list={list} />
|
||||
|
||||
{list.role === 'owner' && <RenameListCard list={list} />}
|
||||
|
||||
{list.role === 'owner' && <InviteCollaboratorCard listId={list.id} />}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
|
||||
import type { CSSProperties } from 'react'
|
||||
import { AppBadge } from '@/components/app-badge'
|
||||
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 { usePinnedLists } from '@/hooks/use-lists'
|
||||
import { authClient, useSession } from '@/lib/auth-client'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
@@ -35,12 +38,26 @@ function AuthenticatedLayout() {
|
||||
return <SessionLoading />
|
||||
}
|
||||
|
||||
return <AuthenticatedShell />
|
||||
}
|
||||
|
||||
/** Split from the layout so the lists query only runs once the session is known. */
|
||||
function AuthenticatedShell() {
|
||||
// Height of the mobile bottom navigation, which grows by the pinned lists bar.
|
||||
// Everything placed above it (page padding, install prompt, dictation button)
|
||||
// reads this variable instead of a fixed offset.
|
||||
const hasPinnedLists = usePinnedLists().length > 0
|
||||
const shellStyle = {
|
||||
'--bottom-nav-height': hasPinnedLists ? '9rem' : '4.5rem',
|
||||
} as CSSProperties
|
||||
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<SidebarProvider style={shellStyle}>
|
||||
<AppBadge />
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<AppHeader />
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pb-[calc(5rem+env(safe-area-inset-bottom))] md:gap-6 md:p-6 md:pb-6">
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pb-[calc(var(--bottom-nav-height)+0.5rem+env(safe-area-inset-bottom))] md:gap-6 md:p-6 md:pb-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
<BottomNav />
|
||||
|
||||
@@ -4,6 +4,8 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
import { AppBadgeCard } from '@/components/settings/app-badge-card'
|
||||
import { PasskeysCard } from '@/components/settings/passkeys-card'
|
||||
import { type Theme, useTheme } from '@/components/theme-provider'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -22,6 +24,8 @@ function SettingsPage() {
|
||||
return (
|
||||
<div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
|
||||
<ProfileCard />
|
||||
<PasskeysCard />
|
||||
<AppBadgeCard />
|
||||
<AppearanceCard />
|
||||
|
||||
<Card>
|
||||
|
||||
179
bun.lock
179
bun.lock
@@ -14,15 +14,21 @@
|
||||
"name": "@superlist/api",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@logtape/logtape": "^2.4.2",
|
||||
"@logtape/otel": "^2.4.2",
|
||||
"@logtape/pretty": "^2.4.2",
|
||||
"@opentelemetry/api": "1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "0.208.0",
|
||||
"@opentelemetry/resources": "2.2.0",
|
||||
"@opentelemetry/sdk-metrics": "2.2.0",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@superlist/shared": "workspace:*",
|
||||
"better-auth": "^1.7.7",
|
||||
"hono": "^4.13.13",
|
||||
"pg": "^8.23.1",
|
||||
"pino": "^10.4.0",
|
||||
"pino-pretty": "^13.2.0",
|
||||
"resend": "^6.32.1",
|
||||
"zod": "^4.6.7",
|
||||
},
|
||||
@@ -38,6 +44,7 @@
|
||||
"name": "@superlist/web",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@hookform/resolvers": "^5.9.1",
|
||||
"@superlist/shared": "workspace:*",
|
||||
@@ -292,6 +299,8 @@
|
||||
|
||||
"@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],
|
||||
|
||||
"@better-auth/passkey": ["@better-auth/passkey@1.7.7", "", { "dependencies": { "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.1", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "better-auth": "^1.7.7", "better-call": "1.4.0", "nanostores": "^1.0.1" } }, "sha512-FMhL3bspBxne8EcyPWx9LdWUCnmrNRoSxCnH9Q2FIWsSWXMYuPPcHOs07v4g0zUXmTlBSr4vwW3J6t2vdUIOlg=="],
|
||||
|
||||
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],
|
||||
|
||||
"@better-auth/telemetry": ["@better-auth/telemetry@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],
|
||||
@@ -340,6 +349,12 @@
|
||||
|
||||
"@fontsource-variable/geist": ["@fontsource-variable/geist@5.3.0", "", {}, "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA=="],
|
||||
|
||||
"@grpc/grpc-js": ["@grpc/grpc-js@1.14.7", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ=="],
|
||||
|
||||
"@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
|
||||
|
||||
"@hexagon/base64": ["@hexagon/base64@1.1.28", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="],
|
||||
|
||||
"@hono/node-server": ["@hono/node-server@1.19.9", "", { "peerDependencies": { "hono": "^4" } }, "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw=="],
|
||||
|
||||
"@hono/zod-validator": ["@hono/zod-validator@0.9.1", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="],
|
||||
@@ -362,10 +377,20 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
|
||||
|
||||
"@kobalte/core": ["@kobalte/core@0.13.14", "", { "dependencies": { "@floating-ui/dom": "^1.5.1", "@internationalized/number": "^3.2.1", "@kobalte/utils": "^0.9.2", "@solid-primitives/props": "^3.1.8", "@solid-primitives/resize-observer": "^2.0.26", "solid-presence": "^0.2.0", "solid-prevent-scroll": "^0.1.11" }, "peerDependencies": { "solid-js": "^1.9.8" } }, "sha512-SBVB1lnvYbYt2x3t7fG0lo5fGLEbHQ6PII3NDPva8vD5e2v53On84ZVQiuIk0XI/55R4GQhden7Yem+R/XR8uQ=="],
|
||||
|
||||
"@kobalte/utils": ["@kobalte/utils@0.9.2", "", { "dependencies": { "@solid-primitives/event-listener": "^2.2.14", "@solid-primitives/keyed": "^1.2.0", "@solid-primitives/map": "^0.4.7", "@solid-primitives/media": "^2.2.4", "@solid-primitives/props": "^3.1.8", "@solid-primitives/refs": "^1.0.5", "@solid-primitives/utils": "^6.2.1" }, "peerDependencies": { "solid-js": "^1.8.8" } }, "sha512-jRVXr+zsVHxzDXRoh+CDeXzvCsFJ6uiHhqqNQ26Cw9ZsZ3D6nqPUBt1gGVtj2ZPmRL3a9Uk1v8D1aJ8/I12Dow=="],
|
||||
|
||||
"@levischuck/tiny-cbor": ["@levischuck/tiny-cbor@0.2.11", "", {}, "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow=="],
|
||||
|
||||
"@logtape/logtape": ["@logtape/logtape@2.4.2", "", {}, "sha512-YJyC1gEMgWmTqJTRtKkjgasEbi8/0gP7Dj8n6bL46gQIAhpTY8uXJ+1QYMOgF5asotlGMvy3G7ejXUe45Yd1MQ=="],
|
||||
|
||||
"@logtape/otel": ["@logtape/otel@2.4.2", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/api-logs": "^0.208.0", "@opentelemetry/exporter-logs-otlp-grpc": "^0.208.0", "@opentelemetry/exporter-logs-otlp-http": "^0.208.0", "@opentelemetry/exporter-logs-otlp-proto": "^0.208.0", "@opentelemetry/otlp-exporter-base": "^0.208.0", "@opentelemetry/resources": "^2.2.0", "@opentelemetry/sdk-logs": "^0.208.0", "@opentelemetry/semantic-conventions": "^1.38.0" }, "peerDependencies": { "@logtape/logtape": "^2.4.2" } }, "sha512-65xTJ1MdaUmegfqVEUil2btaMv//gqe4v2Nxip1Zh2kuC20jMcJYoxVZZqIJzkZpwzwzUFBFvj4/j1TNaQE/4A=="],
|
||||
|
||||
"@logtape/pretty": ["@logtape/pretty@2.4.2", "", { "peerDependencies": { "@logtape/logtape": "^2.4.2" } }, "sha512-WcsJYsBwjL2DypJO4vJSZ7MAgbbEIm7//JE1G61kCV7ttiPqiX+5e+IB4h01bBdTE8FH2IkEIC4dMss7SwHPTg=="],
|
||||
|
||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="],
|
||||
|
||||
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
|
||||
@@ -380,11 +405,63 @@
|
||||
|
||||
"@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
|
||||
|
||||
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
|
||||
|
||||
"@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.208.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg=="],
|
||||
|
||||
"@opentelemetry/core": ["@opentelemetry/core@2.2.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw=="],
|
||||
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/exporter-logs-otlp-grpc@0.208.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-grpc-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0", "@opentelemetry/sdk-logs": "0.208.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-AmZDKFzbq/idME/yq68M155CJW1y056MNBekH9OZewiZKaqgwYN4VYfn3mXVPftYsfrCM2r4V6tS8H2LmfiDCg=="],
|
||||
|
||||
"@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.208.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.208.0", "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0", "@opentelemetry/sdk-logs": "0.208.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg=="],
|
||||
|
||||
"@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.208.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.208.0", "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0", "@opentelemetry/resources": "2.2.0", "@opentelemetry/sdk-logs": "0.208.0", "@opentelemetry/sdk-trace-base": "2.2.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Wy8dZm16AOfM7yddEzSFzutHZDZ6HspKUODSUJVjyhnZFMBojWDjSNgduyCMlw6qaxJYz0dlb0OEcb4Eme+BfQ=="],
|
||||
|
||||
"@opentelemetry/exporter-metrics-otlp-http": ["@opentelemetry/exporter-metrics-otlp-http@0.208.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0", "@opentelemetry/resources": "2.2.0", "@opentelemetry/sdk-metrics": "2.2.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-QZ3TrI90Y0i1ezWQdvreryjY0a5TK4J9gyDLIyhLBwV+EQUvyp5wR7TFPKCAexD4TDSWM0t3ulQDbYYjVtzTyA=="],
|
||||
|
||||
"@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.208.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-transformer": "0.208.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-gMd39gIfVb2OgxldxUtOwGJYSH8P1kVFFlJLuut32L6KgUC4gl1dMhn+YC2mGn0bDOiQYSk/uHOdSjuKp58vvA=="],
|
||||
|
||||
"@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/otlp-grpc-exporter-base@0.208.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-fGvAg3zb8fC0oJAzfz7PQppADI2HYB7TSt/XoCaBJFi1mSquNUjtHXEoviMgObLAa1NRIgOC1lsV1OUKi+9+lQ=="],
|
||||
|
||||
"@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.208.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.208.0", "@opentelemetry/core": "2.2.0", "@opentelemetry/resources": "2.2.0", "@opentelemetry/sdk-logs": "0.208.0", "@opentelemetry/sdk-metrics": "2.2.0", "@opentelemetry/sdk-trace-base": "2.2.0", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-DCFPY8C6lAQHUNkzcNT9R+qYExvsk6C5Bto2pbNxgicpcSWbe2WHShLxkOxIdNcBiYPdVHv/e7vH7K6TI+C+fQ=="],
|
||||
|
||||
"@opentelemetry/resources": ["@opentelemetry/resources@2.2.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A=="],
|
||||
|
||||
"@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.208.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.208.0", "@opentelemetry/core": "2.2.0", "@opentelemetry/resources": "2.2.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-QlAyL1jRpOeaqx7/leG1vJMp84g0xKP6gJmfELBpnI4O/9xPX+Hu5m1POk9Kl+veNkyth5t19hRlN6tNY1sjbA=="],
|
||||
|
||||
"@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.2.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/resources": "2.2.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-G5KYP6+VJMZzpGipQw7Giif48h6SGQ2PFKEYCybeXJsOCB4fp8azqMAAzE5lnnHK3ZVwYQrgmFbsUJO/zOnwGw=="],
|
||||
|
||||
"@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.2.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/resources": "2.2.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw=="],
|
||||
|
||||
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
|
||||
|
||||
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
|
||||
|
||||
"@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
|
||||
"@peculiar/asn1-android": ["@peculiar/asn1-android@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-AuUBRDNdWrgtnuJGXARa0Xdtq6OAD8GqezDQz6Qka7kyynMo9fzkcrtpBEHuX984uEB570BrhMZfJfkUDfpQfw=="],
|
||||
|
||||
"@peculiar/asn1-cms": ["@peculiar/asn1-cms@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-Bk+oatE62dW0Tzzpfk6vdQxfGGEfvuGdWgmijnKjcv7HqZCJISs85z4zw2uDArrk+R1Oel1wts/BBl7HHrtAcA=="],
|
||||
|
||||
"@peculiar/asn1-csr": ["@peculiar/asn1-csr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-KVfbXaKng8886/tOPG55t5K1XkTkGbR4amjIJzytXWobFU5nZgw/sKnSpa1hxP17nUSsrOF/7Mt9WUYeyLsi6Q=="],
|
||||
|
||||
"@peculiar/asn1-ecc": ["@peculiar/asn1-ecc@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-7MSNji77fQa/oN3WAfwagMy8EoJFg50sW4hZ1dtr0zU1BSugit0I2DGpIdPhvkNplopQhz5bogxpn1077eaamA=="],
|
||||
|
||||
"@peculiar/asn1-pfx": ["@peculiar/asn1-pfx@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-rsa": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-2SN2z8qkc2hk/GgTYA8RN54wtsCDZShg9gI2Mq1vLhdj1adcv5fhTbiEmExZUaAMqlizxiEpULQDfHM5iYtn1g=="],
|
||||
|
||||
"@peculiar/asn1-pkcs8": ["@peculiar/asn1-pkcs8@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-HqsSrnpQghRp9SM9QSmR6fa4z/BNktnKq7928+oq4qF0VAnuHZ4cyePKvcxh9fP4taBCP/WHNItlVNsYaQm2qw=="],
|
||||
|
||||
"@peculiar/asn1-pkcs9": ["@peculiar/asn1-pkcs9@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pfx": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-OHFkTg8D2zYafILqFE4KPbqX8srpvd3diGDc2h2cduumawc765mOHGcuFMGvLWlL2bbCMWMmMSCtlXptsOuiPA=="],
|
||||
|
||||
"@peculiar/asn1-rsa": ["@peculiar/asn1-rsa@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-6KwKGjulF489CpidZqkogNgLj6oGzgC4BL2FClM8PuJQ4t5NqT4q4a6A4vrSxBIBhMnL8hGYkLOpbVw0Vq38Tw=="],
|
||||
|
||||
"@peculiar/asn1-schema": ["@peculiar/asn1-schema@2.11.1", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g=="],
|
||||
|
||||
"@peculiar/asn1-x509": ["@peculiar/asn1-x509@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA=="],
|
||||
|
||||
"@peculiar/asn1-x509-attr": ["@peculiar/asn1-x509-attr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-n7RKFrbTzt8pGBlZ90kmKEn1qsLTTyw7lrvHMK0xsA42kQugPk/GXYpNbEcl7DkkdVsU/one5UX7KQPfxLj8vQ=="],
|
||||
|
||||
"@peculiar/utils": ["@peculiar/utils@2.0.3", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="],
|
||||
|
||||
"@peculiar/x509": ["@peculiar/x509@1.14.3", "", { "dependencies": { "@peculiar/asn1-cms": "^2.6.0", "@peculiar/asn1-csr": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.0", "@peculiar/asn1-pkcs9": "^2.6.0", "@peculiar/asn1-rsa": "^2.6.0", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.0", "pvtsutils": "^1.3.6", "reflect-metadata": "^0.2.2", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA=="],
|
||||
|
||||
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
|
||||
|
||||
@@ -414,6 +491,24 @@
|
||||
|
||||
"@prisma/studio-core": ["@prisma/studio-core@0.33.0", "", { "dependencies": { "@radix-ui/react-toggle": "1.1.10", "@visx/curve": "4.0.1-alpha.0", "@visx/event": "4.0.1-alpha.0", "@visx/grid": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/responsive": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/shape": "4.0.1-alpha.0", "d3-array": "3.2.4", "d3-shape": "3.2.0", "elkjs": "0.11.1" }, "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-V2fX/nKEymNTrHXwfP26PGjoLStO35Ogu+ex7CFJbLrMYEcZxxZpiSNOs7px23Hk5mzLWvM5RsqG6Ka+rha+wg=="],
|
||||
|
||||
"@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
|
||||
|
||||
"@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
|
||||
|
||||
"@protobufjs/codegen": ["@protobufjs/codegen@2.0.5", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],
|
||||
|
||||
"@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.1", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],
|
||||
|
||||
"@protobufjs/fetch": ["@protobufjs/fetch@1.1.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],
|
||||
|
||||
"@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
|
||||
|
||||
"@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
|
||||
|
||||
"@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
|
||||
|
||||
"@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],
|
||||
|
||||
"@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="],
|
||||
|
||||
"@radix-ui/primitive": ["@radix-ui/primitive@1.2.0", "", {}, "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw=="],
|
||||
@@ -632,6 +727,10 @@
|
||||
|
||||
"@shadcn/registry": ["@shadcn/registry@0.1.3", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "cn": "^0.2.4", "code-block-writer": "^13.0.3", "deepmerge": "^4.3.1", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "ora": "^8.2.0", "postcss": "^8.5.23", "prompts": "^2.4.2", "recast": "^0.23.11", "socks": "^2.8.8", "stringify-object": "^5.0.0", "tsconfig-paths": "^4.2.0", "type-fest": "^4.41.0", "undici": "^7.29.0", "zod": "^3.24.1" } }, "sha512-82/OmKAVM9pChDHFVAsDP9PcimPGSKZGdbcdwdGGGcSI69ImpN4ZnqsfZ4hkOFEMal92t3y9djYJHMjO4PcVZA=="],
|
||||
|
||||
"@simplewebauthn/browser": ["@simplewebauthn/browser@13.3.0", "", {}, "sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ=="],
|
||||
|
||||
"@simplewebauthn/server": ["@simplewebauthn/server@13.3.3", "", { "dependencies": { "@hexagon/base64": "^1.1.27", "@levischuck/tiny-cbor": "^0.2.2", "@peculiar/asn1-android": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.1", "@peculiar/asn1-rsa": "^2.6.1", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.1", "@peculiar/x509": "^1.14.3" } }, "sha512-LelX/lcy5cjc15A86i/aNxHhB5eU7dd20QsbP0VLAf9e38+SLlsnqCCyecx3xqfGofhmX05h1J9fKRYWxw+luA=="],
|
||||
|
||||
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
|
||||
|
||||
"@solid-primitives/event-listener": ["@solid-primitives/event-listener@2.4.6", "", { "dependencies": { "@solid-primitives/utils": "^6.4.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-5I0YJcTVYIWoMmgBSROBZGcz+ymhew/pGTg2dHW74BUjFKsV8Li4bOZYl0YAGP4mHw5o4UBd9/BEesqBci3wxw=="],
|
||||
@@ -854,6 +953,8 @@
|
||||
|
||||
"arraybuffer.prototype.slice": ["arraybuffer.prototype.slice@1.0.4", "", { "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "is-array-buffer": "^3.0.4" } }, "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ=="],
|
||||
|
||||
"asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="],
|
||||
|
||||
"assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
|
||||
|
||||
"ast-types": ["ast-types@0.16.3", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA=="],
|
||||
@@ -864,8 +965,6 @@
|
||||
|
||||
"at-least-node": ["at-least-node@1.0.0", "", {}, "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg=="],
|
||||
|
||||
"atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="],
|
||||
|
||||
"atomically": ["atomically@1.7.0", "", {}, "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w=="],
|
||||
|
||||
"available-typed-arrays": ["available-typed-arrays@1.0.7", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],
|
||||
@@ -942,8 +1041,6 @@
|
||||
|
||||
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
|
||||
|
||||
"colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="],
|
||||
|
||||
"commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],
|
||||
|
||||
"common-tags": ["common-tags@1.8.2", "", {}, "sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA=="],
|
||||
@@ -1010,8 +1107,6 @@
|
||||
|
||||
"data-view-byte-offset": ["data-view-byte-offset@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-data-view": "^1.0.1" } }, "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ=="],
|
||||
|
||||
"dateformat": ["dateformat@4.6.3", "", {}, "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA=="],
|
||||
|
||||
"debounce-fn": ["debounce-fn@4.0.0", "", { "dependencies": { "mimic-fn": "^3.0.0" } }, "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
@@ -1072,8 +1167,6 @@
|
||||
|
||||
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
|
||||
|
||||
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.26.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="],
|
||||
|
||||
"enquirer": ["enquirer@2.4.1", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
|
||||
@@ -1130,8 +1223,6 @@
|
||||
|
||||
"fast-check": ["fast-check@3.23.2", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||
|
||||
"fast-copy": ["fast-copy@4.1.2", "", {}, "sha512-DUHggaYcouhy5I1LacDJ+JDSqGlumVJP2EAi5Nwt1pWPeLpSvIjkrY+x4fsoI1/+GlTyq+DM9zdgWCFSfqNODA=="],
|
||||
|
||||
"fast-decode-uri-component": ["fast-decode-uri-component@1.0.1", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="],
|
||||
|
||||
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
|
||||
@@ -1142,8 +1233,6 @@
|
||||
|
||||
"fast-querystring": ["fast-querystring@1.1.2", "", { "dependencies": { "fast-decode-uri-component": "^1.0.1" } }, "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg=="],
|
||||
|
||||
"fast-safe-stringify": ["fast-safe-stringify@2.1.1", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="],
|
||||
|
||||
"fast-sha256": ["fast-sha256@1.3.0", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],
|
||||
|
||||
"fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],
|
||||
@@ -1240,8 +1329,6 @@
|
||||
|
||||
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
|
||||
|
||||
"help-me": ["help-me@5.0.0", "", {}, "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="],
|
||||
|
||||
"hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="],
|
||||
|
||||
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
|
||||
@@ -1360,8 +1447,6 @@
|
||||
|
||||
"jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
|
||||
|
||||
"joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="],
|
||||
|
||||
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||
@@ -1410,6 +1495,8 @@
|
||||
|
||||
"lodash": ["lodash@4.17.21", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
|
||||
|
||||
"lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
|
||||
|
||||
"lodash.debounce": ["lodash.debounce@4.0.8", "", {}, "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow=="],
|
||||
|
||||
"log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="],
|
||||
@@ -1480,8 +1567,6 @@
|
||||
|
||||
"ohash": ["ohash@2.0.12", "", {}, "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw=="],
|
||||
|
||||
"on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="],
|
||||
|
||||
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
|
||||
|
||||
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
@@ -1542,14 +1627,6 @@
|
||||
|
||||
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
|
||||
|
||||
"pino": ["pino@10.4.0", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^3.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^1.0.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^4.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA=="],
|
||||
|
||||
"pino-abstract-transport": ["pino-abstract-transport@3.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg=="],
|
||||
|
||||
"pino-pretty": ["pino-pretty@13.2.0", "", { "dependencies": { "colorette": "^2.0.7", "dateformat": "^4.6.3", "fast-copy": "^4.0.0", "fast-safe-stringify": "^2.1.1", "help-me": "^5.0.0", "joycon": "^3.1.1", "minimist": "^1.2.6", "on-exit-leak-free": "^2.1.2", "pino-abstract-transport": "^3.0.0", "pump": "^3.0.3", "secure-json-parse": "^4.1.0", "sonic-boom": "^5.0.0", "strip-json-comments": "^5.0.3" }, "bin": { "pino-pretty": "bin.js" } }, "sha512-jjghD1ML+Di/WxjJDz6j6Y4FT7hIXOlb8h27AyJ+ohtAXJXH4PS/xkv7si+RCCIW59HMgZsMKTDgzdr0RhuRrg=="],
|
||||
|
||||
"pino-std-serializers": ["pino-std-serializers@7.1.0", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="],
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"pkg-types": ["pkg-types@2.3.3", "", { "dependencies": { "confbox": "^0.3.1", "exsolve": "^1.1.1", "pathe": "^2.0.3" } }, "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w=="],
|
||||
@@ -1584,24 +1661,24 @@
|
||||
|
||||
"prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="],
|
||||
|
||||
"process-warning": ["process-warning@5.1.1", "", {}, "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg=="],
|
||||
|
||||
"prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],
|
||||
|
||||
"proper-lockfile": ["proper-lockfile@4.1.2", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="],
|
||||
|
||||
"protobufjs": ["protobufjs@7.6.6", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg=="],
|
||||
|
||||
"proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="],
|
||||
|
||||
"pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
|
||||
|
||||
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||
|
||||
"pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="],
|
||||
|
||||
"pvutils": ["pvutils@1.2.0", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="],
|
||||
|
||||
"qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="],
|
||||
|
||||
"radix-ui": ["radix-ui@1.8.0", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-accessible-icon": "1.2.0", "@radix-ui/react-accordion": "1.3.0", "@radix-ui/react-alert-dialog": "1.2.0", "@radix-ui/react-arrow": "1.1.17", "@radix-ui/react-aspect-ratio": "1.2.0", "@radix-ui/react-avatar": "1.3.0", "@radix-ui/react-checkbox": "1.4.0", "@radix-ui/react-collapsible": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-context-menu": "2.4.0", "@radix-ui/react-dialog": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-dismissable-layer": "1.2.0", "@radix-ui/react-dropdown-menu": "2.2.0", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.0", "@radix-ui/react-form": "0.3.0", "@radix-ui/react-hover-card": "1.2.0", "@radix-ui/react-label": "2.1.17", "@radix-ui/react-menu": "2.2.0", "@radix-ui/react-menubar": "1.2.0", "@radix-ui/react-navigation-menu": "1.4.0", "@radix-ui/react-one-time-password-field": "0.2.0", "@radix-ui/react-password-toggle-field": "0.2.0", "@radix-ui/react-popover": "1.3.0", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-progress": "1.2.0", "@radix-ui/react-radio-group": "1.5.0", "@radix-ui/react-roving-focus": "1.2.0", "@radix-ui/react-scroll-area": "1.4.0", "@radix-ui/react-select": "2.4.0", "@radix-ui/react-separator": "1.2.0", "@radix-ui/react-slider": "1.6.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-switch": "1.4.0", "@radix-ui/react-tabs": "1.2.0", "@radix-ui/react-toast": "1.3.0", "@radix-ui/react-toggle": "1.2.0", "@radix-ui/react-toggle-group": "1.2.0", "@radix-ui/react-toolbar": "1.2.0", "@radix-ui/react-tooltip": "1.4.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-escape-keydown": "1.1.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.5", "@radix-ui/react-visually-hidden": "1.2.13" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-d2p7l6XzZ9agJABImQYTFSbALCqaieTEXs2TmVNpT4cFam6RD91rsucu0VhMs45Oe35rQVWJk8PoDej0z/w3yg=="],
|
||||
|
||||
"range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="],
|
||||
@@ -1628,8 +1705,6 @@
|
||||
|
||||
"readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="],
|
||||
|
||||
"real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="],
|
||||
|
||||
"recast": ["recast@0.23.21", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw=="],
|
||||
|
||||
"recharts": ["recharts@3.10.1", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^11.1.8", "react-redux": "8.x.x || 9.x.x", "reselect": "5.2.0", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA=="],
|
||||
@@ -1638,6 +1713,8 @@
|
||||
|
||||
"redux-thunk": ["redux-thunk@3.1.0", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
|
||||
|
||||
"reflect-metadata": ["reflect-metadata@0.2.2", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
|
||||
|
||||
"reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
|
||||
|
||||
"regenerate": ["regenerate@1.5.0", "", {}, "sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw=="],
|
||||
@@ -1696,14 +1773,10 @@
|
||||
|
||||
"safe-regex2": ["safe-regex2@5.1.2", "", { "dependencies": { "ret": "~0.5.0" }, "bin": { "safe-regex2": "bin/safe-regex2.js" } }, "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw=="],
|
||||
|
||||
"safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="],
|
||||
|
||||
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
|
||||
|
||||
"scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],
|
||||
|
||||
"secure-json-parse": ["secure-json-parse@4.1.1", "", {}, "sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw=="],
|
||||
|
||||
"semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
|
||||
@@ -1760,8 +1833,6 @@
|
||||
|
||||
"solid-transition-group": ["solid-transition-group@0.2.3", "", { "dependencies": { "@solid-primitives/refs": "^1.0.5", "@solid-primitives/transition-group": "^1.0.2" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-iB72c9N5Kz9ykRqIXl0lQohOau4t0dhel9kjwFvx81UZJbVwaChMuBuyhiZmK24b8aKEK0w3uFM96ZxzcyZGdg=="],
|
||||
|
||||
"sonic-boom": ["sonic-boom@4.2.1", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="],
|
||||
|
||||
"sonner": ["sonner@2.0.8", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-UM/ByIoFra8yzV75n1o0Puu0bw5U/9UNnDacrJNspekBewIfsQ3D6ez1nvlWpt7aTsO6rujQtifBpycwIivqlg=="],
|
||||
|
||||
"source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
@@ -1804,8 +1875,6 @@
|
||||
|
||||
"strip-final-newline": ["strip-final-newline@4.0.0", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="],
|
||||
|
||||
"strip-json-comments": ["strip-json-comments@5.0.3", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="],
|
||||
|
||||
"superjson": ["superjson@2.2.6", "", { "dependencies": { "copy-anything": "^4" } }, "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA=="],
|
||||
|
||||
"supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
|
||||
@@ -1824,8 +1893,6 @@
|
||||
|
||||
"terser": ["terser@5.51.2", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q=="],
|
||||
|
||||
"thread-stream": ["thread-stream@4.2.0", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ=="],
|
||||
|
||||
"tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tinybench": ["tinybench@6.2.2", "", {}, "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA=="],
|
||||
@@ -1844,6 +1911,8 @@
|
||||
|
||||
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"tsyringe": ["tsyringe@4.10.0", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="],
|
||||
|
||||
"turbo": ["turbo@2.11.7", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.7", "@turbo/darwin-arm64": "2.11.7", "@turbo/linux-64": "2.11.7", "@turbo/linux-arm64": "2.11.7", "@turbo/windows-64": "2.11.7", "@turbo/windows-arm64": "2.11.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RhXHbqfvY6o3xt/zSHCwSNwLrZlXiqHzewi4eAj9PtZ1T1CqgMJ2yIDb7SKPTG9IikTm925mfzL6hldQVdyNWw=="],
|
||||
|
||||
"tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
|
||||
@@ -1992,6 +2061,12 @@
|
||||
|
||||
"@dotenvx/dotenvx/open": ["open@8.4.2", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="],
|
||||
|
||||
"@logtape/otel/@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="],
|
||||
|
||||
"@logtape/otel/@opentelemetry/resources": ["@opentelemetry/resources@2.12.0", "", { "dependencies": { "@opentelemetry/core": "2.12.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A=="],
|
||||
|
||||
"@opentelemetry/api-logs/@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="],
|
||||
|
||||
"@prisma/dev/std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
|
||||
|
||||
"@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.10.0", "", { "dependencies": { "@prisma/debug": "7.10.0" } }, "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w=="],
|
||||
@@ -2096,14 +2171,14 @@
|
||||
|
||||
"pg-types/postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
|
||||
|
||||
"pino-pretty/sonic-boom": ["sonic-boom@5.0.2", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-/JEruzo6yhNVhsLblTRchgTQHIt7SsdJP0YyrfWaNKjIOQDfrdZv9gwYraYCAsmKV39/LAdV31FLL5NCDpoL/A=="],
|
||||
|
||||
"pkg-types/confbox": ["confbox@0.3.1", "", {}, "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA=="],
|
||||
|
||||
"prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
|
||||
|
||||
"proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
|
||||
|
||||
"protobufjs/@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="],
|
||||
|
||||
"restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
|
||||
|
||||
"shadcn/cn": ["cn@0.2.6", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ=="],
|
||||
@@ -2118,6 +2193,8 @@
|
||||
|
||||
"terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],
|
||||
|
||||
"tsyringe/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
|
||||
|
||||
"type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
|
||||
|
||||
"workbox-build/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="],
|
||||
@@ -2146,6 +2223,8 @@
|
||||
|
||||
"@dotenvx/dotenvx/open/define-lazy-prop": ["define-lazy-prop@2.0.0", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="],
|
||||
|
||||
"@logtape/otel/@opentelemetry/resources/@opentelemetry/core": ["@opentelemetry/core@2.12.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ=="],
|
||||
|
||||
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
||||
|
||||
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
@@ -2190,6 +2269,8 @@
|
||||
|
||||
"ora/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
|
||||
|
||||
"protobufjs/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
|
||||
"string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"workbox-build/stringify-object/is-obj": ["is-obj@1.0.1", "", {}, "sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg=="],
|
||||
|
||||
@@ -22,9 +22,20 @@ services:
|
||||
NODE_ENV: ${NODE_ENV:-production}
|
||||
PORT: ${PORT:-4100}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
# Logs to OpenObserve (optional): without OPENOBSERVE_URL they only go to stdout.
|
||||
OPENOBSERVE_URL: ${OPENOBSERVE_URL:-}
|
||||
OPENOBSERVE_ORG: ${OPENOBSERVE_ORG:-default}
|
||||
OPENOBSERVE_STREAM: ${OPENOBSERVE_STREAM:-superlist}
|
||||
OPENOBSERVE_USER: ${OPENOBSERVE_USER:-}
|
||||
OPENOBSERVE_PASSWORD: ${OPENOBSERVE_PASSWORD:-}
|
||||
METRICS_EXPORT_INTERVAL_MS: ${METRICS_EXPORT_INTERVAL_MS:-15000}
|
||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||
MAIL_FROM: ${MAIL_FROM:-}
|
||||
# Dictation (optional): without the key, dictated text is split without AI.
|
||||
# Dictation (optional): Groq when its key is set, else Gemini; without any key,
|
||||
# dictated text is split without AI.
|
||||
GROQ_API_KEY: ${GROQ_API_KEY:-}
|
||||
GROQ_MODEL: ${GROQ_MODEL:-openai/gpt-oss-120b}
|
||||
GROQ_TIMEOUT_MS: ${GROQ_TIMEOUT_MS:-8000}
|
||||
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
|
||||
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
|
||||
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
|
||||
|
||||
555
docs/openobserve-dashboard.json
Normal file
555
docs/openobserve-dashboard.json
Normal file
@@ -0,0 +1,555 @@
|
||||
{
|
||||
"version": 8,
|
||||
"title": "Superlist API",
|
||||
"description": "Métricas HTTP de la API (OTLP) y requests lentos (logs)",
|
||||
"role": "",
|
||||
"owner": "",
|
||||
"created": "1970-01-01T00:00:00Z",
|
||||
"dashboardId": "",
|
||||
"defaultDatetimeDuration": {
|
||||
"type": "relative",
|
||||
"relativeTimePeriod": "1h",
|
||||
"startTime": null,
|
||||
"endTime": null
|
||||
},
|
||||
"variables": {
|
||||
"list": [],
|
||||
"showDynamicFilters": false
|
||||
},
|
||||
"tabs": [
|
||||
{
|
||||
"tabId": "default",
|
||||
"name": "Default",
|
||||
"panels": [
|
||||
{
|
||||
"id": "Panel_rps",
|
||||
"type": "line",
|
||||
"title": "Requests por segundo por ruta",
|
||||
"description": "Sin /api/health",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "default",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "sum by (http_route) (rate(http_server_request_duration_count{service_name=\"superlist-api\", http_route!=\"/api/health\"}[5m]))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_count",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "{http_route}",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 24,
|
||||
"h": 9,
|
||||
"i": 1
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_latency",
|
||||
"type": "line",
|
||||
"title": "Latencia p50 / p95 / p99",
|
||||
"description": "Percentiles interpolados en buckets de 5 ms a 10 s",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "seconds",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_bucket{http_route!=\"/api/health\"}[5m])))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_bucket",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "p50",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"query": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_bucket{http_route!=\"/api/health\"}[5m])))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_bucket",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "p95",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"query": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_bucket{http_route!=\"/api/health\"}[5m])))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_bucket",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "p99",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 24,
|
||||
"y": 0,
|
||||
"w": 24,
|
||||
"h": 9,
|
||||
"i": 2
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_errors",
|
||||
"type": "metric",
|
||||
"title": "Tasa de error 5xx",
|
||||
"description": "Porcentaje de requests con status 5xx (vacío = 0 %)",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "percent",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "0",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "100 * sum(rate(http_server_request_duration_count{http_response_status_code=~\"5..\"}[5m])) / sum(rate(http_server_request_duration_count[5m]))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_count",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "5xx %",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 0,
|
||||
"y": 9,
|
||||
"w": 12,
|
||||
"h": 9,
|
||||
"i": 3
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_active",
|
||||
"type": "metric",
|
||||
"title": "Requests en curso",
|
||||
"description": "SSE no cuenta: responde enseguida",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "default",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "0",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "sum(http_server_active_requests)",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_active_requests",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "en curso",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 12,
|
||||
"y": 9,
|
||||
"w": 12,
|
||||
"h": 9,
|
||||
"i": 4
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_status",
|
||||
"type": "stacked",
|
||||
"title": "Requests por status",
|
||||
"description": "Requests/s por código de respuesta (sin /api/health)",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "default",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "sum by (http_response_status_code) (rate(http_server_request_duration_count{http_route!=\"/api/health\"}[5m]))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_count",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "{http_response_status_code}",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 24,
|
||||
"y": 9,
|
||||
"w": 24,
|
||||
"h": 9,
|
||||
"i": 5
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_p95_route",
|
||||
"type": "line",
|
||||
"title": "p95 por ruta",
|
||||
"description": "Para encontrar el endpoint lento",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "seconds",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_bucket{http_route!=\"/api/health\"}[5m])))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_bucket",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "{http_route}",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 0,
|
||||
"y": 18,
|
||||
"w": 24,
|
||||
"h": 9,
|
||||
"i": 6
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_avg_route",
|
||||
"type": "line",
|
||||
"title": "Latencia media por ruta",
|
||||
"description": "sum / count de la duración",
|
||||
"config": {
|
||||
"show_legends": true,
|
||||
"legends_position": null,
|
||||
"unit": "seconds",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "promql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "sum by (http_route) (rate(http_server_request_duration_sum{http_route!=\"/api/health\"}[5m])) / sum by (http_route) (rate(http_server_request_duration_count{http_route!=\"/api/health\"}[5m]))",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "http_server_request_duration_sum",
|
||||
"stream_type": "metrics",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "{http_route}",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 24,
|
||||
"y": 18,
|
||||
"w": 24,
|
||||
"h": 9,
|
||||
"i": 7
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
},
|
||||
{
|
||||
"id": "Panel_slowest",
|
||||
"type": "table",
|
||||
"title": "Requests más lentos",
|
||||
"description": "Desde los logs: usa requestid en Logs para ver el detalle",
|
||||
"config": {
|
||||
"show_legends": false,
|
||||
"legends_position": null,
|
||||
"unit": "default",
|
||||
"decimals": 2,
|
||||
"axis_border_show": false,
|
||||
"line_thickness": 1.5,
|
||||
"connect_nulls": false,
|
||||
"no_value_replacement": "",
|
||||
"mark_line": [],
|
||||
"override_config": []
|
||||
},
|
||||
"queryType": "sql",
|
||||
"queries": [
|
||||
{
|
||||
"query": "SELECT _timestamp, method, path, status, durationms, requestid FROM \"superlist\" WHERE durationms IS NOT NULL AND path != '/api/health' ORDER BY durationms DESC LIMIT 20",
|
||||
"vrlFunctionQuery": "",
|
||||
"customQuery": true,
|
||||
"joins": [],
|
||||
"fields": {
|
||||
"stream": "superlist",
|
||||
"stream_type": "logs",
|
||||
"x": [],
|
||||
"y": [],
|
||||
"z": [],
|
||||
"breakdown": [],
|
||||
"filter": {
|
||||
"filterType": "group",
|
||||
"logicalOperator": "AND",
|
||||
"conditions": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"promql_legend": "",
|
||||
"layer_type": "scatter",
|
||||
"weight_fixed": 1,
|
||||
"limit": 0,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"time_shift": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"layout": {
|
||||
"x": 0,
|
||||
"y": 27,
|
||||
"w": 48,
|
||||
"h": 12,
|
||||
"i": 8
|
||||
},
|
||||
"htmlContent": "",
|
||||
"markdownContent": "",
|
||||
"customChartContent": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
184
docs/openobserve-dashboard.md
Normal file
184
docs/openobserve-dashboard.md
Normal file
@@ -0,0 +1,184 @@
|
||||
# Dashboard de la API en OpenObserve
|
||||
|
||||
Guía para armar en OpenObserve un dashboard con las métricas HTTP de la API (latencia, tráfico, errores) y
|
||||
una tabla de requests lentos a partir de los logs.
|
||||
|
||||
## 1. Qué datos llegan
|
||||
|
||||
Con `OPENOBSERVE_URL`, `OPENOBSERVE_USER` y `OPENOBSERVE_PASSWORD` en `apps/api/.env`, la API envía:
|
||||
|
||||
**Métricas** (OTLP, cada `METRICS_EXPORT_INTERVAL_MS`, 15 s por defecto). OpenObserve cambia los puntos por
|
||||
guiones bajos y crea un stream por serie:
|
||||
|
||||
| Stream (tipo `metrics`) | Qué es |
|
||||
| ---------------------------------------- | --------------------------------------------------------- |
|
||||
| `http_server_request_duration_bucket` | Histograma de duración (segundos), un contador por `le` |
|
||||
| `http_server_request_duration_count` | Cantidad de requests (contador acumulado) |
|
||||
| `http_server_request_duration_sum` | Suma de duraciones en segundos (contador acumulado) |
|
||||
| `http_server_active_requests` | Requests en curso (gauge) |
|
||||
|
||||
Labels disponibles: `http_route` (patrón de Hono, ej. `/api/lists/:listId`), `http_request_method`,
|
||||
`http_response_status_code`, `service_name` (`superlist-api`) y `le` (solo en `_bucket`).
|
||||
|
||||
Los buckets van de 5 ms a 10 s: `0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10`.
|
||||
|
||||
**Logs** (stream `superlist`, tipo `logs`). OpenObserve pasa los nombres de campo a **minúsculas**:
|
||||
`method`, `path`, `route`, `status`, `durationms`, `requestid`, `userid`, `useragent`, `severity`, `body`,
|
||||
`category`.
|
||||
|
||||
> Los requests a `/api/health` se loguean en `debug`: en desarrollo (nivel por defecto `debug`) llegan a
|
||||
> OpenObserve, en producción (`info`) no. En las métricas están siempre; los filtros de abajo los excluyen.
|
||||
>
|
||||
> Las rutas que no existen (404 de `notFound`) aparecen con `http_route="/*"`. Agrega `http_route!="/*"` al
|
||||
> selector si no las quieres ver en los paneles de latencia.
|
||||
|
||||
## 2. Comprobar que hay datos
|
||||
|
||||
1. **Streams**: deberías ver los streams de la tabla anterior (filtro *Metrics*) y `superlist` (filtro *Logs*).
|
||||
2. **Logs** → stream `superlist` → *Run query*: aparecen los requests con `durationms`.
|
||||
3. **Metrics** → elegir `http_server_request_duration_count` → aparecen series por `http_route`.
|
||||
|
||||
Si los streams existen pero no tienen registros, mira los logs del contenedor de OpenObserve
|
||||
(`docker logs openobserve`) antes de seguir (ver *Problemas frecuentes*).
|
||||
|
||||
## 3. Crear el dashboard
|
||||
|
||||
> **Atajo:** el dashboard completo (paneles 1–8) está en `docs/openobserve-dashboard.json`. En OpenObserve:
|
||||
> **Dashboards** → **Import** → pegar o subir el JSON. También se puede crear por API:
|
||||
> `curl -u "$OPENOBSERVE_USER:$OPENOBSERVE_PASSWORD" -X POST "$OPENOBSERVE_URL/api/default/dashboards?folder=default" -H 'content-type: application/json' --data-binary @docs/openobserve-dashboard.json`.
|
||||
> Los pasos de abajo explican cada panel por si quieres armarlo o cambiarlo a mano.
|
||||
|
||||
1. **Dashboards** → **New Dashboard** → nombre `Superlist API` → *Save*.
|
||||
2. Rango de tiempo arriba a la derecha: *Past 1 hour*; autorrefresco: *30s* (no tiene sentido menos que el
|
||||
intervalo de exportación).
|
||||
3. Para cada panel: **Add Panel** → tipo de gráfico → en el panel de la izquierda elegir **Stream Type
|
||||
`metrics`** y el stream → cambiar el modo de consulta a **PromQL** → pegar la consulta → en *Legend* poner
|
||||
el label (ej. `{http_route}`) → **Apply** → título → **Save**.
|
||||
|
||||
Todas las consultas usan una ventana de `[5m]`: con contadores acumulados, `rate()` necesita al menos dos
|
||||
muestras dentro de la ventana, y con exportación cada 15 s 5 minutos dan margen de sobra.
|
||||
|
||||
### Panel 1 — Requests por segundo por ruta (línea)
|
||||
|
||||
```promql
|
||||
sum by (http_route) (
|
||||
rate(http_server_request_duration_count{service_name="superlist-api", http_route!="/api/health"}[5m])
|
||||
)
|
||||
```
|
||||
|
||||
Legend: `{http_route}`. Unidad: *req/s* (o *Default*).
|
||||
|
||||
### Panel 2 — Latencia p50 / p95 / p99 (línea)
|
||||
|
||||
Agregar tres consultas en el mismo panel (botón **+** junto a la query):
|
||||
|
||||
```promql
|
||||
histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_bucket{http_route!="/api/health"}[5m])))
|
||||
histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_bucket{http_route!="/api/health"}[5m])))
|
||||
histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_bucket{http_route!="/api/health"}[5m])))
|
||||
```
|
||||
|
||||
Legends: `p50`, `p95`, `p99`. Unidad: **Seconds** (la métrica está en segundos; OpenObserve la muestra como
|
||||
ms cuando corresponde).
|
||||
|
||||
Los percentiles se interpolan dentro de cada bucket: si casi todo tarda menos de 5 ms (el primer bucket), verás
|
||||
valores como `4.75 ms` aunque el request real tarde 0.2 ms. Para la duración exacta usa el panel 4 (media) o
|
||||
la tabla del panel 8.
|
||||
|
||||
### Panel 3 — p95 por ruta (línea o barras horizontales)
|
||||
|
||||
```promql
|
||||
histogram_quantile(0.95,
|
||||
sum by (le, http_route) (rate(http_server_request_duration_bucket{http_route!="/api/health"}[5m]))
|
||||
)
|
||||
```
|
||||
|
||||
Legend: `{http_route}`. Unidad: *Seconds*. Es el panel para encontrar el endpoint lento.
|
||||
|
||||
### Panel 4 — Latencia media por ruta (línea)
|
||||
|
||||
```promql
|
||||
sum by (http_route) (rate(http_server_request_duration_sum{http_route!="/api/health"}[5m]))
|
||||
/
|
||||
sum by (http_route) (rate(http_server_request_duration_count{http_route!="/api/health"}[5m]))
|
||||
```
|
||||
|
||||
### Panel 5 — Requests por status (barras apiladas)
|
||||
|
||||
```promql
|
||||
sum by (http_response_status_code) (rate(http_server_request_duration_count{http_route!="/api/health"}[5m]))
|
||||
```
|
||||
|
||||
Legend: `{http_response_status_code}`. Los 401 son normales (sesión vencida, `/api/lists` sin login); fíjate
|
||||
en los 5xx.
|
||||
|
||||
### Panel 6 — Tasa de error 5xx (métrica única / *Metric*)
|
||||
|
||||
```promql
|
||||
100 * sum(rate(http_server_request_duration_count{http_response_status_code=~"5.."}[5m]))
|
||||
/ sum(rate(http_server_request_duration_count[5m]))
|
||||
```
|
||||
|
||||
Unidad: *Percent*. Sin errores la consulta no devuelve nada (no hay serie 5xx); eso es *0 %*.
|
||||
|
||||
### Panel 7 — Requests en curso (métrica única)
|
||||
|
||||
```promql
|
||||
sum(http_server_active_requests)
|
||||
```
|
||||
|
||||
Normalmente 0–1: las conexiones SSE (`/events`) devuelven la respuesta enseguida y no cuentan mientras están
|
||||
abiertas.
|
||||
|
||||
### Panel 8 — Requests más lentos (tabla, desde logs)
|
||||
|
||||
Este sale de los logs, así que tiene el `requestid` para ir al detalle. **Add Panel** → *Table* → **Stream Type
|
||||
`logs`**, stream `superlist` → modo **Custom SQL**:
|
||||
|
||||
```sql
|
||||
SELECT _timestamp, method, path, status, durationms, requestid
|
||||
FROM "superlist"
|
||||
WHERE durationms IS NOT NULL AND path != '/api/health'
|
||||
ORDER BY durationms DESC
|
||||
LIMIT 20
|
||||
```
|
||||
|
||||
Con el `requestid` de una fila, en **Logs** filtra `requestid = '<id>'` y verás todo lo que se logueó durante
|
||||
ese request (emails, fallbacks de dictado, errores).
|
||||
|
||||
### Opcional — Variable para filtrar por ruta
|
||||
|
||||
**Settings** del dashboard (engranaje) → **Variables** → **Add Variable**:
|
||||
|
||||
- Type: *Query Values* · Name: `route` · Stream type: `metrics` · Stream: `http_server_request_duration_count`
|
||||
· Field: `http_route` · habilitar *Multi select* e *Include All*.
|
||||
|
||||
Después, en las consultas, agrega `http_route=~"$route"` al selector, por ejemplo:
|
||||
|
||||
```promql
|
||||
sum by (http_route) (rate(http_server_request_duration_count{http_route=~"$route"}[5m]))
|
||||
```
|
||||
|
||||
## 4. Alertas sugeridas
|
||||
|
||||
En **Alerts** → **Add alert**, tipo *Scheduled*, stream `metrics`, modo PromQL, cada 5 minutos:
|
||||
|
||||
- **p95 alto**: `histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_bucket{http_route!="/api/health"}[5m]))) > 1`
|
||||
- **Errores 5xx**: `sum(rate(http_server_request_duration_count{http_response_status_code=~"5.."}[5m])) > 0`
|
||||
|
||||
## Problemas frecuentes
|
||||
|
||||
- **No aparece ningún stream**: falta `OPENOBSERVE_URL` o las credenciales están mal (OpenObserve responde
|
||||
401 y el exporter no muestra nada en consola). El log de arranque dice `metricsEnabled: true` si las métricas
|
||||
están activas.
|
||||
- **Los streams existen pero están vacíos y `docker logs openobserve` muestra
|
||||
`wal file create error: ... File exists`**: el directorio de datos de OpenObserve está roto. Pasa, por
|
||||
ejemplo, si la carpeta del host montada en `/data` se borró con el contenedor corriendo. Recrea el contenedor
|
||||
con un volumen con nombre o una carpeta fuera del repo (`-v ~/personal-projects/openobserve-data:/data`).
|
||||
- **Rutas con valores `NaN`** en los paneles de latencia: no tuvieron tráfico en la ventana de 5 minutos
|
||||
(división 0/0). Es normal; desaparecen solas.
|
||||
- **Campo desconocido en SQL (`unknown field 'durationMs'`)**: los nombres de campo de los logs están en
|
||||
minúsculas (`durationms`, `requestid`).
|
||||
- **`rate()` vacío al principio**: hacen falta al menos dos exportaciones dentro de la ventana; espera ~30 s
|
||||
después de arrancar la API.
|
||||
- **`/events` con duraciones muy bajas**: es lo esperado, se mide el tiempo hasta abrir el stream SSE.
|
||||
@@ -3,8 +3,47 @@
|
||||
* and the web app consumes them, so they live here instead of being duplicated.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
|
||||
export type ListRole = 'owner' | 'collaborator'
|
||||
|
||||
/**
|
||||
* Icons a user can give a list (keys of lucide icons). The web app maps each key
|
||||
* to its component; the API only validates the key.
|
||||
*/
|
||||
export const LIST_ICONS = [
|
||||
'shopping-cart',
|
||||
'carrot',
|
||||
'apple',
|
||||
'house',
|
||||
'trees',
|
||||
'park',
|
||||
'beef',
|
||||
'fish',
|
||||
'milk',
|
||||
'croissant',
|
||||
'wine',
|
||||
'pill',
|
||||
'baby',
|
||||
'dog',
|
||||
'shirt',
|
||||
'hammer',
|
||||
'gift',
|
||||
] as const
|
||||
|
||||
export const ListIconSchema = z.enum(LIST_ICONS)
|
||||
|
||||
export type ListIcon = (typeof LIST_ICONS)[number]
|
||||
|
||||
/** Most lists a user can pin to the always-visible bar. */
|
||||
export const MAX_PINNED_LISTS = 4
|
||||
|
||||
/** Body of `PATCH /lists/:listId/preferences` (per-user settings of a list). */
|
||||
export type UpdateListPreferencesRequest = {
|
||||
isPinned?: boolean
|
||||
icon?: ListIcon | null
|
||||
}
|
||||
|
||||
export type InvitationStatus = 'pending' | 'accepted' | 'revoked' | 'expired'
|
||||
|
||||
/** A member of a list, as seen in the list detail. */
|
||||
@@ -26,6 +65,12 @@ export type ShoppingListSummary = {
|
||||
name: string
|
||||
role: ListRole
|
||||
isPrimary: boolean
|
||||
/** Per user: pinned to the always-visible bar. */
|
||||
isPinned: boolean
|
||||
/** Per user: icon chosen for the list, `null` to show its initial. */
|
||||
icon: ListIcon | null
|
||||
/** Items not bought yet. */
|
||||
pendingCount: number
|
||||
memberCount: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
@@ -37,6 +82,8 @@ export type ShoppingListDetail = {
|
||||
name: string
|
||||
role: ListRole
|
||||
isPrimary: boolean
|
||||
isPinned: boolean
|
||||
icon: ListIcon | null
|
||||
members: ListMember[]
|
||||
invitations: ListInvitation[]
|
||||
createdAt: string
|
||||
|
||||
@@ -42,4 +42,8 @@ export const VOICE_SPLIT_EXAMPLES: { said: string; items: string[] }[] = [
|
||||
said: 'cuatrocientos gramos de queso y leche descremada',
|
||||
items: ['400g de queso', 'Leche (descremada)'],
|
||||
},
|
||||
{
|
||||
said: 'azúcar leche y café',
|
||||
items: ['Azúcar', 'Leche', 'Café'],
|
||||
},
|
||||
]
|
||||
|
||||
24
turbo.json
24
turbo.json
@@ -21,7 +21,17 @@
|
||||
"WEB_APP_URL",
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS"
|
||||
"GEMINI_TIMEOUT_MS",
|
||||
"GROQ_API_KEY",
|
||||
"GROQ_MODEL",
|
||||
"GROQ_TIMEOUT_MS",
|
||||
"LOG_LEVEL",
|
||||
"OPENOBSERVE_URL",
|
||||
"OPENOBSERVE_ORG",
|
||||
"OPENOBSERVE_STREAM",
|
||||
"OPENOBSERVE_USER",
|
||||
"OPENOBSERVE_PASSWORD",
|
||||
"METRICS_EXPORT_INTERVAL_MS"
|
||||
]
|
||||
},
|
||||
"dev": {
|
||||
@@ -40,7 +50,17 @@
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS",
|
||||
"VITE_API_URL"
|
||||
"GROQ_API_KEY",
|
||||
"GROQ_MODEL",
|
||||
"GROQ_TIMEOUT_MS",
|
||||
"VITE_API_URL",
|
||||
"LOG_LEVEL",
|
||||
"OPENOBSERVE_URL",
|
||||
"OPENOBSERVE_ORG",
|
||||
"OPENOBSERVE_STREAM",
|
||||
"OPENOBSERVE_USER",
|
||||
"OPENOBSERVE_PASSWORD",
|
||||
"METRICS_EXPORT_INTERVAL_MS"
|
||||
]
|
||||
},
|
||||
"db:generate": {
|
||||
|
||||
Reference in New Issue
Block a user