From 3b37368e7d5f04f2e51f381d6c818f53e7e54250 Mon Sep 17 00:00:00 2001 From: Zaine Date: Fri, 26 Jun 2026 09:26:50 +0100 Subject: [PATCH] initial 2 --- apps/web | 1 - apps/web/.gitignore | 41 ++ apps/web/AGENTS.md | 5 + apps/web/CLAUDE.md | 1 + apps/web/Dockerfile | 39 ++ apps/web/README.md | 36 ++ apps/web/docs/ARCHITECTURE.md | 66 +++ apps/web/docs/KNOWN-ISSUES.md | 41 ++ apps/web/docs/REFACTOR-LOG.md | 74 +++ apps/web/eslint.config.mjs | 18 + apps/web/next.config.ts | 25 + apps/web/package.json | 47 ++ apps/web/postcss.config.mjs | 7 + apps/web/public/file.svg | 1 + apps/web/public/globe.svg | 1 + apps/web/public/icons/icon.svg | 5 + apps/web/public/manifest.json | 16 + apps/web/public/next.svg | 1 + apps/web/public/sw.js | 2 + apps/web/public/vercel.svg | 1 + apps/web/public/window.svg | 1 + apps/web/src/app/achievements/page.tsx | 58 +++ apps/web/src/app/api/achievements/route.ts | 23 + .../src/app/api/actions/[id]/undo/route.ts | 16 + apps/web/src/app/api/actions/recent/route.ts | 11 + .../adventures/[date]/apply-template/route.ts | 15 + .../api/adventures/[date]/items/[id]/route.ts | 29 ++ .../app/api/adventures/[date]/items/route.ts | 15 + .../api/adventures/[date]/quick-log/route.ts | 15 + .../api/adventures/[date]/rest-day/route.ts | 15 + .../src/app/api/adventures/[date]/route.ts | 32 ++ .../api/adventures/[date]/todos/[id]/route.ts | 26 ++ .../app/api/adventures/[date]/todos/route.ts | 15 + .../src/app/api/adventures/catch-up/route.ts | 11 + apps/web/src/app/api/ai/chat/knows/route.ts | 10 + .../app/api/ai/chat/sessions/[id]/route.ts | 40 ++ .../web/src/app/api/ai/chat/sessions/route.ts | 19 + apps/web/src/app/api/ai/config/route.ts | 33 ++ .../src/app/api/ai/context/preview/route.ts | 19 + apps/web/src/app/api/ai/health/route.ts | 21 + apps/web/src/app/api/ai/memory/[id]/route.ts | 40 ++ .../src/app/api/ai/memory/learning/route.ts | 21 + apps/web/src/app/api/ai/memory/reset/route.ts | 13 + apps/web/src/app/api/ai/memory/route.ts | 32 ++ .../memory/suggestions/[id]/accept/route.ts | 15 + .../memory/suggestions/[id]/ignore/route.ts | 15 + .../memory/suggestions/[id]/reject/route.ts | 15 + .../app/api/ai/memory/suggestions/route.ts | 13 + .../api/ai/memory/summary/rebuild/route.ts | 54 +++ .../src/app/api/ai/memory/summary/route.ts | 34 ++ apps/web/src/app/api/ai/models/route.ts | 23 + .../api/ai/suggestions/[id]/dismiss/route.ts | 15 + apps/web/src/app/api/ai/suggestions/route.ts | 26 ++ .../src/app/api/ai/templates/[key]/route.ts | 64 +++ apps/web/src/app/api/ai/templates/route.ts | 12 + apps/web/src/app/api/auth/login/route.ts | 28 ++ .../src/app/api/books/[id]/log-pages/route.ts | 15 + apps/web/src/app/api/books/[id]/route.ts | 15 + apps/web/src/app/api/books/route.ts | 18 + apps/web/src/app/api/cartographer/route.ts | 10 + apps/web/src/app/api/cron/route.ts | 42 ++ apps/web/src/app/api/dashboard/route.ts | 8 + .../src/app/api/explorations/[id]/route.ts | 29 ++ apps/web/src/app/api/explorations/route.ts | 33 ++ apps/web/src/app/api/export/json/route.ts | 25 + apps/web/src/app/api/library/books/route.ts | 31 ++ .../src/app/api/library/cover/[id]/route.ts | 30 ++ .../app/api/library/progress/[id]/route.ts | 23 + apps/web/src/app/api/library/status/route.ts | 10 + .../src/app/api/reflections/[date]/route.ts | 26 ++ .../src/app/api/reviews/[weekStart]/route.ts | 37 ++ .../app/api/settings/day-boundary/route.ts | 20 + apps/web/src/app/api/settings/route.ts | 58 +++ apps/web/src/app/api/stats/[domain]/route.ts | 15 + apps/web/src/app/api/teacher/[id]/route.ts | 31 ++ apps/web/src/app/api/teacher/route.ts | 34 ++ .../src/app/api/templates/[id]/items/route.ts | 32 ++ apps/web/src/app/api/templates/[id]/route.ts | 47 ++ apps/web/src/app/api/templates/route.ts | 19 + apps/web/src/app/api/themes/route.ts | 6 + apps/web/src/app/cartographer/page.tsx | 311 +++++++++++++ apps/web/src/app/favicon.ico | Bin 0 -> 25931 bytes apps/web/src/app/globals.css | 215 +++++++++ apps/web/src/app/layout.tsx | 44 ++ apps/web/src/app/library/page.tsx | 425 +++++++++++++++++ apps/web/src/app/login/page.tsx | 48 ++ apps/web/src/app/mentor/page.tsx | 236 ++++++++++ apps/web/src/app/page.tsx | 122 +++++ apps/web/src/app/review/page.tsx | 168 +++++++ apps/web/src/app/settings/page.tsx | 310 +++++++++++++ apps/web/src/app/statistics/page.tsx | 129 ++++++ apps/web/src/app/teacher/page.tsx | 328 ++++++++++++++ apps/web/src/app/yearly/page.tsx | 57 +++ .../src/components/charts/simple-charts.tsx | 77 ++++ .../features/adventure-item-row.tsx | 147 ++++++ .../src/components/features/catch-up-card.tsx | 42 ++ .../components/features/character-card.tsx | 80 ++++ .../components/features/checklist-item.tsx | 35 ++ .../components/features/daily-reflection.tsx | 121 +++++ .../src/components/features/day-switcher.tsx | 52 +++ .../src/components/features/mentor-panel.tsx | 128 ++++++ .../components/features/quick-log-panel.tsx | 115 +++++ .../components/features/sidebar-widgets.tsx | 99 ++++ .../components/features/template-editor.tsx | 313 +++++++++++++ .../components/features/todays-adventure.tsx | 245 ++++++++++ apps/web/src/components/layout/app-shell.tsx | 129 ++++++ apps/web/src/components/providers.tsx | 22 + apps/web/src/components/retro/overlays.tsx | 98 ++++ apps/web/src/components/retro/skill-bar.tsx | 22 + .../settings/action-history-panel.tsx | 67 +++ .../components/settings/ai-config-panel.tsx | 194 ++++++++ .../components/settings/ai-health-panel.tsx | 114 +++++ .../components/settings/ai-memory-panel.tsx | 365 +++++++++++++++ .../settings/prompt-template-editor.tsx | 189 ++++++++ .../src/components/theme/theme-gallery.tsx | 66 +++ .../src/components/theme/theme-provider.tsx | 88 ++++ apps/web/src/components/ui/page-states.tsx | 7 + apps/web/src/components/ui/retro-window.tsx | 16 + apps/web/src/components/ui/tab-toggle.tsx | 21 + apps/web/src/features/adventure/api.ts | 67 +++ apps/web/src/features/undo/api.ts | 8 + apps/web/src/hooks/useActionToastHandlers.ts | 10 + apps/web/src/hooks/useAdventureMutations.ts | 126 ++++++ apps/web/src/hooks/useUndoMutation.ts | 19 + apps/web/src/lib/ai/ai-normalize.test.ts | 51 +++ apps/web/src/lib/ai/ai-normalize.ts | 124 +++++ apps/web/src/lib/ai/model-resolve.test.ts | 38 ++ apps/web/src/lib/ai/model-resolve.ts | 26 ++ apps/web/src/lib/ai/parse-json.test.ts | 12 + apps/web/src/lib/ai/parse-json.ts | 8 + apps/web/src/lib/ai/prompts/defaults.ts | 145 ++++++ apps/web/src/lib/ai/prompts/render.test.ts | 25 + apps/web/src/lib/ai/prompts/render.ts | 41 ++ apps/web/src/lib/ai/provider-registry.ts | 38 ++ apps/web/src/lib/ai/providers/ollama.ts | 147 ++++++ .../src/lib/ai/providers/openai-compatible.ts | 127 ++++++ apps/web/src/lib/ai/types.test.ts | 16 + apps/web/src/lib/ai/types.ts | 108 +++++ apps/web/src/lib/api-client.ts | 32 ++ apps/web/src/lib/api.ts | 24 + apps/web/src/lib/auth.ts | 37 ++ apps/web/src/lib/config/constants.ts | 48 ++ apps/web/src/lib/config/env.ts | 61 +++ apps/web/src/lib/config/index.ts | 10 + apps/web/src/lib/dates-client.ts | 25 + apps/web/src/lib/dates.ts | 45 ++ apps/web/src/lib/db.ts | 2 + apps/web/src/lib/errors/index.ts | 43 ++ apps/web/src/lib/reflection-utils.ts | 20 + .../adventure-templates.repository.ts | 26 ++ apps/web/src/lib/repositories/index.ts | 3 + .../lib/repositories/settings.repository.ts | 29 ++ .../lib/repositories/teacher.repository.ts | 51 +++ apps/web/src/lib/services/achievements.ts | 93 ++++ apps/web/src/lib/services/action-events.ts | 73 +++ apps/web/src/lib/services/adventure.ts | 4 + .../lib/services/adventure/checklist-value.ts | 4 + apps/web/src/lib/services/adventure/daily.ts | 351 ++++++++++++++ .../services/adventure/derive-state.test.ts | 37 ++ .../lib/services/adventure/derive-state.ts | 32 ++ apps/web/src/lib/services/adventure/index.ts | 4 + .../lib/services/adventure/materialization.ts | 148 ++++++ .../lib/services/adventure/scoring-helpers.ts | 11 + .../web/src/lib/services/adventure/scoring.ts | 100 ++++ .../adventure/template-matching.test.ts | 49 ++ .../services/adventure/template-matching.ts | 23 + .../src/lib/services/adventure/templates.ts | 192 ++++++++ apps/web/src/lib/services/ai-chat.ts | 154 +++++++ apps/web/src/lib/services/ai-config.ts | 116 +++++ apps/web/src/lib/services/ai-context.test.ts | 33 ++ apps/web/src/lib/services/ai-context.ts | 274 +++++++++++ apps/web/src/lib/services/ai-memory.test.ts | 13 + apps/web/src/lib/services/ai-memory.ts | 321 +++++++++++++ apps/web/src/lib/services/ai-teacher.test.ts | 163 +++++++ apps/web/src/lib/services/ai-templates.ts | 162 +++++++ apps/web/src/lib/services/ai.ts | 427 ++++++++++++++++++ apps/web/src/lib/services/calibre-reading.ts | 103 +++++ apps/web/src/lib/services/calibre.ts | 268 +++++++++++ apps/web/src/lib/services/cartographer.ts | 43 ++ apps/web/src/lib/services/catch-up.ts | 61 +++ apps/web/src/lib/services/dashboard.ts | 233 ++++++++++ apps/web/src/lib/services/day-boundary.ts | 15 + .../web/src/lib/services/explorations.test.ts | 76 ++++ apps/web/src/lib/services/explorations.ts | 297 ++++++++++++ .../web/src/lib/services/memory-extraction.ts | 89 ++++ apps/web/src/lib/services/quick-log.ts | 78 ++++ apps/web/src/lib/services/reading.ts | 210 +++++++++ .../web/src/lib/services/reading/log-pages.ts | 42 ++ apps/web/src/lib/services/reflection.test.ts | 74 +++ apps/web/src/lib/services/reflection.ts | 126 ++++++ apps/web/src/lib/services/teacher.ts | 57 +++ apps/web/src/lib/services/theme-migration.ts | 30 ++ apps/web/src/lib/services/undo.test.ts | 41 ++ apps/web/src/lib/services/undo.ts | 235 ++++++++++ apps/web/src/lib/services/user.ts | 44 ++ apps/web/src/lib/services/xp.ts | 147 ++++++ apps/web/src/lib/types/jsonb.ts | 38 ++ apps/web/src/lib/validation/index.ts | 2 + apps/web/src/lib/validation/parse.ts | 20 + apps/web/src/lib/validation/schemas.test.ts | 39 ++ apps/web/src/lib/validation/schemas.ts | 81 ++++ apps/web/src/middleware.ts | 36 ++ apps/web/src/stores/ui.ts | 39 ++ apps/web/src/sw.ts | 23 + apps/web/src/themes/index.css | 4 + apps/web/src/themes/registry.test.ts | 73 +++ apps/web/src/themes/registry.ts | 115 +++++ apps/web/src/themes/themes/all-themes.css | 285 ++++++++++++ apps/web/src/themes/themes/minimal-dark.css | 32 ++ .../src/themes/themes/windows-xp-light.css | 26 ++ apps/web/src/themes/tokens/semantic.css | 48 ++ apps/web/tsconfig.json | 35 ++ apps/web/vitest.config.ts | 17 + 213 files changed, 14688 insertions(+), 1 deletion(-) delete mode 160000 apps/web create mode 100755 apps/web/.gitignore create mode 100755 apps/web/AGENTS.md create mode 100755 apps/web/CLAUDE.md create mode 100755 apps/web/Dockerfile create mode 100755 apps/web/README.md create mode 100755 apps/web/docs/ARCHITECTURE.md create mode 100755 apps/web/docs/KNOWN-ISSUES.md create mode 100755 apps/web/docs/REFACTOR-LOG.md create mode 100755 apps/web/eslint.config.mjs create mode 100755 apps/web/next.config.ts create mode 100755 apps/web/package.json create mode 100755 apps/web/postcss.config.mjs create mode 100755 apps/web/public/file.svg create mode 100755 apps/web/public/globe.svg create mode 100755 apps/web/public/icons/icon.svg create mode 100755 apps/web/public/manifest.json create mode 100755 apps/web/public/next.svg create mode 100755 apps/web/public/sw.js create mode 100755 apps/web/public/vercel.svg create mode 100755 apps/web/public/window.svg create mode 100755 apps/web/src/app/achievements/page.tsx create mode 100755 apps/web/src/app/api/achievements/route.ts create mode 100755 apps/web/src/app/api/actions/[id]/undo/route.ts create mode 100755 apps/web/src/app/api/actions/recent/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/apply-template/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/items/[id]/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/items/route.ts create mode 100644 apps/web/src/app/api/adventures/[date]/quick-log/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/rest-day/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/todos/[id]/route.ts create mode 100755 apps/web/src/app/api/adventures/[date]/todos/route.ts create mode 100644 apps/web/src/app/api/adventures/catch-up/route.ts create mode 100644 apps/web/src/app/api/ai/chat/knows/route.ts create mode 100644 apps/web/src/app/api/ai/chat/sessions/[id]/route.ts create mode 100644 apps/web/src/app/api/ai/chat/sessions/route.ts create mode 100755 apps/web/src/app/api/ai/config/route.ts create mode 100644 apps/web/src/app/api/ai/context/preview/route.ts create mode 100755 apps/web/src/app/api/ai/health/route.ts create mode 100644 apps/web/src/app/api/ai/memory/[id]/route.ts create mode 100644 apps/web/src/app/api/ai/memory/learning/route.ts create mode 100644 apps/web/src/app/api/ai/memory/reset/route.ts create mode 100644 apps/web/src/app/api/ai/memory/route.ts create mode 100644 apps/web/src/app/api/ai/memory/suggestions/[id]/accept/route.ts create mode 100644 apps/web/src/app/api/ai/memory/suggestions/[id]/ignore/route.ts create mode 100644 apps/web/src/app/api/ai/memory/suggestions/[id]/reject/route.ts create mode 100644 apps/web/src/app/api/ai/memory/suggestions/route.ts create mode 100644 apps/web/src/app/api/ai/memory/summary/rebuild/route.ts create mode 100644 apps/web/src/app/api/ai/memory/summary/route.ts create mode 100755 apps/web/src/app/api/ai/models/route.ts create mode 100755 apps/web/src/app/api/ai/suggestions/[id]/dismiss/route.ts create mode 100755 apps/web/src/app/api/ai/suggestions/route.ts create mode 100755 apps/web/src/app/api/ai/templates/[key]/route.ts create mode 100755 apps/web/src/app/api/ai/templates/route.ts create mode 100755 apps/web/src/app/api/auth/login/route.ts create mode 100755 apps/web/src/app/api/books/[id]/log-pages/route.ts create mode 100755 apps/web/src/app/api/books/[id]/route.ts create mode 100755 apps/web/src/app/api/books/route.ts create mode 100755 apps/web/src/app/api/cartographer/route.ts create mode 100755 apps/web/src/app/api/cron/route.ts create mode 100755 apps/web/src/app/api/dashboard/route.ts create mode 100755 apps/web/src/app/api/explorations/[id]/route.ts create mode 100755 apps/web/src/app/api/explorations/route.ts create mode 100755 apps/web/src/app/api/export/json/route.ts create mode 100755 apps/web/src/app/api/library/books/route.ts create mode 100755 apps/web/src/app/api/library/cover/[id]/route.ts create mode 100755 apps/web/src/app/api/library/progress/[id]/route.ts create mode 100755 apps/web/src/app/api/library/status/route.ts create mode 100755 apps/web/src/app/api/reflections/[date]/route.ts create mode 100755 apps/web/src/app/api/reviews/[weekStart]/route.ts create mode 100644 apps/web/src/app/api/settings/day-boundary/route.ts create mode 100755 apps/web/src/app/api/settings/route.ts create mode 100755 apps/web/src/app/api/stats/[domain]/route.ts create mode 100755 apps/web/src/app/api/teacher/[id]/route.ts create mode 100755 apps/web/src/app/api/teacher/route.ts create mode 100755 apps/web/src/app/api/templates/[id]/items/route.ts create mode 100755 apps/web/src/app/api/templates/[id]/route.ts create mode 100755 apps/web/src/app/api/templates/route.ts create mode 100755 apps/web/src/app/api/themes/route.ts create mode 100755 apps/web/src/app/cartographer/page.tsx create mode 100755 apps/web/src/app/favicon.ico create mode 100755 apps/web/src/app/globals.css create mode 100755 apps/web/src/app/layout.tsx create mode 100755 apps/web/src/app/library/page.tsx create mode 100755 apps/web/src/app/login/page.tsx create mode 100644 apps/web/src/app/mentor/page.tsx create mode 100755 apps/web/src/app/page.tsx create mode 100755 apps/web/src/app/review/page.tsx create mode 100755 apps/web/src/app/settings/page.tsx create mode 100755 apps/web/src/app/statistics/page.tsx create mode 100755 apps/web/src/app/teacher/page.tsx create mode 100755 apps/web/src/app/yearly/page.tsx create mode 100755 apps/web/src/components/charts/simple-charts.tsx create mode 100755 apps/web/src/components/features/adventure-item-row.tsx create mode 100644 apps/web/src/components/features/catch-up-card.tsx create mode 100755 apps/web/src/components/features/character-card.tsx create mode 100755 apps/web/src/components/features/checklist-item.tsx create mode 100755 apps/web/src/components/features/daily-reflection.tsx create mode 100644 apps/web/src/components/features/day-switcher.tsx create mode 100644 apps/web/src/components/features/mentor-panel.tsx create mode 100644 apps/web/src/components/features/quick-log-panel.tsx create mode 100755 apps/web/src/components/features/sidebar-widgets.tsx create mode 100755 apps/web/src/components/features/template-editor.tsx create mode 100755 apps/web/src/components/features/todays-adventure.tsx create mode 100755 apps/web/src/components/layout/app-shell.tsx create mode 100755 apps/web/src/components/providers.tsx create mode 100755 apps/web/src/components/retro/overlays.tsx create mode 100755 apps/web/src/components/retro/skill-bar.tsx create mode 100755 apps/web/src/components/settings/action-history-panel.tsx create mode 100755 apps/web/src/components/settings/ai-config-panel.tsx create mode 100755 apps/web/src/components/settings/ai-health-panel.tsx create mode 100644 apps/web/src/components/settings/ai-memory-panel.tsx create mode 100755 apps/web/src/components/settings/prompt-template-editor.tsx create mode 100755 apps/web/src/components/theme/theme-gallery.tsx create mode 100755 apps/web/src/components/theme/theme-provider.tsx create mode 100755 apps/web/src/components/ui/page-states.tsx create mode 100755 apps/web/src/components/ui/retro-window.tsx create mode 100755 apps/web/src/components/ui/tab-toggle.tsx create mode 100755 apps/web/src/features/adventure/api.ts create mode 100755 apps/web/src/features/undo/api.ts create mode 100755 apps/web/src/hooks/useActionToastHandlers.ts create mode 100755 apps/web/src/hooks/useAdventureMutations.ts create mode 100755 apps/web/src/hooks/useUndoMutation.ts create mode 100755 apps/web/src/lib/ai/ai-normalize.test.ts create mode 100755 apps/web/src/lib/ai/ai-normalize.ts create mode 100755 apps/web/src/lib/ai/model-resolve.test.ts create mode 100755 apps/web/src/lib/ai/model-resolve.ts create mode 100755 apps/web/src/lib/ai/parse-json.test.ts create mode 100755 apps/web/src/lib/ai/parse-json.ts create mode 100755 apps/web/src/lib/ai/prompts/defaults.ts create mode 100755 apps/web/src/lib/ai/prompts/render.test.ts create mode 100755 apps/web/src/lib/ai/prompts/render.ts create mode 100755 apps/web/src/lib/ai/provider-registry.ts create mode 100755 apps/web/src/lib/ai/providers/ollama.ts create mode 100755 apps/web/src/lib/ai/providers/openai-compatible.ts create mode 100755 apps/web/src/lib/ai/types.test.ts create mode 100755 apps/web/src/lib/ai/types.ts create mode 100755 apps/web/src/lib/api-client.ts create mode 100755 apps/web/src/lib/api.ts create mode 100755 apps/web/src/lib/auth.ts create mode 100755 apps/web/src/lib/config/constants.ts create mode 100755 apps/web/src/lib/config/env.ts create mode 100755 apps/web/src/lib/config/index.ts create mode 100755 apps/web/src/lib/dates-client.ts create mode 100755 apps/web/src/lib/dates.ts create mode 100755 apps/web/src/lib/db.ts create mode 100755 apps/web/src/lib/errors/index.ts create mode 100755 apps/web/src/lib/reflection-utils.ts create mode 100755 apps/web/src/lib/repositories/adventure-templates.repository.ts create mode 100755 apps/web/src/lib/repositories/index.ts create mode 100755 apps/web/src/lib/repositories/settings.repository.ts create mode 100755 apps/web/src/lib/repositories/teacher.repository.ts create mode 100755 apps/web/src/lib/services/achievements.ts create mode 100755 apps/web/src/lib/services/action-events.ts create mode 100755 apps/web/src/lib/services/adventure.ts create mode 100755 apps/web/src/lib/services/adventure/checklist-value.ts create mode 100755 apps/web/src/lib/services/adventure/daily.ts create mode 100755 apps/web/src/lib/services/adventure/derive-state.test.ts create mode 100755 apps/web/src/lib/services/adventure/derive-state.ts create mode 100755 apps/web/src/lib/services/adventure/index.ts create mode 100755 apps/web/src/lib/services/adventure/materialization.ts create mode 100755 apps/web/src/lib/services/adventure/scoring-helpers.ts create mode 100755 apps/web/src/lib/services/adventure/scoring.ts create mode 100755 apps/web/src/lib/services/adventure/template-matching.test.ts create mode 100755 apps/web/src/lib/services/adventure/template-matching.ts create mode 100755 apps/web/src/lib/services/adventure/templates.ts create mode 100644 apps/web/src/lib/services/ai-chat.ts create mode 100755 apps/web/src/lib/services/ai-config.ts create mode 100644 apps/web/src/lib/services/ai-context.test.ts create mode 100644 apps/web/src/lib/services/ai-context.ts create mode 100644 apps/web/src/lib/services/ai-memory.test.ts create mode 100644 apps/web/src/lib/services/ai-memory.ts create mode 100755 apps/web/src/lib/services/ai-teacher.test.ts create mode 100755 apps/web/src/lib/services/ai-templates.ts create mode 100755 apps/web/src/lib/services/ai.ts create mode 100755 apps/web/src/lib/services/calibre-reading.ts create mode 100755 apps/web/src/lib/services/calibre.ts create mode 100755 apps/web/src/lib/services/cartographer.ts create mode 100644 apps/web/src/lib/services/catch-up.ts create mode 100755 apps/web/src/lib/services/dashboard.ts create mode 100644 apps/web/src/lib/services/day-boundary.ts create mode 100755 apps/web/src/lib/services/explorations.test.ts create mode 100755 apps/web/src/lib/services/explorations.ts create mode 100644 apps/web/src/lib/services/memory-extraction.ts create mode 100644 apps/web/src/lib/services/quick-log.ts create mode 100755 apps/web/src/lib/services/reading.ts create mode 100755 apps/web/src/lib/services/reading/log-pages.ts create mode 100755 apps/web/src/lib/services/reflection.test.ts create mode 100755 apps/web/src/lib/services/reflection.ts create mode 100755 apps/web/src/lib/services/teacher.ts create mode 100755 apps/web/src/lib/services/theme-migration.ts create mode 100755 apps/web/src/lib/services/undo.test.ts create mode 100755 apps/web/src/lib/services/undo.ts create mode 100755 apps/web/src/lib/services/user.ts create mode 100755 apps/web/src/lib/services/xp.ts create mode 100755 apps/web/src/lib/types/jsonb.ts create mode 100755 apps/web/src/lib/validation/index.ts create mode 100755 apps/web/src/lib/validation/parse.ts create mode 100755 apps/web/src/lib/validation/schemas.test.ts create mode 100755 apps/web/src/lib/validation/schemas.ts create mode 100755 apps/web/src/middleware.ts create mode 100755 apps/web/src/stores/ui.ts create mode 100755 apps/web/src/sw.ts create mode 100755 apps/web/src/themes/index.css create mode 100755 apps/web/src/themes/registry.test.ts create mode 100755 apps/web/src/themes/registry.ts create mode 100755 apps/web/src/themes/themes/all-themes.css create mode 100755 apps/web/src/themes/themes/minimal-dark.css create mode 100755 apps/web/src/themes/themes/windows-xp-light.css create mode 100755 apps/web/src/themes/tokens/semantic.css create mode 100755 apps/web/tsconfig.json create mode 100755 apps/web/vitest.config.ts diff --git a/apps/web b/apps/web deleted file mode 160000 index 1916d34..0000000 --- a/apps/web +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1916d348b098debcc2e2383fc95fa6aeb4925f99 diff --git a/apps/web/.gitignore b/apps/web/.gitignore new file mode 100755 index 0000000..5ef6a52 --- /dev/null +++ b/apps/web/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md new file mode 100755 index 0000000..8bd0e39 --- /dev/null +++ b/apps/web/AGENTS.md @@ -0,0 +1,5 @@ + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices. + diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md new file mode 100755 index 0000000..43c994c --- /dev/null +++ b/apps/web/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile new file mode 100755 index 0000000..5f61602 --- /dev/null +++ b/apps/web/Dockerfile @@ -0,0 +1,39 @@ +FROM node:22-alpine AS base + +FROM base AS deps +WORKDIR /app +COPY package.json package-lock.json ./ +COPY apps/web/package.json ./apps/web/ +COPY packages/db/package.json ./packages/db/ +COPY packages/shared/package.json ./packages/shared/ +RUN npm ci && \ + for pkg in \ + lightningcss-linux-x64-gnu \ + lightningcss-linux-x64-musl \ + @tailwindcss/oxide-linux-x64-gnu \ + @tailwindcss/oxide-linux-x64-musl; do \ + if [ -d "node_modules/$pkg" ]; then \ + mkdir -p "apps/web/node_modules/$(dirname "$pkg")"; \ + cp -a "node_modules/$pkg" "apps/web/node_modules/$pkg"; \ + fi; \ + done + +FROM base AS builder +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY --from=deps /app/apps/web/node_modules ./apps/web/node_modules +COPY . . +RUN npm run build -w @adventureos/web + +FROM base AS runner +WORKDIR /app +ENV NODE_ENV=production +RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs +COPY --from=builder /app/apps/web/public ./apps/web/public +COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static +USER nextjs +EXPOSE 3000 +ENV PORT=3000 +ENV HOSTNAME=0.0.0.0 +CMD ["node", "apps/web/server.js"] diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100755 index 0000000..e215bc4 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/apps/web/docs/ARCHITECTURE.md b/apps/web/docs/ARCHITECTURE.md new file mode 100755 index 0000000..0077de4 --- /dev/null +++ b/apps/web/docs/ARCHITECTURE.md @@ -0,0 +1,66 @@ +# AdventureOS Architecture + +AdventureOS is a Next.js 16 full-stack monolith with npm workspaces. + +## Layers + +``` +Browser (React + TanStack Query + Zustand) + ↓ fetch /api/* +Next.js Route Handlers (app/api/**) + ↓ validation (lib/validation) + handleApi (lib/api) +Domain Services (lib/services/**) + ↓ +Repositories (lib/repositories/**) — Drizzle queries +Packages: @adventureos/db, @adventureos/shared +``` + +## Frontend boundaries + +| Path | Responsibility | +|------|----------------| +| `app/*/page.tsx` | Route pages, data fetching via React Query | +| `components/features/` | Domain UI components | +| `components/ui/` | Reusable retro UI primitives | +| `features/*/api.ts` | Typed client fetch wrappers | +| `hooks/` | Shared React hooks (mutations, toasts) | +| `stores/ui.ts` | Ephemeral UI state (toasts, modals) | +| `themes/` | CSS token registry and runtime theme switching | + +## Backend boundaries + +| Path | Responsibility | +|------|----------------| +| `app/api/**/route.ts` | HTTP entry; parse/validate; call services | +| `lib/services/adventure/` | Daily adventures, materialization, scoring, templates | +| `lib/services/reading/` | Shared reading log + action recording | +| `lib/services/ai*.ts` | AI generation, config, memory, chat, context | +| `lib/services/ai-memory.ts` | User-controlled personal AI memories | +| `lib/services/ai-context.ts` | Layered context builder for local models | +| `lib/services/ai-chat.ts` | Mentor chat sessions and messages | +| `lib/services/day-boundary.ts` | Configurable day rollover (after-midnight logging) | +| `lib/repositories/` | Drizzle data access only | +| `lib/config/` | Environment variables and domain constants | +| `lib/errors/` | Typed errors and response mapping | +| `lib/validation/` | Zod request schemas | + +## Data stores + +- **PostgreSQL** — primary app data via Drizzle (`packages/db`) +- **Calibre metadata.db** — read-only SQLite via `better-sqlite3` when configured + +## Service boundaries (rules) + +1. Route handlers must not import Drizzle directly (use services/repositories). +2. Repositories contain no business rules. +3. Services orchestrate repositories, shared math, XP, and action events. +4. Client components use `features/*/api.ts`, not raw fetch scattered in UI. +5. `@adventureos/shared` holds pure domain types and formulas — no I/O. + +## Known gaps + +See [KNOWN-ISSUES.md](./KNOWN-ISSUES.md). + +## Refactor history + +See [REFACTOR-LOG.md](./REFACTOR-LOG.md). diff --git a/apps/web/docs/KNOWN-ISSUES.md b/apps/web/docs/KNOWN-ISSUES.md new file mode 100755 index 0000000..6fb0bce --- /dev/null +++ b/apps/web/docs/KNOWN-ISSUES.md @@ -0,0 +1,41 @@ +# Known Issues + +Issues discovered during refactor audit. Not fixed unless explicitly approved (behaviour preservation). + +## Calibre reading undo is broken + +Both manual (`reading.ts`) and Calibre (`calibre-reading.ts`) use `actionType: "reading.log_pages"`. + +- Manual: `beforeState: { book: { currentPage, status, finishedAt } }`, `entityType: "book"` +- Calibre: `beforeState: { currentPage, status }`, `entityType: "reading_progress"` + +`undo.ts` case `"reading.log_pages"` only restores the manual `books` table. Undoing Calibre page logs will fail or corrupt state. + +## Cron middleware requires session + +`middleware.ts` does not exempt `/api/cron`. External cron with only `x-cron-secret` (per README) receives 401 before the route handler runs. + +## Partial undo coverage + +- `applyTemplateToDate` records no action event +- Template item create/update not recorded (only delete) + +**Fixed:** Reflection saves now record `reflection.save` action events for undo. + +## HTTP status codes + +`handleApi` maps thrown `"Item not found"` to 500, not 404. Normalising would change API contract. + +## Dashboard may ignore Calibre progress + +Stats and dashboard reading metrics query manual `books` / `reading_logs`; Calibre `reading_progress` may not feed scores. + +## Dead / unused code + +- `packages/shared/src/titles.ts` — exported, never imported +- `action_events.inversePatch` — written, never read in undo +- `getCalibreBook()` in calibre.ts — no-op implementation + +## Undo UX inconsistency + +Toast undo (`overlays.tsx`) reloads the page; settings undo invalidates React Query cache. diff --git a/apps/web/docs/REFACTOR-LOG.md b/apps/web/docs/REFACTOR-LOG.md new file mode 100755 index 0000000..0e65ff6 --- /dev/null +++ b/apps/web/docs/REFACTOR-LOG.md @@ -0,0 +1,74 @@ +# Refactor Log + +Internal refactor of AdventureOS. Behaviour, API contracts, and schema preserved unless explicitly noted. + +## Phase 1: Safety baseline + +- Removed debug telemetry from `apps/web/src/app/api/library/books/route.ts` +- Extracted pure adventure helpers: `derive-state.ts`, `template-matching.ts`, `checklist-value.ts` +- Added unit tests for `@adventureos/shared` (xp, levels, scores, chapters) +- Added characterization tests for deriveState, template matching, undo Calibre mismatch +- Replaced misnamed `feature-repair.test.ts` with real tests + +### Manual smoke checklist + +- [ ] Login / logout +- [ ] Command Centre: adventure items, todos, rest day, customize +- [ ] Settings: theme, AI config, templates, action history undo +- [ ] Library: manual books and Calibre (if configured) +- [ ] Cartographer: generate, activate, complete, dismiss +- [ ] Teacher: generate, complete, deep links +- [ ] Undo toast and settings undo + +### Commands run each phase + +```bash +npm run test +npm run lint +npm run build +npm run db:migrate # when DB available +``` + +## Phase 2: Configuration and constants + +- Centralised env reads in `lib/config/` +- Typed constants for settings keys, action types, theme IDs + +## Phase 3: API and data access + +- Zod input validation on teacher, templates, settings routes +- Repository layer for settings, teacher, adventure templates +- Typed errors in `lib/errors/`; `handleApi` uses `mapErrorToResponse` +- Teacher route uses `createTeacherLesson` service + +## Phase 4: Domain/service cleanup + +- Split `adventure.ts` into `lib/services/adventure/{materialization,daily,scoring,templates}.ts` +- Unified Calibre reading log via `lib/services/reading/log-pages.ts` + +## Phase 5: Frontend cleanup + +- Client API: `features/adventure/api.ts`, `features/undo/api.ts`, `lib/api-client.ts` +- Hooks: `useAdventureMutations`, `useUndoMutation`, `useActionToastHandlers` +- Split `todays-adventure.tsx`; extracted `adventure-item-row`, `checklist-item` +- Consolidated AI prompt editors into `AiPromptEditor` +- Shared UI: `RetroWindow`, `TabToggle`, `LoadingState`, `ErrorState` +- Undo toast uses query invalidation (no full page reload) + +## Phase 6: Type safety + +- JSONB interfaces in `lib/types/jsonb.ts` +- Teacher types in `@adventureos/shared` +- Removed unused `@radix-ui/*` dependencies + +## Phase 7: Tests and CI + +- Validation/error unit tests +- `@adventureos/shared` test script and vitest config +- Root `npm run test` runs web + shared +- GitHub Actions CI workflow + +## Phase 8: Documentation + +- [ARCHITECTURE.md](./ARCHITECTURE.md) — layers and service boundaries +- [KNOWN-ISSUES.md](./KNOWN-ISSUES.md) — documented gaps diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs new file mode 100755 index 0000000..05e726d --- /dev/null +++ b/apps/web/eslint.config.mjs @@ -0,0 +1,18 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +const eslintConfig = defineConfig([ + ...nextVitals, + ...nextTs, + // Override default ignores of eslint-config-next. + globalIgnores([ + // Default ignores of eslint-config-next: + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + ]), +]); + +export default eslintConfig; diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts new file mode 100755 index 0000000..97911df --- /dev/null +++ b/apps/web/next.config.ts @@ -0,0 +1,25 @@ +import type { NextConfig } from "next"; +import path from "path"; +import withSerwistInit from "@serwist/next"; + +const withSerwist = withSerwistInit({ + swSrc: "src/sw.ts", + swDest: "public/sw.js", + disable: process.env.NODE_ENV === "development", +}); + +const nextConfig: NextConfig = { + output: "standalone", + outputFileTracingRoot: path.join(__dirname, "../../"), + transpilePackages: ["@adventureos/shared", "@adventureos/db"], + serverExternalPackages: ["postgres"], + webpack: (config) => { + config.resolve.alias = { + ...(config.resolve.alias ?? {}), + "@": path.join(__dirname, "src"), + }; + return config; + }, +}; + +export default withSerwist(nextConfig); diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100755 index 0000000..32b6e44 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,47 @@ +{ + "name": "@adventureos/web", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --webpack", + "build": "next build --webpack", + "start": "next start", + "lint": "eslint", + "test": "vitest run" + }, + "dependencies": { + "@adventureos/db": "*", + "@adventureos/shared": "*", + "@serwist/next": "^9.0.12", + "@tanstack/react-query": "^5.67.2", + "better-sqlite3": "^11.9.1", + "date-fns": "^4.1.0", + "drizzle-orm": "^0.39.3", + "iron-session": "^8.0.4", + "next": "16.2.9", + "postgres": "^3.4.5", + "react": "19.2.4", + "react-dom": "19.2.4", + "serwist": "^9.5.11", + "zod": "^3.25.76", + "zustand": "^5.0.3" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4", + "@types/better-sqlite3": "^7.6.13", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.2.9", + "tailwindcss": "^4", + "typescript": "^5", + "vitest": "^3.2.6" + }, + "optionalDependencies": { + "@tailwindcss/oxide-linux-x64-gnu": "^4.3.1", + "@tailwindcss/oxide-linux-x64-musl": "^4.3.1", + "lightningcss-linux-x64-gnu": "^1.32.0", + "lightningcss-linux-x64-musl": "^1.32.0" + } +} diff --git a/apps/web/postcss.config.mjs b/apps/web/postcss.config.mjs new file mode 100755 index 0000000..61e3684 --- /dev/null +++ b/apps/web/postcss.config.mjs @@ -0,0 +1,7 @@ +const config = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; + +export default config; diff --git a/apps/web/public/file.svg b/apps/web/public/file.svg new file mode 100755 index 0000000..004145c --- /dev/null +++ b/apps/web/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/globe.svg b/apps/web/public/globe.svg new file mode 100755 index 0000000..567f17b --- /dev/null +++ b/apps/web/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/icons/icon.svg b/apps/web/public/icons/icon.svg new file mode 100755 index 0000000..570a1a1 --- /dev/null +++ b/apps/web/public/icons/icon.svg @@ -0,0 +1,5 @@ + + + + A + diff --git a/apps/web/public/manifest.json b/apps/web/public/manifest.json new file mode 100755 index 0000000..10c81d9 --- /dev/null +++ b/apps/web/public/manifest.json @@ -0,0 +1,16 @@ +{ + "name": "AdventureOS", + "short_name": "AdventureOS", + "description": "Your personal command centre for consistency and growth", + "start_url": "/", + "display": "standalone", + "background_color": "#5a8f3e", + "theme_color": "#3A6EA5", + "icons": [ + { + "src": "/icons/icon.svg", + "sizes": "any", + "type": "image/svg+xml" + } + ] +} diff --git a/apps/web/public/next.svg b/apps/web/public/next.svg new file mode 100755 index 0000000..5174b28 --- /dev/null +++ b/apps/web/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js new file mode 100755 index 0000000..c3cb466 --- /dev/null +++ b/apps/web/public/sw.js @@ -0,0 +1,2 @@ +(()=>{"use strict";let e,t,a,s,r,n={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"serwist",runtime:"runtime",suffix:"u">typeof registration?registration.scope:""},i=e=>[n.prefix,e,n.suffix].filter(e=>e&&e.length>0).join("-"),c=e=>e||i(n.precache),o=e=>e||i(n.runtime);var l=class extends Error{details;constructor(e,t){super(((e,...t)=>{let a=e;return t.length>0&&(a+=` :: ${JSON.stringify(t)}`),a})(e,t)),this.name=e,this.details=t}};function h(e){return new Promise(t=>setTimeout(t,e))}let u=new Set;function d(e,t){let a=new URL(e);for(let e of t)a.searchParams.delete(e);return a.href}async function m(e,t,a,s){let r=d(t.url,a);if(t.url===r)return e.match(t,s);let n={...s,ignoreSearch:!0};for(let i of(await e.keys(t,n)))if(r===d(i.url,a))return e.match(i,s)}var f=class{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};let g=async()=>{for(let e of u)await e()},w="-precache-",p=async(e,t=w)=>{let a=(await self.caches.keys()).filter(a=>a.includes(t)&&a.includes(self.registration.scope)&&a!==e);return await Promise.all(a.map(e=>self.caches.delete(e))),a},y=(e,t)=>{let a=t();return e.waitUntil(a),a},_=(e,t)=>t.some(t=>e instanceof t),x=new WeakMap,b=new WeakMap,v=new WeakMap,E={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return x.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return R(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function R(e){if(e instanceof IDBRequest){let t;return t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("success",r),e.removeEventListener("error",n)},r=()=>{t(R(e.result)),s()},n=()=>{a(e.error),s()};e.addEventListener("success",r),e.addEventListener("error",n)}),v.set(t,e),t}if(b.has(e))return b.get(e);let t=function(e){if("function"==typeof e)return(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(q(this),t),R(this.request)}:function(...t){return R(e.apply(q(this),t))};return(e instanceof IDBTransaction&&function(e){if(x.has(e))return;let t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",n),e.removeEventListener("abort",n)},r=()=>{t(),s()},n=()=>{a(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",r),e.addEventListener("error",n),e.addEventListener("abort",n)});x.set(e,t)}(e),_(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,E):e}(e);return t!==e&&(b.set(e,t),v.set(t,e)),t}let q=e=>v.get(e);function S(e,t,{blocked:a,upgrade:s,blocking:r,terminated:n}={}){let i=indexedDB.open(e,t),c=R(i);return s&&i.addEventListener("upgradeneeded",e=>{s(R(i.result),e.oldVersion,e.newVersion,R(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),c.then(e=>{n&&e.addEventListener("close",()=>n()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),c}let D=["get","getKey","getAll","getAllKeys","count"],N=["put","add","delete","clear"],C=new Map;function T(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(C.get(t))return C.get(t);let a=t.replace(/FromIndex$/,""),s=t!==a,r=N.includes(a);if(!(a in(s?IDBIndex:IDBObjectStore).prototype)||!(r||D.includes(a)))return;let n=async function(e,...t){let n=this.transaction(e,r?"readwrite":"readonly"),i=n.store;return s&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&n.done]))[0]};return C.set(t,n),n}E={...e=E,get:(t,a,s)=>T(t,a)||e.get(t,a,s),has:(t,a)=>!!T(t,a)||e.has(t,a)};let P=["continue","continuePrimaryKey","advance"],k={},A=new WeakMap,I=new WeakMap,U={get(e,t){if(!P.includes(t))return e[t];let a=k[t];return a||(a=k[t]=function(...e){A.set(this,I.get(this)[t](...e))}),a}};async function*L(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;let a=new Proxy(t,U);for(I.set(a,t),v.set(a,q(t));t;)yield a,t=await (A.get(a)||t.continue()),A.delete(a)}function F(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&_(e,[IDBIndex,IDBObjectStore])}E={...t=E,get:(e,a,s)=>F(e,a)?L:t.get(e,a,s),has:(e,a)=>F(e,a)||t.has(e,a)};let M=async(e,t)=>{let s=null;if(e.url&&(s=new URL(e.url).origin),s!==self.location.origin)throw new l("cross-origin-copy-response",{origin:s});let r=e.clone(),n={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},i=t?t(n):n,c=!function(){if(void 0===a){let e=new Response("");if("body"in e)try{new Response(e.body),a=!0}catch{a=!1}a=!1}return a}()?await r.blob():r.body;return new Response(c,i)},O="requests",B="queueName";var K=class{_db=null;async addEntry(e){let t=(await this.getDb()).transaction(O,"readwrite",{durability:"relaxed"});await t.store.add(e),await t.done}async getFirstEntryId(){return(await (await this.getDb()).transaction(O).store.openCursor())?.value.id}async getAllEntriesByQueueName(e){return await (await this.getDb()).getAllFromIndex(O,B,IDBKeyRange.only(e))||[]}async getEntryCountByQueueName(e){return(await this.getDb()).countFromIndex(O,B,IDBKeyRange.only(e))}async deleteEntry(e){await (await this.getDb()).delete(O,e)}async getFirstEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"next")}async getLastEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"prev")}async getEndEntryFromIndex(e,t){return(await (await this.getDb()).transaction(O).store.index(B).openCursor(e,t))?.value}async getDb(){return this._db||(this._db=await S("serwist-background-sync",3,{upgrade:this._upgradeDb})),this._db}_upgradeDb(e,t){t>0&&t<3&&e.objectStoreNames.contains(O)&&e.deleteObjectStore(O),e.createObjectStore(O,{autoIncrement:!0,keyPath:"id"}).createIndex(B,B,{unique:!1})}},W=class{_queueName;_queueDb;constructor(e){this._queueName=e,this._queueDb=new K}async pushEntry(e){delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async unshiftEntry(e){let t=await this._queueDb.getFirstEntryId();t?e.id=t-1:delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async popEntry(){return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName))}async shiftEntry(){return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName))}async getAll(){return await this._queueDb.getAllEntriesByQueueName(this._queueName)}async size(){return await this._queueDb.getEntryCountByQueueName(this._queueName)}async deleteEntry(e){await this._queueDb.deleteEntry(e)}async _removeEntry(e){return e&&await this.deleteEntry(e.id),e}};let j=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];var $=class e{_requestData;static async fromRequest(t){let a={url:t.url,headers:{}};for(let e of("GET"!==t.method&&(a.body=await t.clone().arrayBuffer()),t.headers.forEach((e,t)=>{a.headers[t]=e}),j))void 0!==t[e]&&(a[e]=t[e]);return new e(a)}constructor(e){"navigate"===e.mode&&(e.mode="same-origin"),this._requestData=e}toObject(){let e=Object.assign({},this._requestData);return e.headers=Object.assign({},this._requestData.headers),e.body&&(e.body=e.body.slice(0)),e}toRequest(){return new Request(this._requestData.url,this._requestData)}clone(){return new e(this.toObject())}};let H="serwist-background-sync",G=new Set,Q=e=>{let t={request:new $(e.requestData).toRequest(),timestamp:e.timestamp};return e.metadata&&(t.metadata=e.metadata),t};var V=class{_name;_onSync;_maxRetentionTime;_queueStore;_forceSyncFallback;_syncInProgress=!1;_requestsAddedDuringSync=!1;constructor(e,{forceSyncFallback:t,onSync:a,maxRetentionTime:s}={}){if(G.has(e))throw new l("duplicate-queue-name",{name:e});G.add(e),this._name=e,this._onSync=a||this.replayRequests,this._maxRetentionTime=s||10080,this._forceSyncFallback=!!t,this._queueStore=new W(this._name),this._addSyncListener()}get name(){return this._name}async pushRequest(e){await this._addRequest(e,"push")}async unshiftRequest(e){await this._addRequest(e,"unshift")}async popRequest(){return this._removeRequest("pop")}async shiftRequest(){return this._removeRequest("shift")}async getAll(){let e=await this._queueStore.getAll(),t=Date.now(),a=[];for(let s of e){let e=60*this._maxRetentionTime*1e3;t-s.timestamp>e?await this._queueStore.deleteEntry(s.id):a.push(Q(s))}return a}async size(){return await this._queueStore.size()}async _addRequest({request:e,metadata:t,timestamp:a=Date.now()},s){let r={requestData:(await $.fromRequest(e.clone())).toObject(),timestamp:a};switch(t&&(r.metadata=t),s){case"push":await this._queueStore.pushEntry(r);break;case"unshift":await this._queueStore.unshiftEntry(r)}this._syncInProgress?this._requestsAddedDuringSync=!0:await this.registerSync()}async _removeRequest(e){let t,a=Date.now();switch(e){case"pop":t=await this._queueStore.popEntry();break;case"shift":t=await this._queueStore.shiftEntry()}if(t){let s=60*this._maxRetentionTime*1e3;return a-t.timestamp>s?this._removeRequest(e):Q(t)}}async replayRequests(){let e;for(;e=await this.shiftRequest();)try{await fetch(e.request.clone())}catch{throw await this.unshiftRequest(e),new l("queue-replay-failed",{name:this._name})}}async registerSync(){if("sync"in self.registration&&!this._forceSyncFallback)try{await self.registration.sync.register(`${H}:${this._name}`)}catch(e){}}_addSyncListener(){"sync"in self.registration&&!this._forceSyncFallback?self.addEventListener("sync",e=>{if(e.tag===`${H}:${this._name}`){let t=async()=>{let t;this._syncInProgress=!0;try{await this._onSync({queue:this})}catch(e){if(e instanceof Error)throw e}finally{this._requestsAddedDuringSync&&!(t&&!e.lastChance)&&await this.registerSync(),this._syncInProgress=!1,this._requestsAddedDuringSync=!1}};e.waitUntil(t())}}):this._onSync({queue:this})}static get _queueNames(){return G}},z=class{_queue;constructor(e,t){this._queue=new V(e,t)}async fetchDidFail({request:e}){await this._queue.pushRequest({request:e})}};let J={cacheWillUpdate:async({response:e})=>200===e.status||0===e.status?e:null};function X(e){return"string"==typeof e?new Request(e):e}var Y=class{event;request;url;params;_cacheKeys={};_strategy;_handlerDeferred;_extendLifetimePromises;_plugins;_pluginStateMap;constructor(e,t){for(const a of(this.event=t.event,this.request=t.request,t.url&&(this.url=t.url,this.params=t.params),this._strategy=e,this._handlerDeferred=new f,this._extendLifetimePromises=[],this._plugins=[...e.plugins],this._pluginStateMap=new Map,this._plugins))this._pluginStateMap.set(a,{});this.event.waitUntil(this._handlerDeferred.promise)}async fetch(e){let{event:t}=this,a=X(e),s=await this.getPreloadResponse();if(s)return s;let r=this.hasCallback("fetchDidFail")?a.clone():null;try{for(let e of this.iterateCallbacks("requestWillFetch"))a=await e({request:a.clone(),event:t})}catch(e){if(e instanceof Error)throw new l("plugin-error-request-will-fetch",{thrownErrorMessage:e.message})}let n=a.clone();try{let e;for(let s of(e=await fetch(a,"navigate"===a.mode?void 0:this._strategy.fetchOptions),this.iterateCallbacks("fetchDidSucceed")))e=await s({event:t,request:n,response:e});return e}catch(e){throw r&&await this.runCallbacks("fetchDidFail",{error:e,event:t,originalRequest:r.clone(),request:n.clone()}),e}}async fetchAndCachePut(e){let t=await this.fetch(e),a=t.clone();return this.waitUntil(this.cachePut(e,a)),t}async cacheMatch(e){let t,a=X(e),{cacheName:s,matchOptions:r}=this._strategy,n=await this.getCacheKey(a,"read"),i={...r,cacheName:s};for(let e of(t=await caches.match(n,i),this.iterateCallbacks("cachedResponseWillBeUsed")))t=await e({cacheName:s,matchOptions:r,cachedResponse:t,request:n,event:this.event})||void 0;return t}async cachePut(e,t){let a=X(e);await h(0);let s=await this.getCacheKey(a,"write");if(!t)throw new l("cache-put-with-no-response",{url:new URL(String(s.url),location.href).href.replace(RegExp(`^${location.origin}`),"")});let r=await this._ensureResponseSafeToCache(t);if(!r)return!1;let{cacheName:n,matchOptions:i}=this._strategy,c=await self.caches.open(n),o=this.hasCallback("cacheDidUpdate"),u=o?await m(c,s.clone(),["__WB_REVISION__"],i):null;try{await c.put(s,o?r.clone():r)}catch(e){if(e instanceof Error)throw"QuotaExceededError"===e.name&&await g(),e}for(let e of this.iterateCallbacks("cacheDidUpdate"))await e({cacheName:n,oldResponse:u,newResponse:r.clone(),request:s,event:this.event});return!0}async getCacheKey(e,t){let a=`${e.url} | ${t}`;if(!this._cacheKeys[a]){let s=e;for(let e of this.iterateCallbacks("cacheKeyWillBeUsed"))s=X(await e({mode:t,request:s,event:this.event,params:this.params}));this._cacheKeys[a]=s}return this._cacheKeys[a]}hasCallback(e){for(let t of this._strategy.plugins)if(e in t)return!0;return!1}async runCallbacks(e,t){for(let a of this.iterateCallbacks(e))await a(t)}*iterateCallbacks(e){for(let t of this._strategy.plugins)if("function"==typeof t[e]){let a=this._pluginStateMap.get(t),s=s=>{let r={...s,state:a};return t[e](r)};yield s}}waitUntil(e){return this._extendLifetimePromises.push(e),e}async doneWaiting(){let e;for(;e=this._extendLifetimePromises.shift();)await e}destroy(){this._handlerDeferred.resolve(null)}async getPreloadResponse(){if(this.event instanceof FetchEvent&&"navigate"===this.event.request.mode&&"preloadResponse"in this.event)try{let e=await this.event.preloadResponse;if(e)return e}catch(e){return}}async _ensureResponseSafeToCache(e){let t=e,a=!1;for(let e of this.iterateCallbacks("cacheWillUpdate"))if(t=await e({request:this.request,response:t,event:this.event})||void 0,a=!0,!t)break;return!a&&t&&200!==t.status&&(t=void 0),t}},Z=class{cacheName;plugins;fetchOptions;matchOptions;constructor(e={}){this.cacheName=o(e.cacheName),this.plugins=e.plugins||[],this.fetchOptions=e.fetchOptions,this.matchOptions=e.matchOptions}handle(e){let[t]=this.handleAll(e);return t}handleAll(e){e instanceof FetchEvent&&(e={event:e,request:e.request});let t=e.event,a="string"==typeof e.request?new Request(e.request):e.request,s=new Y(this,e.url?{event:t,request:a,url:e.url,params:e.params}:{event:t,request:a}),r=this._getResponse(s,a,t);return[r,this._awaitComplete(r,s,a,t)]}async _getResponse(e,t,a){let s;await e.runCallbacks("handlerWillStart",{event:a,request:t});try{if(s=await this._handle(t,e),void 0===s||"error"===s.type)throw new l("no-response",{url:t.url})}catch(r){if(r instanceof Error){for(let n of e.iterateCallbacks("handlerDidError"))if(void 0!==(s=await n({error:r,event:a,request:t})))break}if(!s)throw r}for(let r of e.iterateCallbacks("handlerWillRespond"))s=await r({event:a,request:t,response:s});return s}async _awaitComplete(e,t,a,s){let r,n;try{r=await e}catch{}try{await t.runCallbacks("handlerDidRespond",{event:s,request:a,response:r}),await t.doneWaiting()}catch(e){e instanceof Error&&(n=e)}if(await t.runCallbacks("handlerDidComplete",{event:s,request:a,response:r,error:n}),t.destroy(),n)throw n}},ee=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(J),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s=[],r=[];if(this._networkTimeoutSeconds){let{id:n,promise:i}=this._getTimeoutPromise({request:e,logs:s,handler:t});a=n,r.push(i)}let n=this._getNetworkPromise({timeoutId:a,request:e,logs:s,handler:t});r.push(n);let i=await t.waitUntil((async()=>await t.waitUntil(Promise.race(r))||await n)());if(!i)throw new l("no-response",{url:e.url});return i}_getTimeoutPromise({request:e,logs:t,handler:a}){let s;return{promise:new Promise(t=>{s=setTimeout(async()=>{t(await a.cacheMatch(e))},1e3*this._networkTimeoutSeconds)}),id:s}}async _getNetworkPromise({timeoutId:e,request:t,logs:a,handler:s}){let r,n;try{n=await s.fetchAndCachePut(t)}catch(e){e instanceof Error&&(r=e)}return e&&clearTimeout(e),(r||!n)&&(n=await s.cacheMatch(t)),n}},et=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s;try{let a=[t.fetch(e)];if(this._networkTimeoutSeconds){let e=h(1e3*this._networkTimeoutSeconds);a.push(e)}if(!(s=await Promise.race(a)))throw Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}};let ea=e=>e&&"object"==typeof e?e:{handle:e};var es=class{handler;match;method;catchHandler;constructor(e,t,a="GET"){this.handler=ea(t),this.match=e,this.method=a}setCatchHandler(e){this.catchHandler=ea(e)}},er=class e extends Z{_fallbackToNetwork;static defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:e})=>!e||e.status>=400?null:e};static copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:e})=>e.redirected?await M(e):e};constructor(t={}){t.cacheName=c(t.cacheName),super(t),this._fallbackToNetwork=!1!==t.fallbackToNetwork,this.plugins.push(e.copyRedirectedCacheableResponsesPlugin)}async _handle(e,t){let a=await t.getPreloadResponse();if(a)return a;let s=await t.cacheMatch(e);return s||(t.event&&"install"===t.event.type?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,t){let a,s=t.params||{};if(this._fallbackToNetwork){let r=s.integrity,n=e.integrity,i=!n||n===r;a=await t.fetch(new Request(e,{integrity:"no-cors"!==e.mode?n||r:void 0})),r&&i&&"no-cors"!==e.mode&&(this._useDefaultCacheabilityPluginIfNeeded(),await t.cachePut(e,a.clone()))}else throw new l("missing-precache-entry",{cacheName:this.cacheName,url:e.url});return a}async _handleInstall(e,t){this._useDefaultCacheabilityPluginIfNeeded();let a=await t.fetch(e);if(!await t.cachePut(e,a.clone()))throw new l("bad-precaching-response",{url:e.url,status:a.status});return a}_useDefaultCacheabilityPluginIfNeeded(){let t=null,a=0;for(let[s,r]of this.plugins.entries())r!==e.copyRedirectedCacheableResponsesPlugin&&(r===e.defaultPrecacheCacheabilityPlugin&&(t=s),r.cacheWillUpdate&&a++);0===a?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):a>1&&null!==t&&this.plugins.splice(t,1)}},en=class extends es{_allowlist;_denylist;constructor(e,{allowlist:t=[/./],denylist:a=[]}={}){super(e=>this._match(e),e),this._allowlist=t,this._denylist=a}_match({url:e,request:t}){if(t&&"navigate"!==t.mode)return!1;let a=e.pathname+e.search;for(let e of this._denylist)if(e.test(a))return!1;return!!this._allowlist.some(e=>e.test(a))}},ei=class extends es{constructor(e,t,a){super(({url:t})=>{let a=e.exec(t.href);if(a)return t.origin!==location.origin&&0!==a.index?void 0:a.slice(1)},t,a)}};let ec=e=>{if(!e)throw new l("add-to-cache-list-unexpected-type",{entry:e});if("string"==typeof e){let t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}let{revision:t,url:a}=e;if(!a)throw new l("add-to-cache-list-unexpected-type",{entry:e});if(!t){let e=new URL(a,location.href);return{cacheKey:e.href,url:e.href}}let s=new URL(a,location.href),r=new URL(a,location.href);return s.searchParams.set("__WB_REVISION__",t),{cacheKey:s.href,url:r.href}};var eo=class{updatedURLs=[];notUpdatedURLs=[];handlerWillStart=async({request:e,state:t})=>{t&&(t.originalRequest=e)};cachedResponseWillBeUsed=async({event:e,state:t,cachedResponse:a})=>{if("install"===e.type&&t?.originalRequest&&t.originalRequest instanceof Request){let e=t.originalRequest.url;a?this.notUpdatedURLs.push(e):this.updatedURLs.push(e)}return a}};let el=async(e,t,a)=>{let s=t.map((e,t)=>({index:t,item:e})),r=async e=>{let t=[];for(;;){let r=s.pop();if(!r)return e(t);let n=await a(r.item);t.push({result:n,index:r.index})}},n=Array.from({length:e},()=>new Promise(r));return(await Promise.all(n)).flat().sort((e,t)=>e.indexe.result)};"u">typeof navigator&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent);let eh="cache-entries",eu=e=>{let t=new URL(e,location.href);return t.hash="",t.href};var ed=class{_cacheName;_db=null;constructor(e){this._cacheName=e}_getId(e){return`${this._cacheName}|${eu(e)}`}_upgradeDb(e){let t=e.createObjectStore(eh,{keyPath:"id"});t.createIndex("cacheName","cacheName",{unique:!1}),t.createIndex("timestamp","timestamp",{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&function(e,{blocked:t}={}){let a=indexedDB.deleteDatabase(e);t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),R(a).then(()=>void 0)}(this._cacheName)}async setTimestamp(e,t){e=eu(e);let a={id:this._getId(e),cacheName:this._cacheName,url:e,timestamp:t},s=(await this.getDb()).transaction(eh,"readwrite",{durability:"relaxed"});await s.store.put(a),await s.done}async getTimestamp(e){return(await (await this.getDb()).get(eh,this._getId(e)))?.timestamp}async expireEntries(e,t){let a=await (await this.getDb()).transaction(eh,"readwrite").store.index("timestamp").openCursor(null,"prev"),s=[],r=0;for(;a;){let n=a.value;n.cacheName===this._cacheName&&(e&&n.timestamp=t?(a.delete(),s.push(n.url)):r++),a=await a.continue()}return s}async getDb(){return this._db||(this._db=await S("serwist-expiration",1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)})),this._db}},em=class{_isRunning=!1;_rerunRequested=!1;_maxEntries;_maxAgeSeconds;_matchOptions;_cacheName;_timestampModel;constructor(e,t={}){this._maxEntries=t.maxEntries,this._maxAgeSeconds=t.maxAgeSeconds,this._matchOptions=t.matchOptions,this._cacheName=e,this._timestampModel=new ed(e)}async expireEntries(){if(this._isRunning){this._rerunRequested=!0;return}this._isRunning=!0;let e=this._maxAgeSeconds?Date.now()-1e3*this._maxAgeSeconds:0,t=await this._timestampModel.expireEntries(e,this._maxEntries),a=await self.caches.open(this._cacheName);for(let e of t)await a.delete(e,this._matchOptions);this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,this.expireEntries())}async updateTimestamp(e){await this._timestampModel.setTimestamp(e,Date.now())}async isURLExpired(e){if(!this._maxAgeSeconds)return!1;let t=await this._timestampModel.getTimestamp(e),a=Date.now()-1e3*this._maxAgeSeconds;return void 0===t||t{u.add(e)})(()=>this.deleteCacheAndMetadata())}_getCacheExpiration(e){if(e===o())throw new l("expire-custom-caches-only");let t=this._cacheExpirations.get(e);return t||(t=new em(e,this._config),this._cacheExpirations.set(e,t)),t}cachedResponseWillBeUsed({event:e,cacheName:t,request:a,cachedResponse:s}){if(!s)return null;let r=this._isResponseDateFresh(s),n=this._getCacheExpiration(t),i="last-used"===this._config.maxAgeFrom,c=(async()=>{i&&await n.updateTimestamp(a.url),await n.expireEntries()})();try{e.waitUntil(c)}catch{}return r?s:null}_isResponseDateFresh(e){if("last-used"===this._config.maxAgeFrom)return!0;let t=Date.now();if(!this._config.maxAgeSeconds)return!0;let a=this._getDateHeaderTimestamp(e);return null===a||a>=t-1e3*this._config.maxAgeSeconds}_getDateHeaderTimestamp(e){if(!e.headers.has("date"))return null;let t=new Date(e.headers.get("date")).getTime();return Number.isNaN(t)?null:t}async cacheDidUpdate({cacheName:e,request:t}){let a=this._getCacheExpiration(e);await a.updateTimestamp(t.url),await a.expireEntries()}async deleteCacheAndMetadata(){for(let[e,t]of this._cacheExpirations)await self.caches.delete(e),await t.delete();this._cacheExpirations=new Map}};let eg=/^\/(\w+\/)?collect/,ew=({serwist:e,cacheName:t,...a})=>{let s,r,c=t||i(n.googleAnalytics),o=new z("serwist-google-analytics",{maxRetentionTime:2880,onSync:async({queue:e})=>{let t;for(;t=await e.shiftRequest();){let{request:s,timestamp:r}=t,n=new URL(s.url);try{let e="POST"===s.method?new URLSearchParams(await s.clone().text()):n.searchParams,t=r-(Number(e.get("qt"))||0),i=Date.now()-t;if(e.set("qt",String(i)),a.parameterOverrides)for(let t of Object.keys(a.parameterOverrides)){let s=a.parameterOverrides[t];e.set(t,s)}"function"==typeof a.hitFilter&&a.hitFilter.call(null,e),await fetch(new Request(n.origin+n.pathname,{body:e.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(a){throw await e.unshiftRequest(t),a}}}});for(let t of[new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtm.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.google-analytics.com"===e.hostname&&"/analytics.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtag/js"===e.pathname,new ee({cacheName:c}),"GET"),new es(s=({url:e})=>"www.google-analytics.com"===e.hostname&&eg.test(e.pathname),r=new et({plugins:[o]}),"GET"),new es(s,r,"POST")])e.registerRoute(t)};var ep=class{_fallbackUrls;_serwist;constructor({fallbackUrls:e,serwist:t}){this._fallbackUrls=e,this._serwist=t}async handlerDidError(e){for(let t of this._fallbackUrls)if("string"==typeof t){let e=await this._serwist.matchPrecache(t);if(void 0!==e)return e}else if(t.matcher(e)){let e=await this._serwist.matchPrecache(t.url);if(void 0!==e)return e}}};let ey=async(e,t)=>{try{if(206===t.status)return t;let a=e.headers.get("range");if(!a)throw new l("no-range-header");let s=(e=>{let t=e.trim().toLowerCase();if(!t.startsWith("bytes="))throw new l("unit-must-be-bytes",{normalizedRangeHeader:t});if(t.includes(","))throw new l("single-range-only",{normalizedRangeHeader:t});let a=/(\d*)-(\d*)/.exec(t);if(!a||!(a[1]||a[2]))throw new l("invalid-range-values",{normalizedRangeHeader:t});return{start:""===a[1]?void 0:Number(a[1]),end:""===a[2]?void 0:Number(a[2])}})(a),r=await t.blob(),n=((e,t,a)=>{let s,r,n=e.size;if(a&&a>n||t&&t<0)throw new l("range-not-satisfiable",{size:n,end:a,start:t});return void 0!==t&&void 0!==a?(s=t,r=a+1):void 0!==t&&void 0===a?(s=t,r=n):void 0!==a&&void 0===t&&(s=n-a,r=n),{start:s,end:r}})(r,s.start,s.end),i=r.slice(n.start,n.end),c=i.size,o=new Response(i,{status:206,statusText:"Partial Content",headers:t.headers});return o.headers.set("Content-Length",String(c)),o.headers.set("Content-Range",`bytes ${n.start}-${n.end-1}/${r.size}`),o}catch(e){return new Response("",{status:416,statusText:"Range Not Satisfiable"})}};var e_=class{cachedResponseWillBeUsed=async({request:e,cachedResponse:t})=>t&&e.headers.has("range")?await ey(e,t):t},ex=class extends Z{async _handle(e,t){let a,s=await t.cacheMatch(e);if(s);else try{s=await t.fetchAndCachePut(e)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}},eb=class extends Z{constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(J)}async _handle(e,t){let a,s=t.fetchAndCachePut(e).catch(()=>{});t.waitUntil(s);let r=await t.cacheMatch(e);if(r);else try{r=await s}catch(e){e instanceof Error&&(a=e)}if(!r)throw new l("no-response",{url:e.url,error:a});return r}},ev=class extends es{constructor(e,t){super(({request:a})=>{let s=e.getUrlsToPrecacheKeys();for(let r of function*(e,{directoryIndex:t="index.html",ignoreURLParametersMatching:a=[/^utm_/,/^fbclid$/],cleanURLs:s=!0,urlManipulation:r}={}){let n=new URL(e,location.href);n.hash="",yield n.href;let i=((e,t=[])=>{for(let a of[...e.searchParams.keys()])t.some(e=>e.test(a))&&e.searchParams.delete(a);return e})(n,a);if(yield i.href,t&&i.pathname.endsWith("/")){let e=new URL(i.href);e.pathname+=t,yield e.href}if(s){let e=new URL(i.href);e.pathname+=".html",yield e.href}if(r)for(let e of r({url:n}))yield e.href}(a.url,t)){let t=s.get(r);if(t)return{cacheKey:t,integrity:e.getIntegrityForPrecacheKey(t)}}},e.precacheStrategy)}},eE=class{_precacheController;constructor({precacheController:e}){this._precacheController=e}cacheKeyWillBeUsed=async({request:e,params:t})=>{let a=t?.cacheKey||this._precacheController.getPrecacheKeyForUrl(e.url);return a?new Request(a,{headers:e.headers}):e}},eR=class{_urlsToCacheKeys=new Map;_urlsToCacheModes=new Map;_cacheKeysToIntegrities=new Map;_concurrentPrecaching;_precacheStrategy;_routes;_defaultHandlerMap;_catchHandler;_requestRules;constructor({precacheEntries:e,precacheOptions:t,skipWaiting:a=!1,importScripts:s,navigationPreload:r=!1,cacheId:i,clientsClaim:o=!1,runtimeCaching:l,offlineAnalyticsConfig:h,disableDevLogs:u=!1,fallbacks:d,requestRules:m}={}){const{precacheStrategyOptions:f,precacheRouteOptions:g,precacheMiscOptions:w}=((e,t={})=>{let{cacheName:a,plugins:s=[],fetchOptions:r,matchOptions:n,fallbackToNetwork:i,directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u,cleanupOutdatedCaches:d,concurrency:m=10,navigateFallback:f,navigateFallbackAllowlist:g,navigateFallbackDenylist:w}=t??{};return{precacheStrategyOptions:{cacheName:c(a),plugins:[...s,new eE({precacheController:e})],fetchOptions:r,matchOptions:n,fallbackToNetwork:i},precacheRouteOptions:{directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u},precacheMiscOptions:{cleanupOutdatedCaches:d,concurrency:m,navigateFallback:f,navigateFallbackAllowlist:g,navigateFallbackDenylist:w}}})(this,t);if(this._concurrentPrecaching=w.concurrency,this._precacheStrategy=new er(f),this._routes=new Map,this._defaultHandlerMap=new Map,this._requestRules=m,this.handleInstall=this.handleInstall.bind(this),this.handleActivate=this.handleActivate.bind(this),this.handleFetch=this.handleFetch.bind(this),this.handleCache=this.handleCache.bind(this),s&&s.length>0&&self.importScripts(...s),r&&self.registration?.navigationPreload&&self.addEventListener("activate",e=>{e.waitUntil(self.registration.navigationPreload.enable().then(()=>{}))}),void 0!==i&&(e=>{var t=e;for(let e of Object.keys(n))(e=>{let a=t[e];"string"==typeof a&&(n[e]=a)})(e)})({prefix:i}),a?self.skipWaiting():self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),o&&self.addEventListener("activate",()=>self.clients.claim()),e&&e.length>0&&this.addToPrecacheList(e),w.cleanupOutdatedCaches&&(e=>{self.addEventListener("activate",t=>{t.waitUntil(p(c(e)).then(e=>{}))})})(f.cacheName),this.registerRoute(new ev(this,g)),w.navigateFallback&&this.registerRoute(new en(this.createHandlerBoundToUrl(w.navigateFallback),{allowlist:w.navigateFallbackAllowlist,denylist:w.navigateFallbackDenylist})),void 0!==h&&("boolean"==typeof h?h&&ew({serwist:this}):ew({...h,serwist:this})),void 0!==l){if(void 0!==d){const e=new ep({fallbackUrls:d.entries,serwist:this});l.forEach(t=>{t.handler instanceof Z&&!t.handler.plugins.some(e=>"handlerDidError"in e)&&t.handler.plugins.push(e)})}for(const e of l)this.registerCapture(e.matcher,e.handler,e.method)}u&&(self.__WB_DISABLE_DEV_LOGS=!0)}get precacheStrategy(){return this._precacheStrategy}get routes(){return this._routes}addEventListeners(){self.addEventListener("install",this.handleInstall),self.addEventListener("activate",this.handleActivate),self.addEventListener("fetch",this.handleFetch),self.addEventListener("message",this.handleCache)}addToPrecacheList(e){let t=[];for(let a of e){"string"==typeof a?t.push(a):a&&!a.integrity&&void 0===a.revision&&t.push(a.url);let{cacheKey:e,url:s}=ec(a),r="string"!=typeof a&&a.revision?"reload":"default";if(this._urlsToCacheKeys.has(s)&&this._urlsToCacheKeys.get(s)!==e)throw new l("add-to-cache-list-conflicting-entries",{firstEntry:this._urlsToCacheKeys.get(s),secondEntry:e});if("string"!=typeof a&&a.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==a.integrity)throw new l("add-to-cache-list-conflicting-integrities",{url:s});this._cacheKeysToIntegrities.set(e,a.integrity)}this._urlsToCacheKeys.set(s,e),this._urlsToCacheModes.set(s,r)}t.length>0&&console.warn(`Serwist is precaching URLs without revision info: ${t.join(", ")} +This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),y(e,async()=>{let t=new eo;this.precacheStrategy.plugins.push(t),await el(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let s=this._cacheKeysToIntegrities.get(a),r=this._urlsToCacheModes.get(t),n=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:n,url:new URL(n.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:s}=t;return{updatedURLs:a,notUpdatedURLs:s}})}async registerRequestRules(e){if(this._requestRules&&e?.addRoutes)try{await e.addRoutes(this._requestRules),this._requestRules=void 0}catch(e){throw e}}handleActivate(e){return y(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),s=[];for(let r of t)a.has(r.url)||(await e.delete(r),s.push(r.url));return{deletedCacheRequests:s}})}handleFetch(e){let{request:t}=e,a=this.handleRequest({request:t,event:e});a&&e.respondWith(a)}handleCache(e){if(e.data&&"CACHE_URLS"===e.data.type){let{payload:t}=e.data,a=Promise.all(t.urlsToCache.map(t=>{let a;return a="string"==typeof t?new Request(t):new Request(...t),this.handleRequest({request:a,event:e})}));e.waitUntil(a),e.ports?.[0]&&a.then(()=>e.ports[0].postMessage(!0))}}setDefaultHandler(e,t="GET"){this._defaultHandlerMap.set(t,ea(e))}setCatchHandler(e){this._catchHandler=ea(e)}registerCapture(e,t,a){let s=((e,t,a)=>{if("string"==typeof e){let s=new URL(e,location.href);return new es(({url:e})=>e.href===s.href,t,a)}if(e instanceof RegExp)return new ei(e,t,a);if("function"==typeof e)return new es(e,t,a);if(e instanceof es)return e;throw new l("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})})(e,t,a);return this.registerRoute(s),s}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new l("unregister-route-but-not-found-with-method",{method:e.method});let t=this._routes.get(e.method).indexOf(e);if(t>-1)this._routes.get(e.method).splice(t,1);else throw new l("unregister-route-route-not-registered")}getUrlsToPrecacheKeys(){return this._urlsToCacheKeys}getPrecachedUrls(){return[...this._urlsToCacheKeys.keys()]}getPrecacheKeyForUrl(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForPrecacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,a=this.getPrecacheKeyForUrl(t);if(a)return(await self.caches.open(this.precacheStrategy.cacheName)).match(a)}createHandlerBoundToUrl(e){let t=this.getPrecacheKeyForUrl(e);if(!t)throw new l("non-precached-url",{url:e});return a=>(a.request=new Request(e),a.params={cacheKey:t,...a.params},this.precacheStrategy.handle(a))}handleRequest({request:e,event:t}){let a,s=new URL(e.url,location.href);if(!s.protocol.startsWith("http"))return;let r=s.origin===location.origin,{params:n,route:i}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=i?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:s,request:e,event:t,params:n})}catch(e){a=Promise.reject(e)}let l=i?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:s,request:e,event:t,params:n})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:s,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:s}){for(let r of this._routes.get(a.method)||[]){let n,i=r.match({url:e,sameOrigin:t,request:a,event:s});if(i)return Array.isArray(n=i)&&0===n.length||i.constructor===Object&&0===Object.keys(i).length?n=void 0:"boolean"==typeof i&&(n=void 0),{route:r,params:n}}return{}}};let eq=[{matcher:/^https:\/\/fonts\.(?:gstatic)\.com\/.*/i,handler:new ex({cacheName:"google-fonts-webfonts",plugins:[new ef({maxEntries:4,maxAgeSeconds:31536e3,maxAgeFrom:"last-used"})]})},{matcher:/^https:\/\/fonts\.(?:googleapis)\.com\/.*/i,handler:new eb({cacheName:"google-fonts-stylesheets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,handler:new eb({cacheName:"static-font-assets",plugins:[new ef({maxEntries:4,maxAgeSeconds:604800,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,handler:new eb({cacheName:"static-image-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:2592e3,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/static.+\.js$/i,handler:new ex({cacheName:"next-static-js-assets",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/image\?url=.+$/i,handler:new eb({cacheName:"next-image",plugins:[new ef({maxEntries:64,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:mp3|wav|ogg)$/i,handler:new ex({cacheName:"static-audio-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:mp4|webm)$/i,handler:new ex({cacheName:"static-video-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"}),new e_]})},{matcher:/\.(?:js)$/i,handler:new eb({cacheName:"static-js-assets",plugins:[new ef({maxEntries:48,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:css|less)$/i,handler:new eb({cacheName:"static-style-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/_next\/data\/.+\/.+\.json$/i,handler:new ee({cacheName:"next-data",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\.(?:json|xml|csv)$/i,handler:new ee({cacheName:"static-data-assets",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400,maxAgeFrom:"last-used"})]})},{matcher:/\/api\/auth\/.*/,handler:new et({networkTimeoutSeconds:10})},{matcher:({sameOrigin:e,url:{pathname:t}})=>e&&t.startsWith("/api/"),method:"GET",handler:new ee({cacheName:"apis",plugins:[new ef({maxEntries:16,maxAgeSeconds:86400,maxAgeFrom:"last-used"})],networkTimeoutSeconds:10})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&"1"===e.headers.get("Next-Router-Prefetch")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc-prefetch",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>"1"===e.headers.get("RSC")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages-rsc",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({request:e,url:{pathname:t},sameOrigin:a})=>e.headers.get("Content-Type")?.includes("text/html")&&a&&!t.startsWith("/api/"),handler:new ee({cacheName:"pages",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({url:{pathname:e},sameOrigin:t})=>t&&!e.startsWith("/api/"),handler:new ee({cacheName:"others",plugins:[new ef({maxEntries:32,maxAgeSeconds:86400})]})},{matcher:({sameOrigin:e})=>!e,handler:new ee({cacheName:"cross-origin",plugins:[new ef({maxEntries:32,maxAgeSeconds:3600})],networkTimeoutSeconds:10})},{matcher:/.*/i,method:"GET",handler:new et}];new eR({precacheEntries:[{'revision':null,'url':'/_next/static/chunks/3199-4a3557850e4b6905.js'},{'revision':null,'url':'/_next/static/chunks/4525-ff31e5ea7d02080f.js'},{'revision':null,'url':'/_next/static/chunks/5239-9df6f85b3ce4fcfc.js'},{'revision':null,'url':'/_next/static/chunks/528-d4588a5ca0277d60.js'},{'revision':null,'url':'/_next/static/chunks/6558-9b5e801acd5a8d15.js'},{'revision':null,'url':'/_next/static/chunks/87c73c54-f46fec743414da25.js'},{'revision':null,'url':'/_next/static/chunks/app/_global-error/page-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-4ba38dd60d12680e.js'},{'revision':null,'url':'/_next/static/chunks/app/achievements/page-d1e8bcd7804cbee8.js'},{'revision':null,'url':'/_next/static/chunks/app/api/achievements/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/actions/%5Bid%5D/undo/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/actions/recent/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/apply-template/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/items/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/items/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/rest-day/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/todos/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/adventures/%5Bdate%5D/todos/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/config/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/health/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/models/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/suggestions/%5Bid%5D/dismiss/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/suggestions/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/templates/%5Bkey%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ai/templates/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/auth/login/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5Bid%5D/log-pages/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/cartographer/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/cron/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/dashboard/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/explorations/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/explorations/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/export/json/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/library/books/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/library/cover/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/library/progress/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/library/status/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/reflections/%5Bdate%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/reviews/%5BweekStart%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/settings/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/%5Bdomain%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/teacher/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/teacher/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/templates/%5Bid%5D/items/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/templates/%5Bid%5D/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/templates/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/api/themes/route-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/app/cartographer/page-36de99d943637132.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-70363222dbc2d7a6.js'},{'revision':null,'url':'/_next/static/chunks/app/library/page-56ffe085875541db.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-5f636e39fc0fa1fb.js'},{'revision':null,'url':'/_next/static/chunks/app/page-ba556633567a0846.js'},{'revision':null,'url':'/_next/static/chunks/app/review/page-512d55520e77ae2c.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/page-d8df59892a38439e.js'},{'revision':null,'url':'/_next/static/chunks/app/statistics/page-6ddc8ad040153f8c.js'},{'revision':null,'url':'/_next/static/chunks/app/teacher/page-77827b4518eee3a6.js'},{'revision':null,'url':'/_next/static/chunks/app/yearly/page-4fa38fc70f1cdf6b.js'},{'revision':null,'url':'/_next/static/chunks/framework-af3c63e39f557570.js'},{'revision':null,'url':'/_next/static/chunks/main-4a90bc78b0d3fc62.js'},{'revision':null,'url':'/_next/static/chunks/main-app-567e4578199091e8.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-555d6023af128706.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/not-found-77f738e136eb71c1.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-77f738e136eb71c1.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-99360225e07f4440.js'},{'revision':null,'url':'/_next/static/css/845391a55dbb4326.css'},{'revision':'501a73f16b7e2b6bc39bc2d222c5af86','url':'/_next/static/wN-9J-ykM9fVHHSAPywAG/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/wN-9J-ykM9fVHHSAPywAG/_ssgManifest.js'},{'revision':'d09f95206c3fa0bb9bd9fefabfd0ea71','url':'/file.svg'},{'revision':'2aaafa6a49b6563925fe440891e32717','url':'/globe.svg'},{'revision':'0927dc4135144aca169f3c770914dcbe','url':'/icons/icon.svg'},{'revision':'e8f86e44407fcbcd8f9748e1b3f67e95','url':'/manifest.json'},{'revision':'8e061864f388b47f33a1c3780831193e','url':'/next.svg'},{'revision':'c0af2f507b369b085b35ef4bbe3bcf1e','url':'/vercel.svg'},{'revision':'a2760511c65806022ad20adf74370ff3','url':'/window.svg'}],skipWaiting:!0,clientsClaim:!0,navigationPreload:!0,runtimeCaching:eq}).addEventListeners()})(); \ No newline at end of file diff --git a/apps/web/public/vercel.svg b/apps/web/public/vercel.svg new file mode 100755 index 0000000..7705396 --- /dev/null +++ b/apps/web/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/window.svg b/apps/web/public/window.svg new file mode 100755 index 0000000..b2b2a44 --- /dev/null +++ b/apps/web/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/app/achievements/page.tsx b/apps/web/src/app/achievements/page.tsx new file mode 100755 index 0000000..6028272 --- /dev/null +++ b/apps/web/src/app/achievements/page.tsx @@ -0,0 +1,58 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { AppShell } from "@/components/layout/app-shell"; + +export default function AchievementsPage() { + const { data, isLoading } = useQuery({ + queryKey: ["achievements"], + queryFn: async () => { + const res = await fetch("/api/achievements"); + return res.json(); + }, + }); + + const unlockedKeys = new Set( + (data?.unlocked ?? []).map((a: { key: string }) => a.key) + ); + + return ( + +
+

Achievement Gallery

+

+ Milestones on your long adventure — earned through showing up, not perfection. +

+ + {isLoading ? ( +

Loading trophies...

+ ) : ( +
+ {(data?.all ?? []).map( + (a: { key: string; name: string; description: string; category: string }) => { + const unlocked = unlockedKeys.has(a.key); + return ( +
+
+ {unlocked ? "🏆" : "🔒"} +
+

{a.name}

+

{a.description}

+ {a.category} +
+
+
+ ); + } + )} +
+ )} +
+
+ ); +} diff --git a/apps/web/src/app/api/achievements/route.ts b/apps/web/src/app/api/achievements/route.ts new file mode 100755 index 0000000..5688f9d --- /dev/null +++ b/apps/web/src/app/api/achievements/route.ts @@ -0,0 +1,23 @@ +import { handleApi } from "@/lib/api"; +import { + getAchievements, + getAllAchievementDefinitions, + checkAchievements, +} from "@/lib/services/achievements"; +import { requireUser } from "@/lib/services/user"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const unlocked = await getAchievements(user.id); + const all = getAllAchievementDefinitions(); + return { unlocked, all }; + }); +} + +export async function POST() { + return handleApi(async () => { + const { user } = await requireUser(); + return checkAchievements(user.id); + }); +} diff --git a/apps/web/src/app/api/actions/[id]/undo/route.ts b/apps/web/src/app/api/actions/[id]/undo/route.ts new file mode 100755 index 0000000..c00f655 --- /dev/null +++ b/apps/web/src/app/api/actions/[id]/undo/route.ts @@ -0,0 +1,16 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { undoAction } from "@/lib/services/undo"; + +export async function POST( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const result = await undoAction(user.id, id); + if (!result.ok) throw new Error(result.error ?? "Undo failed"); + return result; + }); +} diff --git a/apps/web/src/app/api/actions/recent/route.ts b/apps/web/src/app/api/actions/recent/route.ts new file mode 100755 index 0000000..43fb1a5 --- /dev/null +++ b/apps/web/src/app/api/actions/recent/route.ts @@ -0,0 +1,11 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getRecentActions } from "@/lib/services/action-events"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const actions = await getRecentActions(user.id, 30); + return { actions }; + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/apply-template/route.ts b/apps/web/src/app/api/adventures/[date]/apply-template/route.ts new file mode 100755 index 0000000..ccf77c2 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/apply-template/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { applyTemplateToDate } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return applyTemplateToDate(user.id, date, body.templateId, body.force === true); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/items/[id]/route.ts b/apps/web/src/app/api/adventures/[date]/items/[id]/route.ts new file mode 100755 index 0000000..3dbcfca --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/items/[id]/route.ts @@ -0,0 +1,29 @@ +import { handleApi } from "@/lib/api"; +import { updateAdventureItem, updateDailyItemMeta, deleteCustomDailyItem } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ date: string; id: string }> } +) { + const { date, id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.label !== undefined || body.enabled !== undefined || body.config !== undefined) { + return updateDailyItemMeta(user.id, date, id, body); + } + return updateAdventureItem(user.id, date, id, body); + }); +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ date: string; id: string }> } +) { + const { date, id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return deleteCustomDailyItem(user.id, date, id); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/items/route.ts b/apps/web/src/app/api/adventures/[date]/items/route.ts new file mode 100755 index 0000000..32ac674 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/items/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { addCustomDailyItem } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return addCustomDailyItem(user.id, date, body); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/quick-log/route.ts b/apps/web/src/app/api/adventures/[date]/quick-log/route.ts new file mode 100644 index 0000000..b05d553 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/quick-log/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { quickLog } from "@/lib/services/quick-log"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return quickLog(user.id, date, body); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/rest-day/route.ts b/apps/web/src/app/api/adventures/[date]/rest-day/route.ts new file mode 100755 index 0000000..dec8fa3 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/rest-day/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { setRestDay } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + _request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const result = await setRestDay(user.id, date); + return { ok: true, actionEventId: result.actionEventId }; + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/route.ts b/apps/web/src/app/api/adventures/[date]/route.ts new file mode 100755 index 0000000..9e1c4a7 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/route.ts @@ -0,0 +1,32 @@ +import { handleApi } from "@/lib/api"; +import { getDailyAdventure, updateDaySettings } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return getDailyAdventure(user.id, date); + }); +} + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.workHoursTarget !== undefined || body.dayMode !== undefined) { + return updateDaySettings(user.id, date, { + workHoursTarget: body.workHoursTarget, + dayMode: body.dayMode, + }); + } + throw new Error("No valid updates"); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/todos/[id]/route.ts b/apps/web/src/app/api/adventures/[date]/todos/[id]/route.ts new file mode 100755 index 0000000..d57e6f9 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/todos/[id]/route.ts @@ -0,0 +1,26 @@ +import { handleApi } from "@/lib/api"; +import { updateDailyTodo, deleteDailyTodo } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ date: string; id: string }> } +) { + const { date, id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return updateDailyTodo(user.id, date, id, body); + }); +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ date: string; id: string }> } +) { + const { date, id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return deleteDailyTodo(user.id, date, id); + }); +} diff --git a/apps/web/src/app/api/adventures/[date]/todos/route.ts b/apps/web/src/app/api/adventures/[date]/todos/route.ts new file mode 100755 index 0000000..43151d6 --- /dev/null +++ b/apps/web/src/app/api/adventures/[date]/todos/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { createDailyTodo } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return createDailyTodo(user.id, date, body.label); + }); +} diff --git a/apps/web/src/app/api/adventures/catch-up/route.ts b/apps/web/src/app/api/adventures/catch-up/route.ts new file mode 100644 index 0000000..39c956e --- /dev/null +++ b/apps/web/src/app/api/adventures/catch-up/route.ts @@ -0,0 +1,11 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { detectCatchUpGaps } from "@/lib/services/catch-up"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const gaps = await detectCatchUpGaps(user.id); + return { gaps }; + }); +} diff --git a/apps/web/src/app/api/ai/chat/knows/route.ts b/apps/web/src/app/api/ai/chat/knows/route.ts new file mode 100644 index 0000000..2f161a3 --- /dev/null +++ b/apps/web/src/app/api/ai/chat/knows/route.ts @@ -0,0 +1,10 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getWhatAiKnows } from "@/lib/services/ai-chat"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getWhatAiKnows(user.id); + }); +} diff --git a/apps/web/src/app/api/ai/chat/sessions/[id]/route.ts b/apps/web/src/app/api/ai/chat/sessions/[id]/route.ts new file mode 100644 index 0000000..8b34024 --- /dev/null +++ b/apps/web/src/app/api/ai/chat/sessions/[id]/route.ts @@ -0,0 +1,40 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getChatSession, sendChatMessage, archiveChatSession } from "@/lib/services/ai-chat"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const data = await getChatSession(user.id, id); + if (!data) throw new Error("Session not found"); + return data; + }); +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + await archiveChatSession(user.id, id); + return { ok: true }; + }); +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return sendChatMessage(user.id, id, body.content ?? ""); + }); +} diff --git a/apps/web/src/app/api/ai/chat/sessions/route.ts b/apps/web/src/app/api/ai/chat/sessions/route.ts new file mode 100644 index 0000000..5f32e31 --- /dev/null +++ b/apps/web/src/app/api/ai/chat/sessions/route.ts @@ -0,0 +1,19 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { listChatSessions, createChatSession } from "@/lib/services/ai-chat"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const sessions = await listChatSessions(user.id); + return { sessions }; + }); +} + +export async function POST(request: Request) { + const body = await request.json().catch(() => ({})); + return handleApi(async () => { + const { user } = await requireUser(); + return createChatSession(user.id, body.title, body.featureContext); + }); +} diff --git a/apps/web/src/app/api/ai/config/route.ts b/apps/web/src/app/api/ai/config/route.ts new file mode 100755 index 0000000..f43324e --- /dev/null +++ b/apps/web/src/app/api/ai/config/route.ts @@ -0,0 +1,33 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { + getAiBehaviorConfig, + getAiProviderConfig, + saveAiBehaviorConfig, + saveAiProviderConfig, +} from "@/lib/services/ai-config"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const behavior = await getAiBehaviorConfig(user.id); + const provider = await getAiProviderConfig(user.id); + return { behavior, provider }; + }); +} + +export async function PATCH(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + let behavior = await getAiBehaviorConfig(user.id); + let provider = await getAiProviderConfig(user.id); + if (body.behavior) { + behavior = await saveAiBehaviorConfig(user.id, body.behavior); + } + if (body.provider) { + provider = await saveAiProviderConfig(user.id, body.provider); + } + return { behavior, provider }; + }); +} diff --git a/apps/web/src/app/api/ai/context/preview/route.ts b/apps/web/src/app/api/ai/context/preview/route.ts new file mode 100644 index 0000000..aa40ded --- /dev/null +++ b/apps/web/src/app/api/ai/context/preview/route.ts @@ -0,0 +1,19 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { buildMentorContext, formatContextForPrompt } from "@/lib/services/ai-context"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const message = searchParams.get("message") ?? ""; + const feature = searchParams.get("feature") ?? "mentor"; + return handleApi(async () => { + const { user } = await requireUser(); + const ctx = await buildMentorContext(user.id, { userMessage: message, feature, logContext: false }); + return { + layers: ctx.layers, + tokenEstimate: ctx.tokenEstimate, + memoryIds: ctx.memoryIds, + formatted: formatContextForPrompt(ctx), + }; + }); +} diff --git a/apps/web/src/app/api/ai/health/route.ts b/apps/web/src/app/api/ai/health/route.ts new file mode 100755 index 0000000..8c0c801 --- /dev/null +++ b/apps/web/src/app/api/ai/health/route.ts @@ -0,0 +1,21 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getCachedHealth, runHealthCheck } from "@/lib/services/ai-config"; +import { getLastHealthLogs } from "@/lib/services/ai-config"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const cached = await getCachedHealth(user.id); + const logs = await getLastHealthLogs(user.id, 5); + return { health: cached, logs }; + }); +} + +export async function POST() { + return handleApi(async () => { + const { user } = await requireUser(); + const health = await runHealthCheck(user.id); + return { health }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/[id]/route.ts b/apps/web/src/app/api/ai/memory/[id]/route.ts new file mode 100644 index 0000000..6aaab85 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/[id]/route.ts @@ -0,0 +1,40 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getMemory, updateMemory, archiveMemory } from "@/lib/services/ai-memory"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const memory = await getMemory(user.id, id); + if (!memory) throw new Error("Memory not found"); + return memory; + }); +} + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return updateMemory(user.id, id, body); + }); +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + await archiveMemory(user.id, id); + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/learning/route.ts b/apps/web/src/app/api/ai/memory/learning/route.ts new file mode 100644 index 0000000..464e438 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/learning/route.ts @@ -0,0 +1,21 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { + getMemoryLearningSettings, + saveMemoryLearningSettings, +} from "@/lib/services/ai-memory"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getMemoryLearningSettings(user.id); + }); +} + +export async function PATCH(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return saveMemoryLearningSettings(user.id, body); + }); +} diff --git a/apps/web/src/app/api/ai/memory/reset/route.ts b/apps/web/src/app/api/ai/memory/reset/route.ts new file mode 100644 index 0000000..3554905 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/reset/route.ts @@ -0,0 +1,13 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { resetAllMemories } from "@/lib/services/ai-memory"; + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (!body.confirm) throw new Error("Confirmation required"); + await resetAllMemories(user.id); + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/route.ts b/apps/web/src/app/api/ai/memory/route.ts new file mode 100644 index 0000000..75dee7d --- /dev/null +++ b/apps/web/src/app/api/ai/memory/route.ts @@ -0,0 +1,32 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { + listMemories, + createMemory, + getProfileSummary, + listSuggestions, + exportMemories, +} from "@/lib/services/ai-memory"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + return handleApi(async () => { + const { user } = await requireUser(); + const category = searchParams.get("category") ?? undefined; + const q = searchParams.get("q") ?? undefined; + const enabledParam = searchParams.get("enabled"); + const enabled = enabledParam === null ? undefined : enabledParam === "true"; + const memories = await listMemories(user.id, { category, q, enabled }); + const summary = await getProfileSummary(user.id); + const pending = await listSuggestions(user.id, "pending"); + return { memories, summary, pendingCount: pending.length }; + }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return createMemory(user.id, body); + }); +} diff --git a/apps/web/src/app/api/ai/memory/suggestions/[id]/accept/route.ts b/apps/web/src/app/api/ai/memory/suggestions/[id]/accept/route.ts new file mode 100644 index 0000000..2a6f852 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/suggestions/[id]/accept/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { acceptSuggestion } from "@/lib/services/ai-memory"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json().catch(() => ({})); + return handleApi(async () => { + const { user } = await requireUser(); + return acceptSuggestion(user.id, id, body); + }); +} diff --git a/apps/web/src/app/api/ai/memory/suggestions/[id]/ignore/route.ts b/apps/web/src/app/api/ai/memory/suggestions/[id]/ignore/route.ts new file mode 100644 index 0000000..13066bf --- /dev/null +++ b/apps/web/src/app/api/ai/memory/suggestions/[id]/ignore/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { ignoreSuggestion } from "@/lib/services/ai-memory"; + +export async function POST( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + await ignoreSuggestion(user.id, id); + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/suggestions/[id]/reject/route.ts b/apps/web/src/app/api/ai/memory/suggestions/[id]/reject/route.ts new file mode 100644 index 0000000..7b7628f --- /dev/null +++ b/apps/web/src/app/api/ai/memory/suggestions/[id]/reject/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { rejectSuggestion } from "@/lib/services/ai-memory"; + +export async function POST( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + await rejectSuggestion(user.id, id); + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/suggestions/route.ts b/apps/web/src/app/api/ai/memory/suggestions/route.ts new file mode 100644 index 0000000..7f00d21 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/suggestions/route.ts @@ -0,0 +1,13 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { listSuggestions } from "@/lib/services/ai-memory"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const status = searchParams.get("status") ?? "pending"; + return handleApi(async () => { + const { user } = await requireUser(); + const suggestions = await listSuggestions(user.id, status); + return { suggestions }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/summary/rebuild/route.ts b/apps/web/src/app/api/ai/memory/summary/rebuild/route.ts new file mode 100644 index 0000000..8f09386 --- /dev/null +++ b/apps/web/src/app/api/ai/memory/summary/rebuild/route.ts @@ -0,0 +1,54 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { listMemories, saveProfileSummary } from "@/lib/services/ai-memory"; +import { getProvider } from "@/lib/ai/provider-registry"; +import { getAiBehaviorConfig, getAiProviderConfig, buildSystemPrompt } from "@/lib/services/ai-config"; +import { getTemplateBody } from "@/lib/services/ai-templates"; +import { renderTemplate } from "@/lib/ai/prompts/render"; + +export async function POST() { + return handleApi(async () => { + const { user } = await requireUser(); + const memories = await listMemories(user.id, { enabled: true }); + const verified = memories.filter((m) => m.userVerified); + + const bulletList = verified + .map((m) => `- [${m.category}] ${m.title}: ${m.content.slice(0, 120)}`) + .join("\n"); + + const behavior = await getAiBehaviorConfig(user.id); + const providerConfig = await getAiProviderConfig(user.id); + + let summaryText = verified.length === 0 + ? "No verified memories yet. Add memories manually to build your profile." + : bulletList.slice(0, 1500); + + if (behavior.enabled && providerConfig.enabled && verified.length > 0) { + try { + const coreSystem = await getTemplateBody(user.id, "system_core"); + const templateBody = await getTemplateBody(user.id, "mentor_summary"); + const system = buildSystemPrompt(behavior, coreSystem); + const prompt = renderTemplate(templateBody, { + user_name: user.displayName, + context: bulletList, + }); + const provider = getProvider(providerConfig.type); + const res = await provider.generateText(providerConfig, { + model: providerConfig.model, + prompt, + system, + format: "text", + temperature: 0.5, + maxTokens: 400, + timeoutMs: providerConfig.timeoutMs, + }); + if (res.text.trim()) summaryText = res.text.trim(); + } catch { + /* use bullet list fallback */ + } + } + + const summary = await saveProfileSummary(user.id, summaryText); + return { ...summary, sourceMemoryCount: verified.length }; + }); +} diff --git a/apps/web/src/app/api/ai/memory/summary/route.ts b/apps/web/src/app/api/ai/memory/summary/route.ts new file mode 100644 index 0000000..2605c0a --- /dev/null +++ b/apps/web/src/app/api/ai/memory/summary/route.ts @@ -0,0 +1,34 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { + getProfileSummary, + saveProfileSummary, + exportMemories, + importMemories, +} from "@/lib/services/ai-memory"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getProfileSummary(user.id); + }); +} + +export async function PATCH(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return saveProfileSummary(user.id, body.summary ?? ""); + }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "import") { + return importMemories(user.id, body.data, body.overwrite); + } + return exportMemories(user.id); + }); +} diff --git a/apps/web/src/app/api/ai/models/route.ts b/apps/web/src/app/api/ai/models/route.ts new file mode 100755 index 0000000..195431f --- /dev/null +++ b/apps/web/src/app/api/ai/models/route.ts @@ -0,0 +1,23 @@ +import { handleApi } from "@/lib/api"; +import { listProviderTypes } from "@/lib/ai/provider-registry"; +import { requireUser } from "@/lib/services/user"; +import { getAiProviderConfig } from "@/lib/services/ai-config"; +import { getProvider } from "@/lib/ai/provider-registry"; + +export async function GET() { + return handleApi(async () => { + const providers = listProviderTypes(); + return { providers }; + }); +} + +export async function POST() { + return handleApi(async () => { + const { user } = await requireUser(); + const config = await getAiProviderConfig(user.id); + const provider = getProvider(config.type); + if (!provider.listModels) return { models: [config.model] }; + const models = await provider.listModels(config); + return { models }; + }); +} diff --git a/apps/web/src/app/api/ai/suggestions/[id]/dismiss/route.ts b/apps/web/src/app/api/ai/suggestions/[id]/dismiss/route.ts new file mode 100755 index 0000000..fe80f3d --- /dev/null +++ b/apps/web/src/app/api/ai/suggestions/[id]/dismiss/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { dismissSuggestion } from "@/lib/services/explorations"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + await dismissSuggestion(id, user.id); + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/ai/suggestions/route.ts b/apps/web/src/app/api/ai/suggestions/route.ts new file mode 100755 index 0000000..94cde20 --- /dev/null +++ b/apps/web/src/app/api/ai/suggestions/route.ts @@ -0,0 +1,26 @@ +import { handleApi, jsonError } from "@/lib/api"; +import { getSuggestions, dismissSuggestion, generateDailyQuests } from "@/lib/services/explorations"; +import { requireUser } from "@/lib/services/user"; +import { isOllamaAvailable } from "@/lib/services/ai"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const role = searchParams.get("role") ?? undefined; + return handleApi(async () => { + const { user } = await requireUser(); + const suggestions = await getSuggestions(user.id, role); + const ollamaAvailable = await isOllamaAvailable(); + return { suggestions, ollamaAvailable }; + }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "generate_quests") { + return generateDailyQuests(user.id); + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/ai/templates/[key]/route.ts b/apps/web/src/app/api/ai/templates/[key]/route.ts new file mode 100755 index 0000000..c2d0451 --- /dev/null +++ b/apps/web/src/app/api/ai/templates/[key]/route.ts @@ -0,0 +1,64 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { + getPromptTemplate, + updatePromptTemplate, + resetPromptTemplate, + previewTemplate, + getTemplateVersions, + restoreTemplateVersion, +} from "@/lib/services/ai-templates"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ key: string }> } +) { + const { key } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const template = await getPromptTemplate(user.id, key); + const versions = await getTemplateVersions(user.id, key); + return { template, versions }; + }); +} + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ key: string }> } +) { + const { key } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + const template = await updatePromptTemplate(user.id, key, body); + return { template }; + }); +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ key: string }> } +) { + const { key } = await params; + const { searchParams } = new URL(request.url); + const action = searchParams.get("action"); + const body = await request.json().catch(() => ({})); + + return handleApi(async () => { + const { user } = await requireUser(); + + if (action === "reset") { + const template = await resetPromptTemplate(user.id, key); + return { template }; + } + if (action === "preview") { + const rendered = await previewTemplate(user.id, key, body.body); + return { rendered }; + } + if (action === "restore" && body.version) { + const template = await restoreTemplateVersion(user.id, key, body.version); + return { template }; + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/ai/templates/route.ts b/apps/web/src/app/api/ai/templates/route.ts new file mode 100755 index 0000000..28bfd3b --- /dev/null +++ b/apps/web/src/app/api/ai/templates/route.ts @@ -0,0 +1,12 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getPromptTemplates } from "@/lib/services/ai-templates"; +import { PLACEHOLDER_DOCS } from "@/lib/ai/prompts/defaults"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const templates = await getPromptTemplates(user.id); + return { templates, placeholders: PLACEHOLDER_DOCS }; + }); +} diff --git a/apps/web/src/app/api/auth/login/route.ts b/apps/web/src/app/api/auth/login/route.ts new file mode 100755 index 0000000..5ce9b82 --- /dev/null +++ b/apps/web/src/app/api/auth/login/route.ts @@ -0,0 +1,28 @@ +import { handleApi, jsonOk } from "@/lib/api"; +import { getSession, verifyPassword } from "@/lib/auth"; + +export async function POST(request: Request) { + return handleApi(async () => { + const { password } = await request.json(); + if (!verifyPassword(password)) { + throw new Error("Invalid password"); + } + const session = await getSession(); + session.isLoggedIn = true; + await session.save(); + return { ok: true }; + }); +} + +export async function DELETE() { + return handleApi(async () => { + const session = await getSession(); + session.destroy(); + return { ok: true }; + }); +} + +export async function GET() { + const session = await getSession(); + return jsonOk({ isLoggedIn: !!session.isLoggedIn }); +} diff --git a/apps/web/src/app/api/books/[id]/log-pages/route.ts b/apps/web/src/app/api/books/[id]/log-pages/route.ts new file mode 100755 index 0000000..df98ebe --- /dev/null +++ b/apps/web/src/app/api/books/[id]/log-pages/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { logPages } from "@/lib/services/reading"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return logPages(user.id, id, body.pages, body.date, body.note); + }); +} diff --git a/apps/web/src/app/api/books/[id]/route.ts b/apps/web/src/app/api/books/[id]/route.ts new file mode 100755 index 0000000..6c026b4 --- /dev/null +++ b/apps/web/src/app/api/books/[id]/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { updateBook } from "@/lib/services/reading"; +import { requireUser } from "@/lib/services/user"; + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return updateBook(id, user.id, body); + }); +} diff --git a/apps/web/src/app/api/books/route.ts b/apps/web/src/app/api/books/route.ts new file mode 100755 index 0000000..d791c56 --- /dev/null +++ b/apps/web/src/app/api/books/route.ts @@ -0,0 +1,18 @@ +import { handleApi } from "@/lib/api"; +import { getBooks, createBook } from "@/lib/services/reading"; +import { requireUser } from "@/lib/services/user"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getBooks(user.id); + }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return createBook(user.id, body); + }); +} diff --git a/apps/web/src/app/api/cartographer/route.ts b/apps/web/src/app/api/cartographer/route.ts new file mode 100755 index 0000000..a258007 --- /dev/null +++ b/apps/web/src/app/api/cartographer/route.ts @@ -0,0 +1,10 @@ +import { handleApi } from "@/lib/api"; +import { getCartographerDesk } from "@/lib/services/cartographer"; +import { requireUser } from "@/lib/services/user"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getCartographerDesk(user.id); + }); +} diff --git a/apps/web/src/app/api/cron/route.ts b/apps/web/src/app/api/cron/route.ts new file mode 100755 index 0000000..cad1525 --- /dev/null +++ b/apps/web/src/app/api/cron/route.ts @@ -0,0 +1,42 @@ +import { NextResponse } from "next/server"; +import { verifyCronSecret } from "@/lib/auth"; +import { requireUser } from "@/lib/services/user"; +import { materializeDay } from "@/lib/services/adventure"; +import { todayString } from "@/lib/dates"; +import { generateDailyQuests, generateWeeklyExplorations } from "@/lib/services/explorations"; +import { weekStartString } from "@/lib/dates"; +import { generateWeeklyReview } from "@/lib/services/explorations"; +import { pruneOldActions } from "@/lib/services/action-events"; + +export async function POST(request: Request) { + if (!verifyCronSecret(request)) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + const { user } = await requireUser(); + const { searchParams } = new URL(request.url); + const action = searchParams.get("action") ?? "materialize"; + + if (action === "materialize") { + await materializeDay(user.id, todayString()); + return NextResponse.json({ ok: true }); + } + if (action === "generate-quests") { + await generateDailyQuests(user.id); + return NextResponse.json({ ok: true }); + } + if (action === "generate-explorations") { + await generateWeeklyExplorations(user.id); + return NextResponse.json({ ok: true }); + } + if (action === "generate-weekly-review") { + await generateWeeklyReview(user.id, weekStartString()); + return NextResponse.json({ ok: true }); + } + if (action === "prune-actions") { + await pruneOldActions(user.id, 90); + return NextResponse.json({ ok: true }); + } + + return NextResponse.json({ error: "Unknown action" }, { status: 400 }); +} diff --git a/apps/web/src/app/api/dashboard/route.ts b/apps/web/src/app/api/dashboard/route.ts new file mode 100755 index 0000000..9ff9828 --- /dev/null +++ b/apps/web/src/app/api/dashboard/route.ts @@ -0,0 +1,8 @@ +import { handleApi } from "@/lib/api"; +import { getDashboard } from "@/lib/services/dashboard"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const date = searchParams.get("date") ?? undefined; + return handleApi(() => getDashboard(date)); +} diff --git a/apps/web/src/app/api/explorations/[id]/route.ts b/apps/web/src/app/api/explorations/[id]/route.ts new file mode 100755 index 0000000..8f6649d --- /dev/null +++ b/apps/web/src/app/api/explorations/[id]/route.ts @@ -0,0 +1,29 @@ +import { handleApi } from "@/lib/api"; +import { + acceptExploration, + completeExploration, + dismissExploration, +} from "@/lib/services/explorations"; +import { requireUser } from "@/lib/services/user"; +import { todayString } from "@/lib/dates"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "accept") { + return acceptExploration(id, user.id); + } + if (body.action === "complete") { + return completeExploration(id, user.id, body.note ?? "", body.date ?? todayString()); + } + if (body.action === "dismiss" || body.action === "deny") { + return dismissExploration(id, user.id); + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/explorations/route.ts b/apps/web/src/app/api/explorations/route.ts new file mode 100755 index 0000000..f4ba1cb --- /dev/null +++ b/apps/web/src/app/api/explorations/route.ts @@ -0,0 +1,33 @@ +import { handleApi } from "@/lib/api"; +import { + getExplorations, + generateWeeklyExplorations, + acceptExploration, + completeExploration, + dismissExploration, + getExplorationHistory, +} from "@/lib/services/explorations"; +import { requireUser } from "@/lib/services/user"; +import { todayString } from "@/lib/dates"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const weekOf = searchParams.get("week_of") ?? undefined; + const history = searchParams.get("history") === "true"; + return handleApi(async () => { + const { user } = await requireUser(); + if (history) return getExplorationHistory(user.id); + return getExplorations(user.id, weekOf); + }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "generate") { + return generateWeeklyExplorations(user.id); + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/export/json/route.ts b/apps/web/src/app/api/export/json/route.ts new file mode 100755 index 0000000..2f52c60 --- /dev/null +++ b/apps/web/src/app/api/export/json/route.ts @@ -0,0 +1,25 @@ +import { eq } from "drizzle-orm"; +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { db } from "@/lib/db"; +import * as schema from "@adventureos/db/schema"; +import { exportMemories } from "@/lib/services/ai-memory"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const aiData = await exportMemories(user.id); + const tables = { + user: await db.select().from(schema.users).where(eq(schema.users.id, user.id)), + progress: await db.select().from(schema.userProgress), + templates: await db.select().from(schema.adventureTemplates), + books: await db.select().from(schema.books), + achievements: await db.select().from(schema.achievements), + reflections: await db.select().from(schema.reflections), + aiMemories: aiData.memories, + aiProfileSummary: aiData.summary, + aiMemoryLearning: aiData.learning, + }; + return tables; + }); +} \ No newline at end of file diff --git a/apps/web/src/app/api/library/books/route.ts b/apps/web/src/app/api/library/books/route.ts new file mode 100755 index 0000000..073710a --- /dev/null +++ b/apps/web/src/app/api/library/books/route.ts @@ -0,0 +1,31 @@ +import { handleApi } from "@/lib/api"; +import { listCalibreBooks } from "@/lib/services/calibre"; +import { getReadingProgress } from "@/lib/services/calibre-reading"; +import { requireUser } from "@/lib/services/user"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const search = searchParams.get("search") ?? undefined; + const limit = Number(searchParams.get("limit") ?? "200"); + const offset = Number(searchParams.get("offset") ?? "0"); + + return handleApi(async () => { + const { user } = await requireUser(); + const books = await listCalibreBooks({ search, limit, offset }); + const progress = await getReadingProgress(user.id); + const progressMap = new Map(progress.map((p) => [p.calibreBookId, p])); + + return books.map((b) => { + const p = progressMap.get(b.id); + return { + ...b, + currentPage: p?.currentPage ?? 0, + totalPages: p?.totalPages ?? 300, + status: p?.status ?? "unread", + progressPercent: p + ? Math.round((p.currentPage / Math.max(p.totalPages, 1)) * 100) + : 0, + }; + }); + }); +} diff --git a/apps/web/src/app/api/library/cover/[id]/route.ts b/apps/web/src/app/api/library/cover/[id]/route.ts new file mode 100755 index 0000000..f03fe29 --- /dev/null +++ b/apps/web/src/app/api/library/cover/[id]/route.ts @@ -0,0 +1,30 @@ +import fs from "fs"; +import { resolveCoverPath } from "@/lib/services/calibre"; +import { requireUser } from "@/lib/services/user"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + try { + const { id } = await params; + const bookId = Number(id); + if (!Number.isFinite(bookId)) { + return new Response("Invalid id", { status: 400 }); + } + + await requireUser(); + const coverPath = resolveCoverPath(bookId); + if (!coverPath) { + return new Response("Cover not found", { status: 404 }); + } + const buffer = fs.readFileSync(coverPath); + return new Response(buffer, { + headers: { "Content-Type": "image/jpeg", "Cache-Control": "private, max-age=3600" }, + }); + } catch (e) { + const msg = e instanceof Error ? e.message : "Error"; + if (msg === "Unauthorized") return new Response(msg, { status: 401 }); + return new Response(msg, { status: 500 }); + } +} diff --git a/apps/web/src/app/api/library/progress/[id]/route.ts b/apps/web/src/app/api/library/progress/[id]/route.ts new file mode 100755 index 0000000..797ffe4 --- /dev/null +++ b/apps/web/src/app/api/library/progress/[id]/route.ts @@ -0,0 +1,23 @@ +import { handleApi } from "@/lib/api"; +import { logCalibrePages } from "@/lib/services/calibre-reading"; +import { requireUser } from "@/lib/services/user"; +import { todayString } from "@/lib/dates"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const calibreBookId = Number(id); + const body = await request.json(); + + return handleApi(async () => { + const { user } = await requireUser(); + return logCalibrePages( + user.id, + calibreBookId, + body.pages ?? 10, + body.date ?? todayString() + ); + }); +} diff --git a/apps/web/src/app/api/library/status/route.ts b/apps/web/src/app/api/library/status/route.ts new file mode 100755 index 0000000..d41cb4f --- /dev/null +++ b/apps/web/src/app/api/library/status/route.ts @@ -0,0 +1,10 @@ +import { handleApi } from "@/lib/api"; +import { getCalibreStatus } from "@/lib/services/calibre"; +import { requireUser } from "@/lib/services/user"; + +export async function GET() { + return handleApi(async () => { + await requireUser(); + return getCalibreStatus(); + }); +} diff --git a/apps/web/src/app/api/reflections/[date]/route.ts b/apps/web/src/app/api/reflections/[date]/route.ts new file mode 100755 index 0000000..1ce805c --- /dev/null +++ b/apps/web/src/app/api/reflections/[date]/route.ts @@ -0,0 +1,26 @@ +import { handleApi } from "@/lib/api"; +import { saveReflection, getReflection } from "@/lib/services/reflection"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + return saveReflection(user.id, date, body); + }); +} + +export async function GET( + _request: Request, + { params }: { params: Promise<{ date: string }> } +) { + const { date } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return getReflection(user.id, date); + }); +} diff --git a/apps/web/src/app/api/reviews/[weekStart]/route.ts b/apps/web/src/app/api/reviews/[weekStart]/route.ts new file mode 100755 index 0000000..4592f4c --- /dev/null +++ b/apps/web/src/app/api/reviews/[weekStart]/route.ts @@ -0,0 +1,37 @@ +import { handleApi } from "@/lib/api"; +import { + getWeeklyReview, + generateWeeklyReview, + setReviewIntention, +} from "@/lib/services/explorations"; +import { requireUser } from "@/lib/services/user"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ weekStart: string }> } +) { + const { weekStart } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return getWeeklyReview(user.id, weekStart); + }); +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ weekStart: string }> } +) { + const { weekStart } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "generate") { + return generateWeeklyReview(user.id, weekStart); + } + if (body.intention) { + await setReviewIntention(user.id, weekStart, body.intention); + return { ok: true }; + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/settings/day-boundary/route.ts b/apps/web/src/app/api/settings/day-boundary/route.ts new file mode 100644 index 0000000..14c7885 --- /dev/null +++ b/apps/web/src/app/api/settings/day-boundary/route.ts @@ -0,0 +1,20 @@ +import { handleApi } from "@/lib/api"; +import { requireUser } from "@/lib/services/user"; +import { getDayBoundaryHour, setDayBoundaryHour } from "@/lib/services/day-boundary"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const hour = await getDayBoundaryHour(user.id); + return { hour }; + }); +} + +export async function PATCH(request: Request) { + return handleApi(async () => { + const { user } = await requireUser(); + const body = await request.json(); + const hour = await setDayBoundaryHour(user.id, body.hour ?? 0); + return { hour }; + }); +} diff --git a/apps/web/src/app/api/settings/route.ts b/apps/web/src/app/api/settings/route.ts new file mode 100755 index 0000000..d6b9eee --- /dev/null +++ b/apps/web/src/app/api/settings/route.ts @@ -0,0 +1,58 @@ +import { handleApi } from "@/lib/api"; +import { requireUser, updateUserProfile } from "@/lib/services/user"; +import { db, spiritualConfig } from "@/lib/db"; +import { eq } from "drizzle-orm"; +import { normalizeSettingsTheme } from "@/lib/services/theme-migration"; +import { migrateUserThemeInDb } from "@/lib/services/theme-migration"; +import { seedPromptTemplatesForUser } from "@/lib/services/ai-templates"; +import { getSettingsForUser, upsertSetting } from "@/lib/repositories/settings.repository"; +import { parseJsonBody, settingsPatchSchema } from "@/lib/validation"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + const allSettings = await getSettingsForUser(user.id); + const settingsMap = Object.fromEntries(allSettings.map((s) => [s.key, s.value])); + const migratedTheme = await migrateUserThemeInDb( + user.id, + settingsMap.theme as string | undefined + ); + settingsMap.theme = migratedTheme; + const [spiritual] = await db + .select() + .from(spiritualConfig) + .where(eq(spiritualConfig.userId, user.id)); + await seedPromptTemplatesForUser(user.id); + return { + user, + settings: normalizeSettingsTheme(settingsMap), + spiritual, + }; + }); +} + +export async function PATCH(request: Request) { + return handleApi(async () => { + const body = await parseJsonBody(request, settingsPatchSchema); + const { user } = await requireUser(); + + if (body.profile) { + await updateUserProfile(user.id, body.profile); + } + if (body.settings) { + for (const [key, value] of Object.entries(body.settings)) { + await upsertSetting(user.id, key, value); + } + } + if (body.spiritual) { + await db + .update(spiritualConfig) + .set({ + prayerLabels: body.spiritual.prayerLabels, + litanyLabels: body.spiritual.litanyLabels, + }) + .where(eq(spiritualConfig.userId, user.id)); + } + return { ok: true }; + }); +} diff --git a/apps/web/src/app/api/stats/[domain]/route.ts b/apps/web/src/app/api/stats/[domain]/route.ts new file mode 100755 index 0000000..a52b8f6 --- /dev/null +++ b/apps/web/src/app/api/stats/[domain]/route.ts @@ -0,0 +1,15 @@ +import { handleApi } from "@/lib/api"; +import { getStatsOverview, getStatsDomain } from "@/lib/services/dashboard"; + +export async function GET( + request: Request, + { params }: { params: Promise<{ domain: string }> } +) { + const { domain } = await params; + const { searchParams } = new URL(request.url); + const range = Number(searchParams.get("range") ?? 30); + return handleApi(async () => { + if (domain === "overview") return getStatsOverview(); + return getStatsDomain(domain, range); + }); +} diff --git a/apps/web/src/app/api/teacher/[id]/route.ts b/apps/web/src/app/api/teacher/[id]/route.ts new file mode 100755 index 0000000..a743888 --- /dev/null +++ b/apps/web/src/app/api/teacher/[id]/route.ts @@ -0,0 +1,31 @@ +import { handleApi } from "@/lib/api"; +import { getTeacherLesson, completeTeacherLesson } from "@/lib/services/teacher"; +import { requireUser } from "@/lib/services/user"; + +export async function GET( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + const lesson = await getTeacherLesson(user.id, id); + if (!lesson) throw new Error("Lesson not found"); + return lesson; + }); +} + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "complete") { + return completeTeacherLesson(user.id, id, body.completedNote ?? ""); + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/teacher/route.ts b/apps/web/src/app/api/teacher/route.ts new file mode 100755 index 0000000..8ab5241 --- /dev/null +++ b/apps/web/src/app/api/teacher/route.ts @@ -0,0 +1,34 @@ +import { handleApi } from "@/lib/api"; +import { createTeacherLesson, getTeacherHistory } from "@/lib/services/teacher"; +import { requireUser } from "@/lib/services/user"; +import { parseJsonBody } from "@/lib/validation"; +import { + teacherCreateSchema, + normalizeTeacherCreateBody, +} from "@/lib/validation/schemas"; + +export async function POST(request: Request) { + return handleApi(async () => { + // #region agent log + fetch('http://127.0.0.1:7257/ingest/abfa22e4-3d86-4176-9679-7c59b1f0489f',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'04e12c'},body:JSON.stringify({sessionId:'04e12c',location:'api/teacher/route.ts:POST',message:'teacher POST start',data:{},timestamp:Date.now(),hypothesisId:'H1'})}).catch(()=>{}); + // #endregion + const parsed = await parseJsonBody(request, teacherCreateSchema); + const body = normalizeTeacherCreateBody(parsed); + // #region agent log + fetch('http://127.0.0.1:7257/ingest/abfa22e4-3d86-4176-9679-7c59b1f0489f',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'04e12c'},body:JSON.stringify({sessionId:'04e12c',location:'api/teacher/route.ts:POST',message:'teacher body validated',data:{topicLen:body.topic.length,hasExplorationId:!!body.explorationId},timestamp:Date.now(),hypothesisId:'H1'})}).catch(()=>{}); + // #endregion + const { user } = await requireUser(); + const result = await createTeacherLesson(user.id, body); + // #region agent log + fetch('http://127.0.0.1:7257/ingest/abfa22e4-3d86-4176-9679-7c59b1f0489f',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'04e12c'},body:JSON.stringify({sessionId:'04e12c',location:'api/teacher/route.ts:POST',message:'teacher lesson created',data:{source:result.source,lessonId:result.id},timestamp:Date.now(),hypothesisId:'H2'})}).catch(()=>{}); + // #endregion + return result; + }); +} + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getTeacherHistory(user.id); + }); +} diff --git a/apps/web/src/app/api/templates/[id]/items/route.ts b/apps/web/src/app/api/templates/[id]/items/route.ts new file mode 100755 index 0000000..fe2a2af --- /dev/null +++ b/apps/web/src/app/api/templates/[id]/items/route.ts @@ -0,0 +1,32 @@ +import { handleApi } from "@/lib/api"; +import { upsertTemplateItem, deleteTemplateItem, verifyTemplateOwnership } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + await verifyTemplateOwnership(user.id, id); + const itemId = await upsertTemplateItem(id, body); + return { id: itemId }; + }); +} + +export async function DELETE( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const { searchParams } = new URL(request.url); + const itemId = searchParams.get("itemId"); + if (!itemId) throw new Error("itemId required"); + return handleApi(async () => { + const { user } = await requireUser(); + const result = await deleteTemplateItem(itemId, user.id); + return { ok: true, ...result }; + }); +} diff --git a/apps/web/src/app/api/templates/[id]/route.ts b/apps/web/src/app/api/templates/[id]/route.ts new file mode 100755 index 0000000..b298e74 --- /dev/null +++ b/apps/web/src/app/api/templates/[id]/route.ts @@ -0,0 +1,47 @@ +import { handleApi } from "@/lib/api"; +import { + updateTemplate, + deleteTemplate, + duplicateTemplate, + verifyTemplateOwnership, +} from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + await verifyTemplateOwnership(user.id, id); + return updateTemplate(user.id, id, body); + }); +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + return handleApi(async () => { + const { user } = await requireUser(); + return deleteTemplate(user.id, id); + }); +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params; + const body = await request.json(); + return handleApi(async () => { + const { user } = await requireUser(); + if (body.action === "duplicate") { + return duplicateTemplate(user.id, id); + } + throw new Error("Unknown action"); + }); +} diff --git a/apps/web/src/app/api/templates/route.ts b/apps/web/src/app/api/templates/route.ts new file mode 100755 index 0000000..66a241e --- /dev/null +++ b/apps/web/src/app/api/templates/route.ts @@ -0,0 +1,19 @@ +import { handleApi } from "@/lib/api"; +import { getTemplates, createTemplate } from "@/lib/services/adventure"; +import { requireUser } from "@/lib/services/user"; +import { parseJsonBody, templateCreateSchema } from "@/lib/validation"; + +export async function GET() { + return handleApi(async () => { + const { user } = await requireUser(); + return getTemplates(user.id); + }); +} + +export async function POST(request: Request) { + return handleApi(async () => { + const body = await parseJsonBody(request, templateCreateSchema); + const { user } = await requireUser(); + return createTemplate(user.id, body); + }); +} diff --git a/apps/web/src/app/api/themes/route.ts b/apps/web/src/app/api/themes/route.ts new file mode 100755 index 0000000..812cb46 --- /dev/null +++ b/apps/web/src/app/api/themes/route.ts @@ -0,0 +1,6 @@ +import { jsonOk } from "@/lib/api"; +import { THEMES } from "@/themes/registry"; + +export async function GET() { + return jsonOk({ themes: THEMES }); +} diff --git a/apps/web/src/app/cartographer/page.tsx b/apps/web/src/app/cartographer/page.tsx new file mode 100755 index 0000000..d755bf5 --- /dev/null +++ b/apps/web/src/app/cartographer/page.tsx @@ -0,0 +1,311 @@ +"use client"; + +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { AppShell } from "@/components/layout/app-shell"; +import Link from "next/link"; +import { useState } from "react"; +import { useUiStore } from "@/stores/ui"; + +interface Exploration { + id: string; + title: string; + description: string; + category: string; + status: string; + completedNote?: string | null; + minutes?: number | null; +} + +export default function CartographerPage() { + const qc = useQueryClient(); + const showXpToast = useUiStore((s) => s.showXpToast); + const showActionToast = useUiStore((s) => s.showActionToast); + const [tab, setTab] = useState<"active" | "history">("active"); + const [completeId, setCompleteId] = useState(null); + const [note, setNote] = useState(""); + + const { data: desk, isLoading: deskLoading, error: deskError } = useQuery({ + queryKey: ["cartographer-desk"], + queryFn: async () => { + const res = await fetch("/api/cartographer"); + if (!res.ok) throw new Error("Failed to load map desk"); + return res.json(); + }, + }); + + const { data: explorations = [], isLoading, error } = useQuery({ + queryKey: ["explorations"], + queryFn: async () => { + const res = await fetch("/api/explorations"); + if (!res.ok) throw new Error("Failed to load explorations"); + const data = await res.json(); + if (data.error) throw new Error(data.error); + return Array.isArray(data) ? data : []; + }, + }); + + const { data: history = [] } = useQuery({ + queryKey: ["explorations-history"], + queryFn: async () => { + const res = await fetch("/api/explorations?history=true"); + if (!res.ok) throw new Error("Failed"); + const data = await res.json(); + return Array.isArray(data) ? data : []; + }, + enabled: tab === "history", + }); + + const [generateSource, setGenerateSource] = useState<"ai" | "fallback" | "existing" | null>( + null + ); + + const generate = useMutation({ + mutationFn: async () => { + const res = await fetch("/api/explorations", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "generate" }), + }); + if (!res.ok) throw new Error("Generate failed"); + const data = await res.json(); + if (data.error) throw new Error(data.error); + return data as { + explorations: Exploration[]; + source?: "ai" | "fallback" | "existing"; + }; + }, + onSuccess: (data) => { + setGenerateSource(data.source ?? null); + qc.invalidateQueries({ queryKey: ["explorations"] }); + }, + }); + + const generateNotice = + generateSource === "existing" + ? "You still have suggested quests to review — finish or deny them before generating more." + : generateSource === "fallback" + ? "AI unavailable — showing curated offline quest suggestions." + : null; + + const action = useMutation({ + mutationFn: async ({ id, action, note }: { id: string; action: string; note?: string }) => { + const res = await fetch(`/api/explorations/${id}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action, note }), + }); + if (!res.ok) throw new Error("Action failed"); + return res.json(); + }, + onSuccess: (data, vars) => { + qc.invalidateQueries({ queryKey: ["explorations"] }); + qc.invalidateQueries({ queryKey: ["explorations-history"] }); + qc.invalidateQueries({ queryKey: ["dashboard"] }); + qc.invalidateQueries({ queryKey: ["cartographer-desk"] }); + if (vars.action === "complete") showXpToast(100, "Exploration complete"); + if (data.actionEventId) { + showActionToast(`Exploration ${vars.action}`, data.actionEventId); + } + setCompleteId(null); + setNote(""); + }, + }); + + const suggested = explorations.filter((e: Exploration) => e.status === "suggested"); + const active = explorations.filter((e: Exploration) => e.status === "active"); + + return ( + +
+
+

The Cartographer's Desk

+ +
+ + {generate.isError && ( +

+ Could not generate quests. Check AI Health in Settings. +

+ )} + + {generateNotice && ( +

{generateNotice}

+ )} + + {generateSource === "fallback" && !generateNotice && ( +

+ AI is offline — showing curated offline quest suggestions. +

+ )} + + {!deskLoading && desk && ( + <> +
+ {desk.domains?.map((d: { key: string; label: string; score: number }) => ( +
+

{d.label}

+

{d.score}

+
+
+
+
+ ))} +
+ {desk.horizon?.intention && ( +

+ Horizon: {desk.horizon.intention} +

+ )} + + )} + {deskError && ( +

Could not load life map scores.

+ )} + +

+ Optional curiosity quests — pick what interests you this week. +

+ +
+ + +
+ + {tab === "active" && ( + <> + {isLoading ? ( +

Loading map...

+ ) : error ? ( +

Failed to load explorations.

+ ) : ( +
+ {suggested.map((e: Exploration) => ( + action.mutate({ id: e.id, action: "accept" })} + onDismiss={() => action.mutate({ id: e.id, action: "dismiss" })} + /> + ))} + {active.map((e: Exploration) => ( + setCompleteId(e.id)} + /> + ))} + {suggested.length === 0 && active.length === 0 && ( +

+ No explorations this week. Generate some quests — dismissed quests won't block new ones. +

+ )} +
+ )} + + )} + + {tab === "history" && ( +
+ {history.map((e: Exploration) => ( + + ✓ {e.title} + + ))} +
+ )} + + {completeId && ( +
+
+

What did you learn?

+ setNote(e.target.value)} + placeholder="One thing you discovered..." + /> + +
+
+ )} +
+ + ); +} + +function QuestCard({ + exploration, + active, + onAccept, + onDismiss, + onComplete, +}: { + exploration: Exploration; + active?: boolean; + onAccept?: () => void; + onDismiss?: () => void; + onComplete?: () => void; +}) { + return ( +
+ + {exploration.category} + +

{exploration.title}

+

{exploration.description}

+ {exploration.minutes && ( +

~{exploration.minutes} min

+ )} +
+ {active ? ( + <> + + + Study with Teacher + + + ) : ( + <> + + + + )} +
+
+ ); +} diff --git a/apps/web/src/app/favicon.ico b/apps/web/src/app/favicon.ico new file mode 100755 index 0000000000000000000000000000000000000000..718d6fea4835ec2d246af9800eddb7ffb276240c GIT binary patch literal 25931 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 LrJugUA?W`A8`#=m literal 0 HcmV?d00001 diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css new file mode 100755 index 0000000..6ce03ed --- /dev/null +++ b/apps/web/src/app/globals.css @@ -0,0 +1,215 @@ +@import "tailwindcss"; +@import "../themes/index.css"; + +* { + box-sizing: border-box; +} + +body { + margin: 0; + font-family: var(--font-sans); + font-size: calc(14px * var(--density)); + color: var(--color-text); + background-color: var(--color-body-bg); + background-image: var(--color-body-bg-image); + background-size: cover; + background-attachment: fixed; + min-height: 100vh; +} + +body::after { + content: ""; + position: fixed; + inset: 0; + pointer-events: none; + background: var(--effect-scanlines); + z-index: 9999; +} + +@theme inline { + --color-xp-blue: var(--color-accent); + --color-bliss-green: var(--color-positive); + --color-parchment: var(--color-surface); + --color-gold: var(--color-gold); + --color-ink: var(--color-text); + --font-sans: var(--font-sans); + --font-serif: var(--font-serif); +} + +.retro-window { + background: var(--color-surface); + border: 2px solid; + border-color: var(--color-border-light) var(--color-border-dark) var(--color-border-dark) + var(--color-border-light); + box-shadow: var(--window-shadow); +} + +.retro-window-inset { + border: 2px solid; + border-color: var(--color-border-dark) var(--color-border-light) var(--color-border-light) + var(--color-border-dark); + background: var(--color-surface-inset); + color: var(--color-text); +} + +.retro-titlebar { + background: linear-gradient( + 180deg, + var(--color-titlebar-start) 0%, + var(--color-titlebar-mid) 8%, + var(--color-titlebar-end) 100% + ); + color: var(--color-accent-text); + padding: 4px 8px; + font-weight: bold; + font-size: 13px; + display: flex; + align-items: center; + justify-content: space-between; + user-select: none; +} + +.retro-btn { + background: linear-gradient(180deg, var(--color-surface-raised) 0%, var(--color-surface) 100%); + border: 2px solid; + border-color: var(--color-border-light) var(--color-border-dark) var(--color-border-dark) + var(--color-border-light); + padding: 4px 12px; + font-family: var(--font-sans); + font-size: 13px; + color: var(--color-text); + cursor: pointer; +} + +.retro-btn:hover { + background: linear-gradient(180deg, var(--color-surface-raised) 0%, var(--color-btn-hover) 100%); +} + +.retro-btn:active { + border-color: var(--color-border-dark) var(--color-border-light) var(--color-border-light) + var(--color-border-dark); + padding: 5px 11px 3px 13px; +} + +.retro-btn-primary { + background: linear-gradient(180deg, var(--color-btn-primary-start) 0%, var(--color-accent) 100%); + color: var(--color-accent-text); + border-color: var(--color-btn-primary-border-light) var(--color-btn-primary-border-dark) + var(--color-btn-primary-border-dark) var(--color-btn-primary-border-light); +} + +.skill-bar-track { + height: 14px; + background: var(--color-skill-track); + border: 1px solid var(--color-border-dark); + box-shadow: inset 1px 1px 2px rgba(0, 0, 0, 0.3); + position: relative; + overflow: hidden; +} + +.skill-bar-fill { + height: 100%; + background: linear-gradient( + 180deg, + color-mix(in srgb, var(--color-skill-fill) 80%, white) 0%, + var(--color-skill-fill) 50%, + color-mix(in srgb, var(--color-skill-fill) 70%, black) 100% + ); + border-right: 1px solid var(--color-gold); + transition: width 600ms ease-out; +} + +.skill-bar-fill-gold { + background: linear-gradient( + 180deg, + color-mix(in srgb, var(--color-skill-fill-gold) 80%, white) 0%, + var(--color-skill-fill-gold) 50%, + color-mix(in srgb, var(--color-skill-fill-gold) 60%, black) 100% + ); +} + +@media (prefers-reduced-motion: reduce) { + .skill-bar-fill { + transition: none; + } +} + +.serif { + font-family: var(--font-serif); +} + +.xp-toast { + animation: slideUp 200ms ease-out, fadeOut 3s ease-in 2s forwards; +} + +.action-toast { + animation: slideUp 200ms ease-out; +} + +@keyframes slideUp { + from { + transform: translateY(20px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +@keyframes fadeOut { + to { + opacity: 0; + } +} + +.book-spine { + writing-mode: vertical-rl; + text-orientation: mixed; + transform: rotate(180deg); + min-height: 120px; + padding: 8px 4px; + border-radius: 2px 4px 4px 2px; + cursor: pointer; + transition: transform 150ms; +} + +.book-spine:hover { + transform: rotate(180deg) translateY(-4px); +} + +.parchment-bg { + background: var(--color-surface); + background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.03'/%3E%3C/svg%3E"); +} + +.theme-preview-card { + cursor: pointer; + transition: transform 150ms, box-shadow 150ms; +} + +.theme-preview-card:hover { + transform: translateY(-2px); +} + +.theme-preview-card.selected { + outline: 2px solid var(--color-accent); + outline-offset: 2px; +} + +.theme-preview-bar { + height: 20px; + border-radius: 2px 2px 0 0; +} + +.theme-preview-body { + padding: 8px; + display: flex; + gap: 4px; +} + +.theme-preview-swatch { + width: 16px; + height: 16px; + border-radius: 2px; +} diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx new file mode 100755 index 0000000..c7dbb93 --- /dev/null +++ b/apps/web/src/app/layout.tsx @@ -0,0 +1,44 @@ +import type { Metadata, Viewport } from "next"; +import "./globals.css"; +import { Providers } from "@/components/providers"; +import { XpToast, ActionToast, BookCelebration, WelcomeBack } from "@/components/retro/overlays"; + +export const metadata: Metadata = { + title: "AdventureOS", + description: "Your personal command centre for consistency and growth", + manifest: "/manifest.json", + appleWebApp: { capable: true, title: "AdventureOS" }, +}; + +export const viewport: Viewport = { + themeColor: "#3A6EA5", + width: "device-width", + initialScale: 1, +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + +