@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# react-app-router
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para **una SPA con varias pantallas**: tabla de rutas en un solo sitio, cabecera con navegación, pantallas perezosas (un chunk por pantalla), 404 y pantalla de error. El guard de sesión y las acciones de la cabecera entran desde `main.tsx`, así que el router no conoce la auth.
|
|
6
|
+
|
|
7
|
+
Con una sola pantalla no hace falta: la base ya pinta `HomeScreen` sin router.
|
|
8
|
+
|
|
9
|
+
**Requiere `vite-react-base`** (sustituye su `App.tsx`). **Usa `react-supabase-auth`** (`RequireSession` como guard) y `playwright-e2e`.
|
|
10
|
+
|
|
11
|
+
## Qué incluye
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
src/router/
|
|
15
|
+
routes.tsx PATHS · appRoutes({guard?, headerActions?}) → RouteObject[] · createAppRouter({kind: 'browser' | 'hash'})
|
|
16
|
+
Layout.tsx cabecera (nombre, NavLink por ruta, acciones) + <Outlet>
|
|
17
|
+
NotFoundScreen.tsx 404 con enlace al inicio
|
|
18
|
+
ErrorScreen.tsx error boundary de ruta: título, solo la clase del error, botón Recargar
|
|
19
|
+
router.css solo usa las variables de vite-react-base
|
|
20
|
+
index.ts
|
|
21
|
+
router.test.tsx 5 tests: navegación y enlace activo, pantalla perezosa por URL, 404 y vuelta, guard y acciones, error sin internos
|
|
22
|
+
src/screens/SettingsScreen.tsx ejemplo de pantalla perezosa
|
|
23
|
+
src/App.tsx sustituye al de la base: <AppProvider><RouterProvider router/></AppProvider>
|
|
24
|
+
src/App.test.tsx sustituye al de la base: los mismos 4 tests, montando el router en memoria
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Decisiones
|
|
28
|
+
|
|
29
|
+
- **react-router en modo data** (`createBrowserRouter` + `RouterProvider`), no `<Routes>` anidadas. Las rutas son datos (`RouteObject[]`), así que `createMemoryRouter(appRoutes(), {initialEntries})` las monta en un test sin DOM de navegador, y `lazy` las trocea por pantalla. No había un patrón común en los proyectos de origen; la receta toma de ellos la tabla declarativa con guard por rama y que la sesión decida antes que la ruta.
|
|
30
|
+
- **El guard y las acciones se inyectan.** `appRoutes({guard, headerActions})` recibe un componente que envuelve el layout y un nodo para la cabecera. `router/` no importa `auth/`; `main.tsx`, un nivel por encima, los junta. Sin auth, no se pasa nada y la app es pública.
|
|
31
|
+
- **`PATHS` como constantes.** Enlaces, `navigate` y tests usan `PATHS.settings`, no `'/settings'` escrito a mano.
|
|
32
|
+
- **Una ruta perezosa como ejemplo.** `lazy: async () => ({ Component })` saca `SettingsScreen` a su propio chunk; se descarga la primera vez que se visita.
|
|
33
|
+
- **404 dentro del layout y error boundary de ruta.** `*` pinta `NotFoundScreen` con la cabecera; una pantalla que lanza al renderizar muestra `ErrorScreen` con la *clase* del error y un botón de recargar, nunca el mensaje (puede llevar internos).
|
|
34
|
+
- **`browser` por defecto, `hash` si el host no reenvía a `index.html`.** `vite preview` y cualquier host de SPA responden `index.html` a cualquier ruta; en un bucket estático sin fallback, `createAppRouter({ kind: 'hash' })`.
|
|
35
|
+
|
|
36
|
+
## Cómo adaptarla
|
|
37
|
+
|
|
38
|
+
1. Copia `files/` encima del frontend de `vite-react-base` (sobrescribe `App.tsx` y `App.test.tsx`) y ejecuta `npm install react-router@^8.5.1`.
|
|
39
|
+
2. **Arranque** (`main.tsx`):
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
import { createAppRouter } from './router'
|
|
43
|
+
const router = createAppRouter() // público
|
|
44
|
+
const router = createAppRouter({ guard: RequireSession, headerActions: <SignOutButton /> }) // con react-supabase-auth
|
|
45
|
+
// render: <App services={{ api }} router={router} />
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
3. **Una pantalla nueva:** su ruta en `PATHS`, su entrada en `children` de `appRoutes` (`lazy` si pesa) y su `NavLink` en `Layout.tsx`. Para `react-agent-chat`: añade `chat: ChatApi` a `AppServices`, constrúyelo en `main.tsx` junto a `api` y una `ChatScreen` que haga `<ChatView chat={useApp().chat} />`.
|
|
49
|
+
4. **Rutas con parámetros:** `path: 'documents/:id'` y `useParams()` en la pantalla. Declara las literales antes que las dinámicas (`documents/new` antes de `documents/:id`).
|
|
50
|
+
5. **Pantallas por rol:** envuelve la rama con otro guard (`({children}) => role === 'admin' ? children : <Navigate to={PATHS.home} />`) o pasa un guard distinto a `appRoutes`. El backend sigue siendo la barrera real (en producción, el guard deja pasar si no pudo cargar las capacidades, para no entrar en bucle).
|
|
51
|
+
6. Para comprobarla: `npm run typecheck && npm test` (9 tests de esta receta, 28 con la base).
|
|
52
|
+
|
|
53
|
+
**Dependencias:** `react-router` (probado con 8.5.1).
|
|
54
|
+
|
|
55
|
+
## Origen
|
|
56
|
+
|
|
57
|
+
- Probado en producción: tabla de rutas declarativa con guard en la rama protegida, rutas literales antes que dinámicas, `**` a una pantalla, `loadChildren` por feature; la sesión decide antes que la ruta, constantes de ruta, router por hash, tests de `navigate` con un `vi.fn()` y e2e con `toHaveURL`.
|
|
58
|
+
- Nuevo en esta receta: guard inyectado desde arriba, error boundary de ruta y pantalla perezosa, siguiendo la regla de que las capacidades no se importan entre sí.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { render, screen } from '@testing-library/react'
|
|
2
|
+
import userEvent from '@testing-library/user-event'
|
|
3
|
+
import { createMemoryRouter } from 'react-router'
|
|
4
|
+
import { describe, expect, it } from 'vitest'
|
|
5
|
+
|
|
6
|
+
import { App } from './App'
|
|
7
|
+
import { ApiError, NetworkError, type Api } from './api/api'
|
|
8
|
+
import { createFakeApi } from './api/fake/fake-api'
|
|
9
|
+
import { makeApi } from './api/make-api'
|
|
10
|
+
import { appRoutes, PATHS } from './router'
|
|
11
|
+
|
|
12
|
+
function mount(api: Api, path = PATHS.home) {
|
|
13
|
+
render(<App services={{ api }} router={createMemoryRouter(appRoutes(), { initialEntries: [path] })} />)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('App with the fake api', () => {
|
|
17
|
+
it('renders data loaded through the context', async () => {
|
|
18
|
+
mount(createFakeApi({ latencyMs: 0 }))
|
|
19
|
+
|
|
20
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Demo User' })).toBeTruthy()
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('shows an error by code and retries', async () => {
|
|
24
|
+
let calls = 0
|
|
25
|
+
const api: Api = {
|
|
26
|
+
...createFakeApi({ latencyMs: 0 }),
|
|
27
|
+
me: async () => {
|
|
28
|
+
calls += 1
|
|
29
|
+
if (calls === 1) throw new ApiError(403, 'forbidden')
|
|
30
|
+
return { userId: 'u', tenantId: 't', name: 'Ana' }
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
mount(api)
|
|
34
|
+
|
|
35
|
+
expect((await screen.findByRole('alert')).textContent).toContain('forbidden')
|
|
36
|
+
await userEvent.click(screen.getByRole('button', { name: 'Reintentar' }))
|
|
37
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Ana' })).toBeTruthy()
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('tells offline apart from an API error', async () => {
|
|
41
|
+
mount({ me: async () => Promise.reject(new NetworkError()) })
|
|
42
|
+
expect((await screen.findByRole('alert')).textContent).toContain('Sin conexión')
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
describe('makeApi factory', () => {
|
|
47
|
+
it('builds the implementation the settings name', async () => {
|
|
48
|
+
const fake = await makeApi({ mode: 'fake', apiUrl: '/api' })
|
|
49
|
+
expect(await fake.me()).toMatchObject({ name: 'Demo User' })
|
|
50
|
+
|
|
51
|
+
const http = await makeApi({ mode: 'http', apiUrl: '/api' })
|
|
52
|
+
expect(typeof http.me).toBe('function')
|
|
53
|
+
})
|
|
54
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { RouterProvider, type createBrowserRouter } from 'react-router'
|
|
2
|
+
|
|
3
|
+
import { AppProvider, type AppServices } from './app-context'
|
|
4
|
+
|
|
5
|
+
export type AppRouter = ReturnType<typeof createBrowserRouter>
|
|
6
|
+
|
|
7
|
+
/** Root component. Gets its services and its router from outside (main.tsx or a test), so it never builds them. */
|
|
8
|
+
export function App({ services, router }: { services: AppServices; router: AppRouter }) {
|
|
9
|
+
return (
|
|
10
|
+
<AppProvider services={services}>
|
|
11
|
+
<RouterProvider router={router} />
|
|
12
|
+
</AppProvider>
|
|
13
|
+
)
|
|
14
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Route error boundary: a screen that throws while rendering shows this instead of a blank page. */
|
|
2
|
+
|
|
3
|
+
import { isRouteErrorResponse, useRouteError } from 'react-router'
|
|
4
|
+
|
|
5
|
+
export function ErrorScreen() {
|
|
6
|
+
const error = useRouteError()
|
|
7
|
+
const title = isRouteErrorResponse(error) ? `Error ${error.status}` : 'Algo ha fallado'
|
|
8
|
+
// Only the class reaches the screen; the message may carry internals.
|
|
9
|
+
const kind = error instanceof Error ? error.name : typeof error
|
|
10
|
+
return (
|
|
11
|
+
<main className="layout">
|
|
12
|
+
<section role="alert" className="card">
|
|
13
|
+
<h1>{title}</h1>
|
|
14
|
+
<p className="muted">{kind}</p>
|
|
15
|
+
<button className="button" onClick={() => window.location.reload()}>
|
|
16
|
+
Recargar
|
|
17
|
+
</button>
|
|
18
|
+
</section>
|
|
19
|
+
</main>
|
|
20
|
+
)
|
|
21
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Shell of every screen: header with navigation and the current screen in `<Outlet>`. */
|
|
2
|
+
|
|
3
|
+
import type { ReactNode } from 'react'
|
|
4
|
+
import { NavLink, Outlet } from 'react-router'
|
|
5
|
+
|
|
6
|
+
import { CONFIG } from '../config'
|
|
7
|
+
import { PATHS } from './routes'
|
|
8
|
+
import './router.css'
|
|
9
|
+
|
|
10
|
+
export function Layout({ actions }: { actions?: ReactNode }) {
|
|
11
|
+
return (
|
|
12
|
+
<>
|
|
13
|
+
<header className="topbar">
|
|
14
|
+
<strong className="topbar-brand">{CONFIG.appName}</strong>
|
|
15
|
+
<nav className="topbar-nav" aria-label="Principal">
|
|
16
|
+
<NavLink to={PATHS.home} end>
|
|
17
|
+
Inicio
|
|
18
|
+
</NavLink>
|
|
19
|
+
<NavLink to={PATHS.settings}>Ajustes</NavLink>
|
|
20
|
+
</nav>
|
|
21
|
+
{actions && <div className="topbar-actions">{actions}</div>}
|
|
22
|
+
</header>
|
|
23
|
+
<main className="layout">
|
|
24
|
+
<Outlet />
|
|
25
|
+
</main>
|
|
26
|
+
</>
|
|
27
|
+
)
|
|
28
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { appRoutes, createAppRouter, PATHS, type AppRoutesOptions, type Guard, type RouterKind } from './routes'
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/* Header and navigation. Only uses the design tokens of vite-react-base. */
|
|
2
|
+
.topbar {
|
|
3
|
+
display: flex;
|
|
4
|
+
align-items: center;
|
|
5
|
+
gap: var(--space-4);
|
|
6
|
+
padding: var(--space-2) var(--space-3);
|
|
7
|
+
border-bottom: 1px solid var(--color-border);
|
|
8
|
+
background: var(--color-surface);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
.topbar-brand { color: var(--color-text); }
|
|
12
|
+
|
|
13
|
+
.topbar-nav { display: flex; gap: var(--space-3); flex: 1; }
|
|
14
|
+
|
|
15
|
+
.topbar-nav a {
|
|
16
|
+
color: var(--color-muted);
|
|
17
|
+
text-decoration: none;
|
|
18
|
+
padding: var(--space-1) 0;
|
|
19
|
+
border-bottom: 2px solid transparent;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
.topbar-nav a.active {
|
|
23
|
+
color: var(--color-text);
|
|
24
|
+
border-bottom-color: var(--color-primary);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
.topbar-nav a:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
|
|
28
|
+
|
|
29
|
+
.topbar-actions { display: flex; gap: var(--space-2); }
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { render, screen } from '@testing-library/react'
|
|
2
|
+
import userEvent from '@testing-library/user-event'
|
|
3
|
+
import type { ReactNode } from 'react'
|
|
4
|
+
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router'
|
|
5
|
+
import { describe, expect, it } from 'vitest'
|
|
6
|
+
|
|
7
|
+
import { createFakeApi } from '../api/fake/fake-api'
|
|
8
|
+
import { AppProvider } from '../app-context'
|
|
9
|
+
import { appRoutes, PATHS, type AppRoutesOptions } from './routes'
|
|
10
|
+
|
|
11
|
+
function mount(path: string, options: AppRoutesOptions = {}) {
|
|
12
|
+
const router = createMemoryRouter(appRoutes(options), { initialEntries: [path] })
|
|
13
|
+
render(
|
|
14
|
+
<AppProvider services={{ api: createFakeApi({ latencyMs: 0 }) }}>
|
|
15
|
+
<RouterProvider router={router} />
|
|
16
|
+
</AppProvider>,
|
|
17
|
+
)
|
|
18
|
+
return router
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('app routes', () => {
|
|
22
|
+
it('renders the home under the layout and navigates with the links', async () => {
|
|
23
|
+
const router = mount(PATHS.home)
|
|
24
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Demo User' })).toBeTruthy()
|
|
25
|
+
await userEvent.click(screen.getByRole('link', { name: 'Ajustes' }))
|
|
26
|
+
expect(await screen.findByRole('heading', { name: 'Ajustes' })).toBeTruthy()
|
|
27
|
+
expect(router.state.location.pathname).toBe(PATHS.settings)
|
|
28
|
+
expect(screen.getByRole('link', { name: 'Ajustes' }).className).toContain('active')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('loads a lazy screen by URL', async () => {
|
|
32
|
+
mount(PATHS.settings)
|
|
33
|
+
expect(await screen.findByRole('heading', { name: 'Ajustes' })).toBeTruthy()
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('shows a 404 with a way back', async () => {
|
|
37
|
+
mount('/nope')
|
|
38
|
+
expect(await screen.findByRole('heading', { name: 'Página no encontrada' })).toBeTruthy()
|
|
39
|
+
await userEvent.click(screen.getByRole('link', { name: 'Volver al inicio' }))
|
|
40
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Demo User' })).toBeTruthy()
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('runs every screen through the guard and renders the header actions', async () => {
|
|
44
|
+
const Guard = ({ children }: { children: ReactNode }) => <div data-testid="guarded">{children}</div>
|
|
45
|
+
mount(PATHS.settings, { guard: Guard, headerActions: <button>Salir</button> })
|
|
46
|
+
expect(await screen.findByRole('heading', { name: 'Ajustes' })).toBeTruthy()
|
|
47
|
+
expect(screen.getByTestId('guarded')).toBeTruthy()
|
|
48
|
+
expect(screen.getByRole('button', { name: 'Salir' })).toBeTruthy()
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('a screen that throws shows the error screen with only the error class', async () => {
|
|
52
|
+
const Boom = () => {
|
|
53
|
+
throw new Error('secret internals')
|
|
54
|
+
}
|
|
55
|
+
const [root] = appRoutes()
|
|
56
|
+
const router = createMemoryRouter([{ ...root, index: undefined, children: [{ index: true, element: <Boom /> }] } as RouteObject], {
|
|
57
|
+
initialEntries: [PATHS.home],
|
|
58
|
+
})
|
|
59
|
+
render(<RouterProvider router={router} />)
|
|
60
|
+
const alert = await screen.findByRole('alert')
|
|
61
|
+
expect(alert.textContent).toContain('Algo ha fallado')
|
|
62
|
+
expect(alert.textContent).toContain('Error')
|
|
63
|
+
expect(alert.textContent).not.toContain('secret internals')
|
|
64
|
+
})
|
|
65
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The route table of the app: one place, declarative (react-router in data mode).
|
|
3
|
+
* `guard` and `headerActions` come from outside (main.tsx): the router does not know the auth capability,
|
|
4
|
+
* it only receives a component that decides whether `children` may render.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { Fragment, type ComponentType, type ReactNode } from 'react'
|
|
8
|
+
import { createBrowserRouter, createHashRouter, type RouteObject } from 'react-router'
|
|
9
|
+
|
|
10
|
+
import { HomeScreen } from '../screens/HomeScreen'
|
|
11
|
+
import { ErrorScreen } from './ErrorScreen'
|
|
12
|
+
import { Layout } from './Layout'
|
|
13
|
+
import { NotFoundScreen } from './NotFoundScreen'
|
|
14
|
+
|
|
15
|
+
export type Guard = ComponentType<{ children: ReactNode }>
|
|
16
|
+
|
|
17
|
+
export type AppRoutesOptions = {
|
|
18
|
+
/** Wraps every screen under the layout (e.g. `RequireSession`). Default: no guard. */
|
|
19
|
+
guard?: Guard
|
|
20
|
+
/** Rendered at the right of the header (e.g. a sign-out button). */
|
|
21
|
+
headerActions?: ReactNode
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Paths as constants: links and tests never retype a string. */
|
|
25
|
+
export const PATHS = {
|
|
26
|
+
home: '/',
|
|
27
|
+
settings: '/settings',
|
|
28
|
+
} as const
|
|
29
|
+
|
|
30
|
+
export function appRoutes({ guard: Guard = Fragment, headerActions }: AppRoutesOptions = {}): RouteObject[] {
|
|
31
|
+
return [
|
|
32
|
+
{
|
|
33
|
+
path: PATHS.home,
|
|
34
|
+
element: (
|
|
35
|
+
<Guard>
|
|
36
|
+
<Layout actions={headerActions} />
|
|
37
|
+
</Guard>
|
|
38
|
+
),
|
|
39
|
+
errorElement: <ErrorScreen />,
|
|
40
|
+
children: [
|
|
41
|
+
{ index: true, element: <HomeScreen /> },
|
|
42
|
+
// Lazy screen: its own chunk, downloaded on first visit. Add yours the same way.
|
|
43
|
+
{ path: PATHS.settings, lazy: async () => ({ Component: (await import('../screens/SettingsScreen')).SettingsScreen }) },
|
|
44
|
+
{ path: '*', element: <NotFoundScreen /> },
|
|
45
|
+
],
|
|
46
|
+
},
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type RouterKind = 'browser' | 'hash'
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* `browser` = clean URLs; the server must answer index.html for every path (Vite does, so does any SPA host).
|
|
54
|
+
* `hash` = `#/settings`; works on a static host with no fallback.
|
|
55
|
+
*/
|
|
56
|
+
export function createAppRouter(options: AppRoutesOptions & { kind?: RouterKind } = {}) {
|
|
57
|
+
const create = options.kind === 'hash' ? createHashRouter : createBrowserRouter
|
|
58
|
+
return create(appRoutes(options))
|
|
59
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Example of a lazy screen (see router/routes.tsx). Replace it with yours. */
|
|
2
|
+
|
|
3
|
+
export function SettingsScreen() {
|
|
4
|
+
return (
|
|
5
|
+
<section className="card">
|
|
6
|
+
<h1>Ajustes</h1>
|
|
7
|
+
<p className="muted">Esta pantalla se descarga la primera vez que se visita.</p>
|
|
8
|
+
</section>
|
|
9
|
+
)
|
|
10
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# react-supabase-auth
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para **el login del frontend con Supabase Auth** (correo y contraseña): sesión guardada, token Bearer renovado solo, pantalla de login, guard que la enseña hasta que hay sesión y botón de salir. El proveedor se elige en `.env`: `supabase` en real y `fake` para desarrollar, demos y e2e sin Supabase.
|
|
6
|
+
|
|
7
|
+
No cubre magic link, OAuth, registro ni invitaciones: supabase-js los ofrece, pero cada uno es un flujo con callback y no estaban en más de un proyecto de origen.
|
|
8
|
+
|
|
9
|
+
**Requiere `vite-react-base`** (usa su `TokenProvider` y sus variables de diseño). **Usa `react-app-router`** (le pasa `RequireSession` como guard) y `playwright-e2e` (entra con la cuenta del fake).
|
|
10
|
+
|
|
11
|
+
## Qué incluye
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
src/auth/
|
|
15
|
+
auth.ts Auth (el contrato): getSession · signIn · signOut · refresh · onChange · AuthError(code) · tokenProviderOf(auth)
|
|
16
|
+
settings.ts bloque AuthSettings: authSettings(import.meta.env) → VITE_AUTH_PROVIDER (obligatorio), VITE_SUPABASE_URL, VITE_SUPABASE_ANON_KEY
|
|
17
|
+
supabase-auth.ts createSupabaseAuth({url, anonKey, fetcher?}): supabase-js con sesión persistida y refresh automático
|
|
18
|
+
fake-auth.ts createFakeAuth({users?}): en memoria, sesión en localStorage; cuenta demo@example.com / demo
|
|
19
|
+
make-auth.ts makeAuth(settings): factory con import() por proveedor (supabase-js es un chunk aparte)
|
|
20
|
+
session-store.ts createSessionStore(auth): loading → signed_in | signed_out (+ expired), sin React
|
|
21
|
+
session-context.tsx SessionProvider · useSession() · RequireSession (el guard: login hasta que hay sesión)
|
|
22
|
+
LoginScreen.tsx correo + contraseña, mensaje por código, "Tu sesión ha caducado"
|
|
23
|
+
SignOutButton.tsx "Salir (correo)"
|
|
24
|
+
auth.css solo usa las variables de vite-react-base
|
|
25
|
+
index.ts
|
|
26
|
+
fake-gotrue.ts Supabase Auth a nivel HTTP para tests: corre el supabase-js real, solo se sustituye fetch
|
|
27
|
+
auth.test.ts 18 tests: conformidad de los dos proveedores, qué se envía a GoTrue, refresh revocado, 429/5xx, store, settings, factory
|
|
28
|
+
session.test.tsx 4 tests: login → contenido, contraseña mal, sesión guardada, caducidad
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Decisiones
|
|
32
|
+
|
|
33
|
+
- **`Auth` es un tipo con dos implementaciones** (el patrón de `Api` en la base): `createSupabaseAuth` y `createFakeAuth`. `makeAuth` elige por `VITE_AUTH_PROVIDER` y un valor desconocido falla nombrándolo. Las dos van con `import()`: la build en modo fake no descarga supabase-js (217 kB) y la real no lleva el fake.
|
|
34
|
+
- **supabase-js, no la API REST a mano.** Hablar con GoTrue por `fetch` obliga a gestionar el refresh a mano (renovar 60 s antes, una sola promesa en vuelo, borrar la sesión si el refresh da 4xx). supabase-js hace todo eso con `persistSession` y `autoRefreshToken`; la receta solo añade el camino explícito `refresh()` para el 401 del cliente HTTP.
|
|
35
|
+
- **La sesión vive fuera de React** (`session-store.ts`). `main.tsx` lo construye una vez, le da `expire` al cliente HTTP (`onSessionExpired`) y el store a `<SessionProvider>`. Así el 401 que sobrevive al refresh (la "sesión zombie") vuelve al login con "Tu sesión ha caducado" sin que el cliente HTTP sepa nada de React.
|
|
36
|
+
- **El guard no conoce el router.** `RequireSession` pinta el login *en el sitio* del contenido y conserva la URL: tras entrar, el usuario ve lo que pidió. Con `react-app-router` se pasa como `guard` y protege todas las pantallas.
|
|
37
|
+
- **Solo el código del error llega a la pantalla.** `AuthError.code` ∈ `invalid_credentials | email_not_confirmed | rate_limited | unavailable`; el mensaje de supabase-js queda en `cause`.
|
|
38
|
+
- **`signOut` borra lo local primero** (`scope: 'local'`) y avisar a GoTrue es cortesía: si no hay red, se sale igual.
|
|
39
|
+
- **Un refresh rechazado cierra la sesión; un fallo de red no.** `refreshSession` con `AuthApiError` (token revocado, contraseña cambiada) borra la sesión; un 5xx o sin conexión devuelve `null` sin tocarla.
|
|
40
|
+
- **Rol y tenant no se leen del JWT.** Los proyectos de origen no decodifican claims en el navegador: el rol sale de `GET /me` (la `Identity` de la base) y el tenant lo saca el backend del token (`auth-verifier`). El frontend solo necesita `user.id` y `email`.
|
|
41
|
+
- **El fake persiste en localStorage**, como el real: una recarga mantiene la sesión y el e2e puede probarlo. Una cuenta por defecto; `users` para más.
|
|
42
|
+
- **Tests a nivel HTTP** (`fake-gotrue.ts`, como `FakeOpenAI` en `voice-providers`): corre el supabase-js real y se comprueba el grant, la `apikey` y el refresh token que se envían, y cómo se tratan las respuestas reales (`error_code`).
|
|
43
|
+
|
|
44
|
+
## Cómo adaptarla
|
|
45
|
+
|
|
46
|
+
1. Copia `files/` encima del frontend de `vite-react-base` y ejecuta `npm install @supabase/supabase-js@^2.119.0`.
|
|
47
|
+
2. **Settings:** en `config.ts` añade el bloque, igual que un `Settings(AuthSettings, ...)` del backend:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { authSettings } from './auth/settings'
|
|
51
|
+
export const CONFIG = { ..., auth: authSettings(import.meta.env) } as const
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
En `vite-env.d.ts` declara `VITE_AUTH_PROVIDER`, `VITE_SUPABASE_URL` y `VITE_SUPABASE_ANON_KEY` (las tres `?: string`). En `.env`: `VITE_AUTH_PROVIDER=supabase`, la URL del proyecto y la anon key (son públicas: RLS protege los datos). En `.env.fake`: `VITE_AUTH_PROVIDER=fake`.
|
|
55
|
+
3. **Arranque** (`main.tsx`):
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
const auth = await makeAuth(CONFIG.auth)
|
|
59
|
+
const session = createSessionStore(auth)
|
|
60
|
+
const api = await makeApi({ ..., tokens: tokenProviderOf(auth), onSessionExpired: session.expire })
|
|
61
|
+
// render:
|
|
62
|
+
<SessionProvider store={session}>
|
|
63
|
+
<RequireSession><App services={{ api }} /></RequireSession>
|
|
64
|
+
</SessionProvider>
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Con `react-app-router`: `createAppRouter({ guard: RequireSession, headerActions: <SignOutButton /> })` y `<App services router>` dentro de `<SessionProvider>`.
|
|
68
|
+
4. **Pantallas:** `useSession()` da `status`, `session.user`, `signOut`. El backend sigue siendo quien dice quién eres (`api.me()`).
|
|
69
|
+
5. **Proveedor nuevo** (JWT propio, Auth0): implementa `Auth`, añade el valor en `AuthProvider` y el caso en `makeAuth`, y pásalo por la batería `conformance(...)` de `auth.test.ts`.
|
|
70
|
+
6. Para comprobarla: `npm run typecheck && npm test` (22 tests de esta receta, 45 con la base).
|
|
71
|
+
|
|
72
|
+
**Dependencias:** `@supabase/supabase-js` (probado con 2.119).
|
|
73
|
+
|
|
74
|
+
## Origen
|
|
75
|
+
|
|
76
|
+
- Probado en producción: `Api` con sesión dentro (`hasSession`, `login`, `logout`), refresh una vez en 401 y después `onSessionExpired`, login en el sitio del contenido, "Tu sesión ha caducado", salir borrando lo local y avisando por cortesía, un refresh con 4xx cierra la sesión y con 5xx no, fake de auth con contraseña incorrecta y sesión persistida, cliente probado inyectando `fetcher` y `storage`; supabase-js con `getSession` + `onAuthStateChange`, `signInWithPassword`, errores como claves estables, 401 con sesión viva = cerrar sesión, guard que espera la comprobación inicial; tokens en localStorage validados con `getMe()` al arrancar.
|
|
77
|
+
- Nuevo en esta receta: `session-store.ts` fuera de React, `fake-gotrue.ts` y el proveedor elegido en settings, siguiendo la base.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Email + password. Messages by `AuthError.code`, never the provider's text. */
|
|
2
|
+
|
|
3
|
+
import { useState, type FormEvent } from 'react'
|
|
4
|
+
|
|
5
|
+
import { AuthError, type AuthErrorCode } from './auth'
|
|
6
|
+
import { useSession } from './session-context'
|
|
7
|
+
import './auth.css'
|
|
8
|
+
|
|
9
|
+
const MESSAGES: Record<AuthErrorCode, string> = {
|
|
10
|
+
invalid_credentials: 'No coinciden el correo y la contraseña',
|
|
11
|
+
email_not_confirmed: 'Confirma tu correo antes de entrar',
|
|
12
|
+
rate_limited: 'Demasiados intentos. Espera un momento',
|
|
13
|
+
unavailable: 'No se pudo iniciar sesión. Inténtalo de nuevo',
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function LoginScreen() {
|
|
17
|
+
const { signIn, expired } = useSession()
|
|
18
|
+
const [email, setEmail] = useState('')
|
|
19
|
+
const [password, setPassword] = useState('')
|
|
20
|
+
const [sending, setSending] = useState(false)
|
|
21
|
+
const [error, setError] = useState<string | null>(null)
|
|
22
|
+
|
|
23
|
+
async function submit(event: FormEvent) {
|
|
24
|
+
event.preventDefault()
|
|
25
|
+
setSending(true)
|
|
26
|
+
setError(null)
|
|
27
|
+
try {
|
|
28
|
+
await signIn({ email, password })
|
|
29
|
+
} catch (reason) {
|
|
30
|
+
setError(reason instanceof AuthError ? MESSAGES[reason.code] : MESSAGES.unavailable)
|
|
31
|
+
setSending(false)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return (
|
|
36
|
+
<form className="card login" onSubmit={(event) => void submit(event)} aria-labelledby="login-title">
|
|
37
|
+
<h1 id="login-title">Entrar</h1>
|
|
38
|
+
{expired && <p className="muted">Tu sesión ha caducado</p>}
|
|
39
|
+
<label className="field">
|
|
40
|
+
Correo
|
|
41
|
+
<input type="email" name="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
|
42
|
+
</label>
|
|
43
|
+
<label className="field">
|
|
44
|
+
Contraseña
|
|
45
|
+
<input
|
|
46
|
+
type="password"
|
|
47
|
+
name="password"
|
|
48
|
+
autoComplete="current-password"
|
|
49
|
+
required
|
|
50
|
+
value={password}
|
|
51
|
+
onChange={(e) => setPassword(e.target.value)}
|
|
52
|
+
/>
|
|
53
|
+
</label>
|
|
54
|
+
{error && (
|
|
55
|
+
<p role="alert" className="login-error">
|
|
56
|
+
{error}
|
|
57
|
+
</p>
|
|
58
|
+
)}
|
|
59
|
+
<button className="button" type="submit" disabled={sending}>
|
|
60
|
+
{sending ? 'Entrando…' : 'Entrar'}
|
|
61
|
+
</button>
|
|
62
|
+
</form>
|
|
63
|
+
)
|
|
64
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { useSession } from './session-context'
|
|
2
|
+
|
|
3
|
+
/** Shows who is signed in and signs out. Put it wherever the layout has room (header, menu). */
|
|
4
|
+
export function SignOutButton() {
|
|
5
|
+
const { session, signOut } = useSession()
|
|
6
|
+
if (!session) return null
|
|
7
|
+
return (
|
|
8
|
+
<button className="button" onClick={() => void signOut()}>
|
|
9
|
+
Salir ({session.user.email})
|
|
10
|
+
</button>
|
|
11
|
+
)
|
|
12
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/* Login form. Only uses the design tokens of vite-react-base. */
|
|
2
|
+
.login {
|
|
3
|
+
max-width: 360px;
|
|
4
|
+
margin: var(--space-4) auto;
|
|
5
|
+
display: grid;
|
|
6
|
+
gap: var(--space-3);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
.field {
|
|
10
|
+
display: grid;
|
|
11
|
+
gap: var(--space-1);
|
|
12
|
+
font-size: 0.9rem;
|
|
13
|
+
color: var(--color-muted);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
.field input {
|
|
17
|
+
font: inherit;
|
|
18
|
+
color: var(--color-text);
|
|
19
|
+
background: var(--color-bg);
|
|
20
|
+
border: 1px solid var(--color-border);
|
|
21
|
+
border-radius: var(--radius);
|
|
22
|
+
padding: var(--space-2) var(--space-3);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
.field input:focus {
|
|
26
|
+
outline: 2px solid var(--color-primary);
|
|
27
|
+
outline-offset: 1px;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.login-error {
|
|
31
|
+
color: var(--color-danger);
|
|
32
|
+
margin: 0;
|
|
33
|
+
}
|