Compare commits
11 Commits
9bd2cc9089
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3411b4b145 | ||
|
|
eace15b140 | ||
|
|
aa170de8d1 | ||
|
|
7ed4d27844 | ||
| f3d9996b11 | |||
|
|
6830c827d7 | ||
|
|
cc0611b6a0 | ||
|
|
9159dd9c9b | ||
|
|
1964d3e08b | ||
| 01769314cb | |||
|
|
2117188bf9 |
17
.claude/launch.json
Normal file
17
.claude/launch.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "web",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": ["run", "dev", "--filter=@superlist/web"],
|
||||
"port": 7153
|
||||
},
|
||||
{
|
||||
"name": "api",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": ["run", "dev", "--filter=@superlist/api"],
|
||||
"port": 4100
|
||||
}
|
||||
]
|
||||
}
|
||||
13
.env.example
13
.env.example
@@ -13,11 +13,13 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# 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 +29,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
|
||||
|
||||
42
AGENTS.md
42
AGENTS.md
@@ -6,9 +6,10 @@ 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, 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`)
|
||||
|
||||
@@ -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/`.
|
||||
@@ -203,7 +206,19 @@ export class CreateAlert {
|
||||
→ `requestId` → request logger → BetterAuth → modules.
|
||||
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
|
||||
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
|
||||
email+password enabled) and owns every route under `/api/auth/*`.
|
||||
email+password enabled) and owns every route under `/api/auth/*`. Password recovery uses the `emailOTP`
|
||||
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
|
||||
@@ -212,9 +227,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`)
|
||||
|
||||
@@ -241,7 +257,7 @@ apps/web/src/
|
||||
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
|
||||
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
|
||||
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
|
||||
- `(auth)/sign-in.tsx` — public routes.
|
||||
- `(auth)/sign-in.tsx`, `sign-up.tsx`, `forgot-password.tsx` — public routes.
|
||||
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
|
||||
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
|
||||
`_authenticated/`.
|
||||
@@ -265,6 +281,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
|
||||
|
||||
2
STACK.md
2
STACK.md
@@ -5,4 +5,4 @@
|
||||
- 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)
|
||||
|
||||
@@ -6,11 +6,13 @@ BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||
# 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 +22,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,6 +16,7 @@
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
|
||||
@@ -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;
|
||||
@@ -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
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { passkey } from '@better-auth/passkey'
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
|
||||
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 ?? '')
|
||||
@@ -9,6 +15,8 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const OTP_EXPIRES_IN_SECONDS = 10 * 60
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
||||
baseURL: process.env.BETTER_AUTH_URL,
|
||||
@@ -27,7 +35,40 @@ export const auth = betterAuth({
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
requireEmailVerification: false,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
},
|
||||
plugins: [
|
||||
// Password recovery: a 6-digit code sent by email, checked by
|
||||
// /api/auth/email-otp/reset-password. Codes live (hashed) in `verifications`.
|
||||
emailOTP({
|
||||
otpLength: 6,
|
||||
expiresIn: OTP_EXPIRES_IN_SECONDS,
|
||||
allowedAttempts: 3,
|
||||
storeOTP: 'hashed',
|
||||
disableSignUp: true,
|
||||
sendVerificationOTP: async ({ email, otp, type }) => {
|
||||
if (type !== 'forget-password') return
|
||||
|
||||
// Not awaited on purpose: answering at the same speed whether or not the
|
||||
// email exists avoids leaking which addresses have an account.
|
||||
void sendEmail({
|
||||
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')
|
||||
})
|
||||
},
|
||||
}),
|
||||
// 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: {
|
||||
create: {
|
||||
|
||||
47
apps/api/src/lib/emails/password-reset.ts
Normal file
47
apps/api/src/lib/emails/password-reset.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { Email } from '@/lib/mailer'
|
||||
|
||||
type PasswordResetEmailInput = {
|
||||
otp: string
|
||||
expiresInMinutes: number
|
||||
}
|
||||
|
||||
/** Builds the "your password reset code" email (in Spanish). */
|
||||
export function passwordResetEmail({
|
||||
otp,
|
||||
expiresInMinutes,
|
||||
}: PasswordResetEmailInput): Omit<Email, 'to'> {
|
||||
const subject = `Tu código para restablecer la contraseña: ${otp}`
|
||||
|
||||
const text = [
|
||||
'Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.',
|
||||
'',
|
||||
`Tu código es: ${otp}`,
|
||||
'',
|
||||
`Vence en ${expiresInMinutes} minutos.`,
|
||||
'Si no lo pediste, ignora este correo: tu contraseña no cambiará.',
|
||||
].join('\n')
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="es">
|
||||
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
|
||||
<tr><td>
|
||||
<h1 style="font-size:20px; margin:0 0 16px;">Restablece tu contraseña</h1>
|
||||
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
|
||||
Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.
|
||||
Usa este código para elegir una nueva:
|
||||
</p>
|
||||
<p style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:32px; font-weight:700; letter-spacing:8px; text-align:center; background:#f4f4f5; border-radius:8px; padding:16px; margin:0 0 24px; color:#18181b;">
|
||||
${otp}
|
||||
</p>
|
||||
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:0;">
|
||||
El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo:
|
||||
tu contraseña no cambiará.
|
||||
</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
@@ -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(
|
||||
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||
{
|
||||
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),
|
||||
},
|
||||
)
|
||||
} 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',
|
||||
)
|
||||
}
|
||||
const body = (await postJson(
|
||||
this.fetchFn,
|
||||
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||
{ 'x-goog-api-key': this.config.apiKey },
|
||||
{
|
||||
systemInstruction: { parts: [{ text: systemInstruction }] },
|
||||
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
||||
generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
|
||||
},
|
||||
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
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
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',
|
||||
}
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
|
||||
import { type ClipboardEvent, useEffect, useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview'
|
||||
import { ItemInputPreview } from '@/components/items/item-input-preview'
|
||||
import { Field, FieldError } from '@/components/ui/field'
|
||||
import {
|
||||
InputGroup,
|
||||
@@ -14,19 +12,10 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||
import { isPlainItem } from '@/lib/natural-input/parse-item'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||
@@ -44,9 +33,6 @@ type CreateItemFormProps = {
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
|
||||
const NEW_ITEM_INPUT_ID = 'new-item-input'
|
||||
|
||||
@@ -69,23 +55,6 @@ export function refocusNewItemInput(): void {
|
||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||
}
|
||||
|
||||
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||
function itemLimitError(item: PreviewItem): string | null {
|
||||
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Input to add items to a list. Submits with Enter or the "+" button. The text is read
|
||||
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
|
||||
@@ -96,11 +65,6 @@ type AddedItems = {
|
||||
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
|
||||
*/
|
||||
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
const { data: items } = useItems(listId)
|
||||
// The text the user asked to add as typed; editing it brings the reading back.
|
||||
const [literalText, setLiteralText] = useState<string | null>(null)
|
||||
|
||||
@@ -111,22 +75,31 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
|
||||
const text = useWatch({ control: form.control, name: 'entry' })
|
||||
const literal = literalText !== null && literalText === text
|
||||
// Placeholders have no server id yet, so they cannot be added to.
|
||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) })
|
||||
const restoreText = (source: string, message: string) => {
|
||||
const current = form.getValues('entry').trim()
|
||||
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||
form.setError('entry', { message })
|
||||
}
|
||||
|
||||
// A failed item comes back to the input, and so does a dictation that breaks the limits.
|
||||
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: restoreText,
|
||||
onDictationRejected: (transcript, message) => {
|
||||
form.setValue('entry', transcript)
|
||||
form.setError('entry', { message })
|
||||
},
|
||||
})
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
|
||||
// The keyboard's own microphone (the only one in the installed iOS app) just writes
|
||||
// text: once it has been quiet for a few seconds, that text is added as a dictation.
|
||||
const keyboardDictation = useKeyboardDictation({
|
||||
onIdle: () => {
|
||||
const dictated = form.getValues('entry').trim()
|
||||
if (dictated && !dictation.listening && !voiceSplit.isPending) void addDictation(dictated)
|
||||
if (dictated && !dictation.listening && !processing) onTranscript(dictated)
|
||||
},
|
||||
})
|
||||
const processing = voiceSplit.isPending
|
||||
const dictating = dictation.listening || processing
|
||||
|
||||
// The partial transcript is shown in the input while the user talks.
|
||||
@@ -140,64 +113,6 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
text.trim() !== '' &&
|
||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||
|
||||
const restoreText = (source: string, message: string) => {
|
||||
const current = form.getValues('entry').trim()
|
||||
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||
form.setError('entry', { message })
|
||||
}
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
restoreText(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
// The input clears at once (items are added optimistically) so several items can be
|
||||
// typed in a row; if a request fails its text comes back with the error.
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
@@ -217,48 +132,12 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
addItems(toAdd)
|
||||
})
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the whole transcript is added as a single item.
|
||||
*/
|
||||
const addDictation = async (transcript: string) => {
|
||||
/** A dictation clears the input and goes through `addDictation`. */
|
||||
const onTranscript = (transcript: string) => {
|
||||
keyboardDictation.cancel()
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, true, existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
form.setValue('entry', transcript)
|
||||
form.setError('entry', { message: limitError })
|
||||
return
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
void addDictation(transcript)
|
||||
}
|
||||
|
||||
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
|
||||
@@ -376,12 +255,3 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||
function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||
if (!text.trim()) return []
|
||||
|
||||
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||
|
||||
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||
}
|
||||
|
||||
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(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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
51
apps/web/src/components/items/dictate-items-button.tsx
Normal file
51
apps/web/src/components/items/dictate-items-button.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||
|
||||
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||
|
||||
type DictateItemsButtonProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
|
||||
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||
*/
|
||||
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
const { listening, busy, processing, heard, message, start, stop } = useDictateItems(listId)
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={listening ? 'default' : 'secondary'}
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
disabled={busy}
|
||||
className="relative rounded-full"
|
||||
onClick={() => {
|
||||
if (listening) stop()
|
||||
else start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2Icon className="animate-spin" />
|
||||
) : listening ? (
|
||||
<SquareIcon className="fill-current" />
|
||||
) : (
|
||||
<MicIcon />
|
||||
)}
|
||||
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<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,8 @@ 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'
|
||||
import { MoveItemDialog } from './move-item-dialog'
|
||||
@@ -101,13 +103,14 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
Usa el campo de arriba para añadir tu primer artículo.
|
||||
</p>
|
||||
</div>
|
||||
<DictateItemsButton listId={listId} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
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">
|
||||
@@ -144,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>
|
||||
)
|
||||
}
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
171
apps/web/src/hooks/use-add-items.ts
Normal file
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { useRef } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { PreviewItem } from '@/components/items/item-input-preview'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
||||
export function itemLimitError(item: PreviewItem): string | null {
|
||||
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
||||
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
||||
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** The items `text` adds, each with the pending item it repeats, if any. */
|
||||
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
||||
if (!text.trim()) return []
|
||||
|
||||
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
||||
|
||||
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
type UseAddItemsOptions = {
|
||||
/** An item could not be created: `source` is the text it was read from. */
|
||||
onItemFailed: (source: string, message: string) => void
|
||||
/** A dictation was not added because an item breaks the API limits. */
|
||||
onDictationRejected: (transcript: string, message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds items to a list the way the "add an item" input does: an item already pending is
|
||||
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
||||
* and can be undone as a whole.
|
||||
*/
|
||||
export function useAddItems(
|
||||
listId: string,
|
||||
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
||||
) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
const { data: items } = useItems(listId)
|
||||
// Placeholders have no server id yet, so they cannot be added to.
|
||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
for (const item of toAdd) {
|
||||
if (item.duplicate) {
|
||||
const patch = mergeInto(item.duplicate, item)
|
||||
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
||||
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
onItemFailed(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the transcript is read as typed text when it is
|
||||
* already split into lines, and added as a single item otherwise.
|
||||
*
|
||||
* @returns how many items were understood (0 when the dictation had none).
|
||||
*/
|
||||
const addDictation = async (transcript: string): Promise<number> => {
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return 0
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
onDictationRejected(transcript, limitError)
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return toAdd.length
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return toAdd.length
|
||||
}
|
||||
|
||||
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
||||
}
|
||||
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,22 +1,9 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
/** The slice of the Web Speech API this hook uses (TypeScript's DOM lib does not ship it). */
|
||||
type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
||||
|
||||
type SpeechRecognitionLike = {
|
||||
lang: string
|
||||
interimResults: boolean
|
||||
continuous: boolean
|
||||
maxAlternatives: number
|
||||
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onend: (() => void) | null
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
}
|
||||
|
||||
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
|
||||
import {
|
||||
canDictate,
|
||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
||||
@@ -33,18 +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') return null
|
||||
|
||||
const iosStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
if (iosStandalone) return null
|
||||
|
||||
const speechWindow = window as Window & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
||||
}
|
||||
|
||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
||||
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])
|
||||
}
|
||||
|
||||
155
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
155
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { splitDictation } from '@/lib/natural-input/dictation'
|
||||
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
|
||||
|
||||
export const DICTATION_MESSAGES = {
|
||||
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
|
||||
unavailable: 'No encontramos un micrófono disponible.',
|
||||
unsupported:
|
||||
'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.',
|
||||
empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.',
|
||||
failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.',
|
||||
} as const
|
||||
|
||||
/** Recognition errors with a message of their own; any other one is `failed`. */
|
||||
const RECOGNITION_ERRORS: Record<string, string | null> = {
|
||||
'not-allowed': DICTATION_MESSAGES.denied,
|
||||
'service-not-allowed': DICTATION_MESSAGES.unsupported,
|
||||
'audio-capture': DICTATION_MESSAGES.unavailable,
|
||||
// Silence just ends with no phrases; a stop of ours is not an error.
|
||||
'no-speech': null,
|
||||
aborted: null,
|
||||
}
|
||||
|
||||
/** What `getUserMedia` rejects with, as one of the messages. */
|
||||
function microphoneError(error: unknown): string {
|
||||
const name = error instanceof DOMException ? error.name : ''
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied
|
||||
|
||||
return DICTATION_MESSAGES.unavailable
|
||||
}
|
||||
|
||||
type DictationStatus = 'idle' | 'requesting' | 'listening'
|
||||
|
||||
type UseMicrophoneDictationOptions = {
|
||||
/** The phrases dictated, one per item said, when the dictation ends with some. */
|
||||
onPhrases: (phrases: string[]) => void
|
||||
/** Why the dictation did not deliver anything, in Spanish. */
|
||||
onError: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition`
|
||||
* in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks
|
||||
* for the microphone right there, then listens until the user calls `stop()` or the
|
||||
* browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases
|
||||
* (`splitDictation`).
|
||||
*
|
||||
* The microphone stream is only used to ask for the permission: its tracks are stopped
|
||||
* as soon as it arrives (even after an unmount), before the recognition opens its own
|
||||
* 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('')
|
||||
const callbacksRef = useRef({ onPhrases, onError })
|
||||
// Ends the dictation in progress: `true` delivers what was heard, `false` drops it.
|
||||
const endRef = useRef<((deliver: boolean) => void) | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { onPhrases, onError }
|
||||
})
|
||||
|
||||
useEffect(() => () => endRef.current?.(false), [])
|
||||
|
||||
const start = useCallback(() => {
|
||||
if (endRef.current) return
|
||||
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
if (!SpeechRecognition) {
|
||||
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
|
||||
return
|
||||
}
|
||||
|
||||
let recognition: SpeechRecognitionLike | null = null
|
||||
let segments: string[] = []
|
||||
let failure: string | null = null
|
||||
let done = false
|
||||
|
||||
const end = (deliver: boolean) => {
|
||||
if (done) return
|
||||
done = true
|
||||
endRef.current = null
|
||||
// Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done.
|
||||
recognition?.abort()
|
||||
setStatus('idle')
|
||||
setHeard('')
|
||||
// Stopped while the permission was being asked: there is nothing to tell.
|
||||
if (!deliver || (!recognition && !failure)) return
|
||||
|
||||
const phrases = splitDictation(segments)
|
||||
if (failure) callbacksRef.current.onError(failure)
|
||||
else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty)
|
||||
else callbacksRef.current.onPhrases(phrases)
|
||||
}
|
||||
|
||||
const listen = () => {
|
||||
recognition = new SpeechRecognition()
|
||||
recognition.lang = 'es-AR'
|
||||
recognition.interimResults = true
|
||||
recognition.continuous = true
|
||||
recognition.maxAlternatives = 1
|
||||
|
||||
// Each result is a stretch of speech between pauses; the last one may still change.
|
||||
recognition.onresult = (event) => {
|
||||
segments = Array.from(event.results, (result) => result[0].transcript)
|
||||
setHeard(splitDictation(segments).join(' · '))
|
||||
}
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
const message = RECOGNITION_ERRORS[event.error]
|
||||
if (message === null) return
|
||||
failure = message ?? DICTATION_MESSAGES.failed
|
||||
}
|
||||
|
||||
recognition.onend = () => end(true)
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
setStatus('listening')
|
||||
} catch {
|
||||
failure = DICTATION_MESSAGES.failed
|
||||
end(true)
|
||||
}
|
||||
}
|
||||
|
||||
endRef.current = end
|
||||
setStatus('requesting')
|
||||
|
||||
// Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself.
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
listen()
|
||||
return
|
||||
}
|
||||
|
||||
// Called right in the click, before any `await`, so Safari treats it as the user's.
|
||||
navigator.mediaDevices.getUserMedia({ audio: true }).then(
|
||||
(stream) => {
|
||||
for (const track of stream.getTracks()) track.stop()
|
||||
if (!done) listen()
|
||||
},
|
||||
(error: unknown) => {
|
||||
failure = microphoneError(error)
|
||||
end(true)
|
||||
},
|
||||
)
|
||||
}, [])
|
||||
|
||||
/** Stops listening; what was heard so far is delivered. */
|
||||
const stop = useCallback(() => endRef.current?.(true), [])
|
||||
|
||||
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 })
|
||||
},
|
||||
})
|
||||
}
|
||||
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,5 @@
|
||||
import { passkeyClient } from '@better-auth/passkey/client'
|
||||
import { emailOTPClient } from 'better-auth/client/plugins'
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
|
||||
/**
|
||||
@@ -7,6 +9,7 @@ import { createAuthClient } from 'better-auth/react'
|
||||
*/
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||
plugins: [emailOTPClient(), passkeyClient()],
|
||||
})
|
||||
|
||||
export const { signIn, signUp, signOut, useSession } = authClient
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
37
apps/web/src/lib/natural-input/dictation.test.ts
Normal file
37
apps/web/src/lib/natural-input/dictation.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { splitDictation } from './dictation'
|
||||
|
||||
describe('splitDictation', () => {
|
||||
it('splits on "nuevo ítem" and its variants', () => {
|
||||
expect(
|
||||
splitDictation([
|
||||
'leche descremada nuevo ítem pan Nuevo item 2 kilos de papa, otro artículo yerba',
|
||||
]),
|
||||
).toEqual(['leche descremada', 'pan', '2 kilos de papa', 'yerba'])
|
||||
})
|
||||
|
||||
it('takes every segment and line as a separate phrase', () => {
|
||||
expect(splitDictation(['Leche.', ' pan\nqueso rallado '])).toEqual([
|
||||
'Leche',
|
||||
'pan',
|
||||
'queso rallado',
|
||||
])
|
||||
})
|
||||
|
||||
it('collapses spaces and drops empty phrases', () => {
|
||||
expect(splitDictation([' dulce de leche ', '', 'nuevo ítem', '...'])).toEqual([
|
||||
'dulce de leche',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a repeated phrase once, ignoring case and accents', () => {
|
||||
expect(splitDictation(['jamón', 'Jamon nuevo ítem pan', 'pan'])).toEqual(['jamón', 'pan'])
|
||||
})
|
||||
|
||||
it('does not split words that only contain the keywords', () => {
|
||||
expect(splitDictation(['productos nuevos de limpieza'])).toEqual([
|
||||
'productos nuevos de limpieza',
|
||||
])
|
||||
})
|
||||
})
|
||||
35
apps/web/src/lib/natural-input/dictation.ts
Normal file
35
apps/web/src/lib/natural-input/dictation.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { normalizeWord } from './text'
|
||||
|
||||
/**
|
||||
* What the user says to start another item: "nuevo ítem", "otro artículo", "nuevo
|
||||
* producto". The punctuation the recognizer puts around it goes with it.
|
||||
*/
|
||||
const NEXT_ITEM =
|
||||
/[\s,.;:]*(?<!\p{L})(?:nuevo|otro)\s+(?:[íi]tem|art[íi]culo|producto)(?!\p{L})[\s,.;:]*/giu
|
||||
|
||||
/** Punctuation the recognizer adds around a phrase ("Leche."), not part of the item. */
|
||||
const EDGE_PUNCTUATION = /^[\s,.;:]+|[\s,.;:]+$/g
|
||||
|
||||
/**
|
||||
* The phrases of a dictation, one per item said: each segment (a pause or a line break,
|
||||
* as the recognizer delivers them) is also split on "nuevo ítem". Spaces are collapsed,
|
||||
* empty phrases dropped and a phrase repeated in the same dictation kept once (ignoring
|
||||
* case and accents); the words themselves are left as heard.
|
||||
*/
|
||||
export function splitDictation(segments: string[]): string[] {
|
||||
const phrases: string[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const segment of segments) {
|
||||
for (const part of segment.split(/\r?\n/).flatMap((line) => line.split(NEXT_ITEM))) {
|
||||
const phrase = part.replace(/\s+/g, ' ').replace(EDGE_PUNCTUATION, '')
|
||||
const key = normalizeWord(phrase)
|
||||
if (!phrase || seen.has(key)) continue
|
||||
|
||||
seen.add(key)
|
||||
phrases.push(phrase)
|
||||
}
|
||||
}
|
||||
|
||||
return phrases
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
47
apps/web/src/lib/speech-recognition.ts
Normal file
47
apps/web/src/lib/speech-recognition.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/** The slice of the Web Speech API the app uses (TypeScript's DOM lib does not ship it). */
|
||||
export type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
|
||||
|
||||
export type SpeechRecognitionLike = {
|
||||
lang: string
|
||||
interimResults: boolean
|
||||
continuous: boolean
|
||||
maxAlternatives: number
|
||||
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onend: (() => void) | null
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
}
|
||||
|
||||
export type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
|
||||
|
||||
/** `SpeechRecognition`, or Safari's `webkitSpeechRecognition`, or `null` when there is none. */
|
||||
export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
|
||||
const speechWindow = window as Window & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor
|
||||
}
|
||||
|
||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
|
||||
}
|
||||
|
||||
/** Whether the page runs as an app installed on the iOS home screen. */
|
||||
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
|
||||
}
|
||||
288
apps/web/src/routes/(auth)/forgot-password.tsx
Normal file
288
apps/web/src/routes/(auth)/forgot-password.tsx
Normal file
@@ -0,0 +1,288 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { AppBrand } from '@/components/app-logo'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
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 { emailOtp } from '@/lib/auth-client'
|
||||
|
||||
type ForgotPasswordSearch = { redirect?: string; email?: string }
|
||||
|
||||
export const Route = createFileRoute('/(auth)/forgot-password')({
|
||||
validateSearch: (search: Record<string, unknown>): ForgotPasswordSearch => ({
|
||||
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||
email: typeof search.email === 'string' ? search.email : undefined,
|
||||
}),
|
||||
component: ForgotPasswordPage,
|
||||
})
|
||||
|
||||
const requestSchema = z.object({
|
||||
email: z.email('Introduce un correo electrónico válido'),
|
||||
})
|
||||
|
||||
const resetSchema = z
|
||||
.object({
|
||||
otp: z.string().regex(/^\d{6}$/, 'El código tiene 6 dígitos'),
|
||||
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((values) => values.password === values.confirmPassword, {
|
||||
message: 'Las contraseñas no coinciden',
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
|
||||
// BetterAuth answers in English; an unknown email reads like a wrong code so the
|
||||
// form doesn't reveal which addresses have an account.
|
||||
const resetErrorMessages: Record<string, string> = {
|
||||
INVALID_OTP: 'El código no es correcto.',
|
||||
USER_NOT_FOUND: 'El código no es correcto.',
|
||||
OTP_EXPIRED: 'El código venció. Pide uno nuevo.',
|
||||
TOO_MANY_ATTEMPTS: 'Demasiados intentos fallidos. Pide un código nuevo.',
|
||||
}
|
||||
|
||||
type RequestValues = z.infer<typeof requestSchema>
|
||||
type ResetValues = z.infer<typeof resetSchema>
|
||||
|
||||
function ForgotPasswordPage() {
|
||||
const { redirect, email: initialEmail } = Route.useSearch()
|
||||
const [email, setEmail] = useState<string | null>(null)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
<AppBrand />
|
||||
<Card className="w-full max-w-sm">
|
||||
{email ? (
|
||||
<ResetPasswordStep
|
||||
email={email}
|
||||
redirect={redirect}
|
||||
onChangeEmail={() => setEmail(null)}
|
||||
/>
|
||||
) : (
|
||||
<RequestCodeStep
|
||||
defaultEmail={initialEmail ?? ''}
|
||||
redirect={redirect}
|
||||
onSent={setEmail}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type RequestCodeStepProps = {
|
||||
defaultEmail: string
|
||||
redirect?: string
|
||||
onSent: (email: string) => void
|
||||
}
|
||||
|
||||
function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<RequestValues>({
|
||||
resolver: zodResolver(requestSchema),
|
||||
defaultValues: { email: defaultEmail },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ email }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
|
||||
if (requestError) {
|
||||
setError(requestError.message ?? 'No pudimos enviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
onSent(email)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Recuperar contraseña</CardTitle>
|
||||
<CardDescription>Te enviaremos un código por correo para elegir una nueva.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos enviar el código</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.email}>
|
||||
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="ada@ejemplo.com"
|
||||
{...form.register('email')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.email]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Enviando…' : 'Enviar código'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type ResetPasswordStepProps = {
|
||||
email: string
|
||||
redirect?: string
|
||||
onChangeEmail: () => void
|
||||
}
|
||||
|
||||
function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) {
|
||||
const navigate = useNavigate()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [resending, setResending] = useState(false)
|
||||
|
||||
const form = useForm<ResetValues>({
|
||||
resolver: zodResolver(resetSchema),
|
||||
defaultValues: { otp: '', password: '', confirmPassword: '' },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ otp, password }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: resetError } = await emailOtp.resetPassword({ email, otp, password })
|
||||
|
||||
if (resetError) {
|
||||
setError(
|
||||
(resetError.code && resetErrorMessages[resetError.code]) ??
|
||||
resetError.message ??
|
||||
'No pudimos cambiar tu contraseña',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Contraseña actualizada. Ya puedes iniciar sesión.')
|
||||
await navigate({ to: '/sign-in', search: redirect ? { redirect } : {} })
|
||||
})
|
||||
|
||||
const resend = async () => {
|
||||
setResending(true)
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
setResending(false)
|
||||
|
||||
if (requestError) {
|
||||
toast.error(requestError.message ?? 'No pudimos reenviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Te enviamos un código nuevo')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Elige una nueva contraseña</CardTitle>
|
||||
<CardDescription>
|
||||
Si existe una cuenta con <span className="text-foreground font-medium">{email}</span>, te
|
||||
enviamos un código de 6 dígitos. Vence en 10 minutos.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos cambiar tu contraseña</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.otp}>
|
||||
<FieldLabel htmlFor="otp">Código</FieldLabel>
|
||||
<Input
|
||||
id="otp"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
placeholder="123456"
|
||||
className="font-mono tracking-widest"
|
||||
{...form.register('otp')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.otp]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<FieldLabel htmlFor="password">Nueva contraseña</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('password')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.password]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.confirmPassword}>
|
||||
<FieldLabel htmlFor="confirmPassword">Repite la contraseña</FieldLabel>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('confirmPassword')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.confirmPassword]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Guardando…' : 'Cambiar contraseña'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<Button type="button" variant="link" className="h-auto p-0" onClick={onChangeEmail}>
|
||||
Usar otro correo
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
disabled={resending}
|
||||
onClick={resend}
|
||||
>
|
||||
{resending ? 'Reenviando…' : 'Reenviar código'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BackToSignIn({ redirect }: { redirect?: string }) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-center text-sm">
|
||||
¿Recordaste tu contraseña?{' '}
|
||||
<Link
|
||||
to="/sign-in"
|
||||
search={redirect ? { redirect } : {}}
|
||||
className="text-foreground font-medium underline-offset-4 hover:underline"
|
||||
>
|
||||
Inicia sesión
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -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,14 +100,31 @@ function SignInPage() {
|
||||
return
|
||||
}
|
||||
|
||||
if (redirect) {
|
||||
window.location.assign(redirect)
|
||||
return
|
||||
}
|
||||
|
||||
await navigate({ to: '/' })
|
||||
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 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">
|
||||
<AppBrand />
|
||||
@@ -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')}
|
||||
/>
|
||||
@@ -85,7 +158,19 @@ function SignInPage() {
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||
<div className="flex items-center justify-between">
|
||||
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
search={() => {
|
||||
const email = form.getValues('email')
|
||||
return { redirect, email: email || undefined }
|
||||
}}
|
||||
className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
@@ -95,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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
|
||||
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'
|
||||
@@ -37,6 +38,7 @@ function AuthenticatedLayout() {
|
||||
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppBadge />
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<AppHeader />
|
||||
|
||||
@@ -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>
|
||||
|
||||
50
bun.lock
50
bun.lock
@@ -14,6 +14,7 @@
|
||||
"name": "@superlist/api",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
@@ -38,6 +39,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 +294,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 +344,8 @@
|
||||
|
||||
"@fontsource-variable/geist": ["@fontsource-variable/geist@5.3.0", "", {}, "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA=="],
|
||||
|
||||
"@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=="],
|
||||
@@ -366,6 +372,8 @@
|
||||
|
||||
"@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=="],
|
||||
|
||||
"@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=="],
|
||||
@@ -384,6 +392,32 @@
|
||||
|
||||
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
"@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
|
||||
|
||||
"@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=="],
|
||||
@@ -632,6 +666,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 +892,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=="],
|
||||
@@ -1596,6 +1636,10 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1638,6 +1682,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=="],
|
||||
@@ -1844,6 +1890,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=="],
|
||||
@@ -2118,6 +2166,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=="],
|
||||
|
||||
@@ -24,7 +24,11 @@ services:
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
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}
|
||||
|
||||
@@ -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é'],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
"WEB_APP_URL",
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS"
|
||||
"GEMINI_TIMEOUT_MS",
|
||||
"GROQ_API_KEY",
|
||||
"GROQ_MODEL",
|
||||
"GROQ_TIMEOUT_MS"
|
||||
]
|
||||
},
|
||||
"dev": {
|
||||
@@ -40,6 +43,9 @@
|
||||
"GEMINI_API_KEY",
|
||||
"GEMINI_MODEL",
|
||||
"GEMINI_TIMEOUT_MS",
|
||||
"GROQ_API_KEY",
|
||||
"GROQ_MODEL",
|
||||
"GROQ_TIMEOUT_MS",
|
||||
"VITE_API_URL"
|
||||
]
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user