From a25a892ae51c5e4bc6468466fe9d26f4cee41143 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 12 Jul 2026 07:30:05 +0000 Subject: [PATCH] feat: implement message type/name persistence, rehydration and calendar date fixes Co-authored-by: ngoiyaeric <115367894+ngoiyaeric@users.noreply.github.com> --- app/actions.tsx | 8 +- app/search/[id]/page.tsx | 11 +- .../migrations/0009_add_message_type_name.sql | 3 + drizzle/migrations/meta/0006_snapshot.json | 989 ++++++++++++++++++ drizzle/migrations/meta/_journal.json | 7 + lib/actions/calendar.ts | 37 +- lib/actions/chat-db.ts | 16 +- lib/actions/chat.ts | 16 +- lib/db/schema.ts | 2 + public/sw.js | 2 +- tests/targeted.test.ts | 146 +++ 11 files changed, 1206 insertions(+), 31 deletions(-) create mode 100644 drizzle/migrations/0009_add_message_type_name.sql create mode 100644 drizzle/migrations/meta/0006_snapshot.json create mode 100644 tests/targeted.test.ts diff --git a/app/actions.tsx b/app/actions.tsx index cfc66e71..12b351f8 100644 --- a/app/actions.tsx +++ b/app/actions.tsx @@ -661,7 +661,7 @@ export const AI = createAI({ userId: actualUserId, path, title, - messages: updatedMessages + messages: updatedMessages.filter(msg => !(msg.content === 'end' && msg.type === 'end')) } await saveChat(chat, actualUserId) } @@ -710,6 +710,8 @@ export const getUIStateFromAIState = (aiState: AIState): UIState => { id, component: } + default: + return null } break case 'assistant': @@ -770,6 +772,8 @@ export const getUIStateFromAIState = (aiState: AIState): UIState => { ) } } + default: + return null } break case 'tool': @@ -868,5 +872,5 @@ export const getUIStateFromAIState = (aiState: AIState): UIState => { } } }) - .filter(message => message !== null) as UIState + .filter(message => message !== null && message !== undefined) as UIState } diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx index 8db74186..9e2c0349 100644 --- a/app/search/[id]/page.tsx +++ b/app/search/[id]/page.tsx @@ -18,7 +18,7 @@ export async function generateMetadata({ params }: SearchPageProps) { // TODO: Metadata generation might need authenticated user if chats are private // For now, assuming getChat can be called or it handles anon access for metadata appropriately const userId = await getCurrentUserIdOnServer(); // Attempt to get user for metadata - const chat = await getChat(id, userId || 'anonymous'); // Pass userId or 'anonymous' if none + const chat = await getChat(id, userId || undefined); // Pass userId or undefined if none (allows public fallback) return { title: chat?.title?.toString().slice(0, 50) || 'Search', }; @@ -48,14 +48,11 @@ export default async function SearchPage({ params }: SearchPageProps) { const initialMessages: AIMessage[] = dbMessages.map((dbMsg): AIMessage => { return { id: dbMsg.id, - role: dbMsg.role as AIMessage['role'], // Cast role, ensure AIMessage['role'] includes all dbMsg.role possibilities + role: dbMsg.role as AIMessage['role'], content: dbMsg.content, createdAt: dbMsg.createdAt ? new Date(dbMsg.createdAt) : undefined, - // 'type' and 'name' are not in the basic Drizzle 'messages' schema. - // These would be undefined unless specific logic is added to derive them. - // For instance, if a message with role 'tool' should have a 'name', - // or if some messages have a specific 'type' based on content or other flags. - // This mapping assumes standard user/assistant messages primarily. + type: dbMsg.type ? (dbMsg.type as AIMessage['type']) : undefined, + name: dbMsg.name || undefined, }; }); diff --git a/drizzle/migrations/0009_add_message_type_name.sql b/drizzle/migrations/0009_add_message_type_name.sql new file mode 100644 index 00000000..955f2182 --- /dev/null +++ b/drizzle/migrations/0009_add_message_type_name.sql @@ -0,0 +1,3 @@ +ALTER TABLE "messages" ADD COLUMN "type" text; +--> statement-breakpoint +ALTER TABLE "messages" ADD COLUMN "name" text; diff --git a/drizzle/migrations/meta/0006_snapshot.json b/drizzle/migrations/meta/0006_snapshot.json new file mode 100644 index 00000000..1e33b421 --- /dev/null +++ b/drizzle/migrations/meta/0006_snapshot.json @@ -0,0 +1,989 @@ +{ + "id": "13fa067e-fa56-4d84-9ffc-fbc4b215f295", + "prevId": "fd89f5aa-13b0-4dd4-9f50-4e921eea0f4f", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.calendar_notes": { + "name": "calendar_notes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "date": { + "name": "date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location_tags": { + "name": "location_tags", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "user_tags": { + "name": "user_tags", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "map_feature_id": { + "name": "map_feature_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "calendar_notes_user_id_users_id_fk": { + "name": "calendar_notes_user_id_users_id_fk", + "tableFrom": "calendar_notes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "calendar_notes_chat_id_chats_id_fk": { + "name": "calendar_notes_chat_id_chats_id_fk", + "tableFrom": "calendar_notes", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chat_participants": { + "name": "chat_participants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'collaborator'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "chat_participants_chat_id_chats_id_fk": { + "name": "chat_participants_chat_id_chats_id_fk", + "tableFrom": "chat_participants", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_participants_user_id_users_id_fk": { + "name": "chat_participants_user_id_users_id_fk", + "tableFrom": "chat_participants", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "chat_participants_chat_user_unique": { + "name": "chat_participants_chat_user_unique", + "nullsNotDistinct": false, + "columns": [ + "chat_id", + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chats": { + "name": "chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'Untitled Chat'" + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'private'" + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "share_path": { + "name": "share_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "shareable_link_id": { + "name": "shareable_link_id", + "type": "uuid", + "primaryKey": false, + "notNull": false, + "default": "gen_random_uuid()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "chats_shareable_link_id_unique": { + "name": "chats_shareable_link_id_unique", + "nullsNotDistinct": false, + "columns": [ + "shareable_link_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.document_chunks": { + "name": "document_chunks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "document_id": { + "name": "document_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "chunk_text": { + "name": "chunk_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "document_chunks_document_id_documents_id_fk": { + "name": "document_chunks_document_id_documents_id_fk", + "tableFrom": "document_chunks", + "tableTo": "documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.documents": { + "name": "documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "storage_path": { + "name": "storage_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'pending'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "documents_user_id_users_id_fk": { + "name": "documents_user_id_users_id_fk", + "tableFrom": "documents", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "documents_chat_id_chats_id_fk": { + "name": "documents_chat_id_chats_id_fk", + "tableFrom": "documents", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.locations": { + "name": "locations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "geojson": { + "name": "geojson", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "geometry": { + "name": "geometry", + "type": "geometry(GEOMETRY, 4326)", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "locations_user_id_users_id_fk": { + "name": "locations_user_id_users_id_fk", + "tableFrom": "locations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "locations_chat_id_chats_id_fk": { + "name": "locations_chat_id_chats_id_fk", + "tableFrom": "locations", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages": { + "name": "messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "location_id": { + "name": "location_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "messages_chat_id_chats_id_fk": { + "name": "messages_chat_id_chats_id_fk", + "tableFrom": "messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_user_id_users_id_fk": { + "name": "messages_user_id_users_id_fk", + "tableFrom": "messages", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_location_id_locations_id_fk": { + "name": "messages_location_id_locations_id_fk", + "tableFrom": "messages", + "tableTo": "locations", + "columnsFrom": [ + "location_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.prompt_generation_jobs": { + "name": "prompt_generation_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result_prompt": { + "name": "result_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "prompt_generation_jobs_user_id_users_id_fk": { + "name": "prompt_generation_jobs_user_id_users_id_fk", + "tableFrom": "prompt_generation_jobs", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.system_prompts": { + "name": "system_prompts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "system_prompts_user_id_users_id_fk": { + "name": "system_prompts_user_id_users_id_fk", + "tableFrom": "system_prompts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'viewer'" + }, + "selected_model": { + "name": "selected_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_prompt": { + "name": "system_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "clerk_user_id": { + "name": "clerk_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone_number": { + "name": "phone_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + }, + "users_clerk_user_id_unique": { + "name": "users_clerk_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "clerk_user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.visualizations": { + "name": "visualizations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'map_layer'" + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "geometry": { + "name": "geometry", + "type": "geometry(GEOMETRY, 4326)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "visualizations_user_id_users_id_fk": { + "name": "visualizations_user_id_users_id_fk", + "tableFrom": "visualizations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "visualizations_chat_id_chats_id_fk": { + "name": "visualizations_chat_id_chats_id_fk", + "tableFrom": "visualizations", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json index ee11d5f4..5b29172e 100644 --- a/drizzle/migrations/meta/_journal.json +++ b/drizzle/migrations/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1783699200000, "tag": "0005_add_documents_rag", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1783789573796, + "tag": "0009_add_message_type_name", + "breakpoints": true } ] } diff --git a/lib/actions/calendar.ts b/lib/actions/calendar.ts index cf6fe21e..cdc5f475 100644 --- a/lib/actions/calendar.ts +++ b/lib/actions/calendar.ts @@ -1,6 +1,6 @@ 'use server' -import { and, desc, eq, isNull, sql } from 'drizzle-orm' +import { and, desc, eq, isNull, sql, gte, lte } from 'drizzle-orm' import { db } from '@/lib/db' import { calendarNotes } from '@/lib/db/schema' import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user' @@ -27,12 +27,14 @@ export async function getNotes(date: Date, chatId: string | null): Promise= ${startDate}`) + // which bypasses Drizzle's column-aware value mapping and relies on postgres.js untyped binding, + // leading to Date-vs-string parameter mismatches. Prefer Drizzle's typed comparators like gte/lte + // or explicit .toISOString() conversion. const whereConditions = [ eq(calendarNotes.userId, userId), - and( - sql`${calendarNotes.date} >= ${startDate}`, - sql`${calendarNotes.date} <= ${endDate}` - ) + gte(calendarNotes.date, startDate), + lte(calendarNotes.date, endDate) ]; if (chatId) { @@ -51,7 +53,15 @@ export async function getNotes(date: Date, chatId: string | null): Promise { +export async function getChat(id: string, userId?: string | null): Promise { if (!userId) { - console.warn('getChat called without userId'); + console.warn('getChat called without userId. Querying public chat fallback.'); // Potentially allow fetching public chats if userId is null for anonymous users const result = await db.select().from(chats).where(and(eq(chats.id, id), eq(chats.visibility, 'public'))).limit(1); return result[0] || null; @@ -144,7 +144,15 @@ export async function saveChat(chatData: NewChat, messagesData: Omit { .orderBy(asc(messages.createdAt)); // Order messages chronologically return result; } catch (error) { - console.error(`Error fetching messages for chat ${chatId}:`, error); + console.error(`Error fetching messages for chat ${chatId} in getMessagesByChatId:`, { chatId, error }); return []; } } diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts index 6c5bc745..e2197dbf 100644 --- a/lib/actions/chat.ts +++ b/lib/actions/chat.ts @@ -137,21 +137,17 @@ export async function getChats(userId?: string | null): Promise { const { chats } = await dbGetChatsPage(userId, 20, 0) return chats } catch (error) { - console.error('Error fetching chats from DB:', error) + console.error('Error fetching chats from DB for user:', { userId, error }) return [] } } -export async function getChat(id: string, userId: string): Promise { - if (!userId) { - console.warn('getChat called without userId.') - return null; - } +export async function getChat(id: string, userId?: string | null): Promise { try { - const chat = await dbGetChat(id, userId) + const chat = await dbGetChat(id, userId || undefined) return chat } catch (error) { - console.error(`Error fetching chat ${id} from DB:`, error) + console.error(`Error fetching chat ${id} for user ${userId} from DB:`, { id, userId, error }) return null } } @@ -167,7 +163,7 @@ export async function getChatMessages(chatId: string): Promise try { return dbGetMessagesByChatId(chatId); } catch (error) { - console.error(`Error fetching messages for chat ${chatId} in getChatMessages:`, error); + console.error(`Error fetching messages for chat ${chatId} in getChatMessages:`, { chatId, error }); return []; } } @@ -216,6 +212,8 @@ export async function saveChat(chat: OldChatType, userId: string): Promise locations.id, { onDelete: 'set null' }), createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(), + type: text('type'), + name: text('name'), }); export const chatParticipants = pgTable('chat_participants', { diff --git a/public/sw.js b/public/sw.js index 43c9f8ec..b48d46d5 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,2 +1,2 @@ (()=>{"use strict";let e,t,a,r={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"serwist",runtime:"runtime",suffix:"undefined"!=typeof registration?registration.scope:""},s=e=>[r.prefix,e,r.suffix].filter(e=>e&&e.length>0).join("-"),i=e=>{for(let t of Object.keys(r))e(t)},n={updateDetails:e=>{i(t=>{let a=e[t];"string"==typeof a&&(r[t]=a)})},getGoogleAnalyticsName:e=>e||s(r.googleAnalytics),getPrecacheName:e=>e||s(r.precache),getRuntimeName:e=>e||s(r.runtime)},c=(e,...t)=>{let a=e;return t.length>0&&(a+=` :: ${JSON.stringify(t)}`),a};var o=class extends Error{details;constructor(e,t){super(c(e,t)),this.name=e,this.details=t}};let l=e=>new URL(String(e),location.href).href.replace(RegExp(`^${location.origin}`),"");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 f(e,t,a,r){let s=d(t.url,a);if(t.url===s)return e.match(t,r);let i={...r,ignoreSearch:!0};for(let n of(await e.keys(t,i)))if(s===d(n.url,a))return e.match(n,r)}var w=class{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};let y=async()=>{for(let e of u)await e()},p="-precache-",g=async(e,t=p)=>{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},m=e=>{self.addEventListener("activate",t=>{t.waitUntil(g(n.getPrecacheName(e)).then(e=>{}))})},_=()=>{self.addEventListener("activate",()=>self.clients.claim())},v=(e,t)=>{let a=t();return e.waitUntil(a),a},b=(e,t)=>t.some(t=>e instanceof t),R=new WeakMap,q=new WeakMap,E=new WeakMap,D={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return R.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return S(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function S(e){if(e instanceof IDBRequest){let t=new Promise((t,a)=>{let r=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{t(S(e.result)),r()},i=()=>{a(e.error),r()};e.addEventListener("success",s),e.addEventListener("error",i)});return E.set(t,e),t}if(q.has(e))return q.get(e);let r=function(e){if("function"==typeof e)return(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(P(this),t),S(this.request)}:function(...t){return S(e.apply(P(this),t))};return(e instanceof IDBTransaction&&function(e){if(R.has(e))return;let t=new Promise((t,a)=>{let r=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{t(),r()},i=()=>{a(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});R.set(e,t)}(e),b(e,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,D):e}(e);return r!==e&&(q.set(e,r),E.set(r,e)),r}let P=e=>E.get(e),k=["get","getKey","getAll","getAllKeys","count"],C=["put","add","delete","clear"],T=new Map;function N(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(T.get(t))return T.get(t);let a=t.replace(/FromIndex$/,""),r=t!==a,s=C.includes(a);if(!(a in(r?IDBIndex:IDBObjectStore).prototype)||!(s||k.includes(a)))return;let i=async function(e,...t){let i=this.transaction(e,s?"readwrite":"readonly"),n=i.store;return r&&(n=n.index(t.shift())),(await Promise.all([n[a](...t),s&&i.done]))[0]};return T.set(t,i),i}D=(e=>({...e,get:(t,a,r)=>N(t,a)||e.get(t,a,r),has:(t,a)=>!!N(t,a)||e.has(t,a)}))(D);let I=["continue","continuePrimaryKey","advance"],L={},x=new WeakMap,U=new WeakMap,B={get(e,t){if(!I.includes(t))return e[t];let a=L[t];return a||(a=L[t]=function(...e){x.set(this,U.get(this)[t](...e))}),a}};async function*O(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;let a=new Proxy(t,B);for(U.set(a,t),E.set(a,P(t));t;)yield a,t=await (x.get(a)||t.continue()),x.delete(a)}function K(e,t){return t===Symbol.asyncIterator&&b(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&b(e,[IDBIndex,IDBObjectStore])}D=(e=>({...e,get:(t,a,r)=>K(t,a)?O:e.get(t,a,r),has:(t,a)=>K(t,a)||e.has(t,a)}))(D);let A=async(t,a)=>{let r=null;if(t.url&&(r=new URL(t.url).origin),r!==self.location.origin)throw new o("cross-origin-copy-response",{origin:r});let s=t.clone(),i={headers:new Headers(s.headers),status:s.status,statusText:s.statusText},n=a?a(i):i,c=!function(){if(void 0===e){let t=new Response("");if("body"in t)try{new Response(t.body),e=!0}catch{e=!1}e=!1}return e}()?await s.blob():s.body;return new Response(c,n)},M=()=>{self.__WB_DISABLE_DEV_LOGS=!0},F="requests",W="queueName";var j=class{_db=null;async addEntry(e){let t=(await this.getDb()).transaction(F,"readwrite",{durability:"relaxed"});await t.store.add(e),await t.done}async getFirstEntryId(){return(await (await this.getDb()).transaction(F).store.openCursor())?.value.id}async getAllEntriesByQueueName(e){return await (await this.getDb()).getAllFromIndex(F,W,IDBKeyRange.only(e))||[]}async getEntryCountByQueueName(e){return(await this.getDb()).countFromIndex(F,W,IDBKeyRange.only(e))}async deleteEntry(e){await (await this.getDb()).delete(F,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(F).store.index(W).openCursor(e,t))?.value}async getDb(){return this._db||(this._db=await function(e,t,{blocked:a,upgrade:r,blocking:s,terminated:i}={}){let n=indexedDB.open(e,3),c=S(n);return r&&n.addEventListener("upgradeneeded",e=>{r(S(n.result),e.oldVersion,e.newVersion,S(n.transaction),e)}),a&&n.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),c.then(e=>{i&&e.addEventListener("close",()=>i()),s&&e.addEventListener("versionchange",e=>s(e.oldVersion,e.newVersion,e))}).catch(()=>{}),c}("serwist-background-sync",0,{upgrade:this._upgradeDb})),this._db}_upgradeDb(e,t){t>0&&t<3&&e.objectStoreNames.contains(F)&&e.deleteObjectStore(F),e.createObjectStore(F,{autoIncrement:!0,keyPath:"id"}).createIndex(W,W,{unique:!1})}},H=class{_queueName;_queueDb;constructor(e){this._queueName=e,this._queueDb=new j}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 $=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];var G=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}),$))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 V="serwist-background-sync",Q=new Set,z=e=>{let t={request:new G(e.requestData).toRequest(),timestamp:e.timestamp};return e.metadata&&(t.metadata=e.metadata),t};var J=class{_name;_onSync;_maxRetentionTime;_queueStore;_forceSyncFallback;_syncInProgress=!1;_requestsAddedDuringSync=!1;constructor(e,{forceSyncFallback:t,onSync:a,maxRetentionTime:r}={}){if(Q.has(e))throw new o("duplicate-queue-name",{name:e});Q.add(e),this._name=e,this._onSync=a||this.replayRequests,this._maxRetentionTime=r||10080,this._forceSyncFallback=!!t,this._queueStore=new H(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 r of e){let e=60*this._maxRetentionTime*1e3;t-r.timestamp>e?await this._queueStore.deleteEntry(r.id):a.push(z(r))}return a}async size(){return await this._queueStore.size()}async _addRequest({request:e,metadata:t,timestamp:a=Date.now()},r){let s={requestData:(await G.fromRequest(e.clone())).toObject(),timestamp:a};switch(t&&(s.metadata=t),r){case"push":await this._queueStore.pushEntry(s);break;case"unshift":await this._queueStore.unshiftEntry(s)}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 r=60*this._maxRetentionTime*1e3;return a-t.timestamp>r?this._removeRequest(e):z(t)}}async replayRequests(){let e;for(;e=await this.shiftRequest();)try{await fetch(e.request.clone())}catch{throw await this.unshiftRequest(e),new o("queue-replay-failed",{name:this._name})}}async registerSync(){if("sync"in self.registration&&!this._forceSyncFallback)try{await self.registration.sync.register(`${V}:${this._name}`)}catch(e){}}_addSyncListener(){"sync"in self.registration&&!this._forceSyncFallback?self.addEventListener("sync",e=>{if(e.tag===`${V}:${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 Q}},X=class{_queue;constructor(e,t){this._queue=new J(e,t)}async fetchDidFail({request:e}){await this._queue.pushRequest({request:e})}};let Y={cacheWillUpdate:async({response:e})=>200===e.status||0===e.status?e:null};function Z(e){return"string"==typeof e?new Request(e):e}var ee=class{event;request;url;params;_cacheKeys={};_strategy;_handlerDeferred;_extendLifetimePromises;_plugins;_pluginStateMap;constructor(e,t){for(let 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 w,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=Z(e),r=await this.getPreloadResponse();if(r)return r;let s=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 o("plugin-error-request-will-fetch",{thrownErrorMessage:e.message})}let i=a.clone();try{let e;for(let r of(e=await fetch(a,"navigate"===a.mode?void 0:this._strategy.fetchOptions),this.iterateCallbacks("fetchDidSucceed")))e=await r({event:t,request:i,response:e});return e}catch(e){throw s&&await this.runCallbacks("fetchDidFail",{error:e,event:t,originalRequest:s.clone(),request:i.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=Z(e),{cacheName:r,matchOptions:s}=this._strategy,i=await this.getCacheKey(a,"read"),n={...s,cacheName:r};for(let e of(t=await caches.match(i,n),this.iterateCallbacks("cachedResponseWillBeUsed")))t=await e({cacheName:r,matchOptions:s,cachedResponse:t,request:i,event:this.event})||void 0;return t}async cachePut(e,t){let a=Z(e);await h(0);let r=await this.getCacheKey(a,"write");if(!t)throw new o("cache-put-with-no-response",{url:l(r.url)});let s=await this._ensureResponseSafeToCache(t);if(!s)return!1;let{cacheName:i,matchOptions:n}=this._strategy,c=await self.caches.open(i),u=this.hasCallback("cacheDidUpdate"),d=u?await f(c,r.clone(),["__WB_REVISION__"],n):null;try{await c.put(r,u?s.clone():s)}catch(e){if(e instanceof Error)throw"QuotaExceededError"===e.name&&await y(),e}for(let e of this.iterateCallbacks("cacheDidUpdate"))await e({cacheName:i,oldResponse:d,newResponse:s.clone(),request:r,event:this.event});return!0}async getCacheKey(e,t){let a=`${e.url} | ${t}`;if(!this._cacheKeys[a]){let r=e;for(let e of this.iterateCallbacks("cacheKeyWillBeUsed"))r=Z(await e({mode:t,request:r,event:this.event,params:this.params}));this._cacheKeys[a]=r}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),r=r=>{let s={...r,state:a};return t[e](s)};yield r}}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}},et=class{cacheName;plugins;fetchOptions;matchOptions;constructor(e={}){this.cacheName=n.getRuntimeName(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,r=new ee(this,e.url?{event:t,request:a,url:e.url,params:e.params}:{event:t,request:a}),s=this._getResponse(r,a,t);return[s,this._awaitComplete(s,r,a,t)]}async _getResponse(e,t,a){let r;await e.runCallbacks("handlerWillStart",{event:a,request:t});try{if(r=await this._handle(t,e),void 0===r||"error"===r.type)throw new o("no-response",{url:t.url})}catch(s){if(s instanceof Error){for(let i of e.iterateCallbacks("handlerDidError"))if(void 0!==(r=await i({error:s,event:a,request:t})))break}if(!r)throw s}for(let s of e.iterateCallbacks("handlerWillRespond"))r=await s({event:a,request:t,response:r});return r}async _awaitComplete(e,t,a,r){let s,i;try{s=await e}catch{}try{await t.runCallbacks("handlerDidRespond",{event:r,request:a,response:s}),await t.doneWaiting()}catch(e){e instanceof Error&&(i=e)}if(await t.runCallbacks("handlerDidComplete",{event:r,request:a,response:s,error:i}),t.destroy(),i)throw i}},ea=class extends et{_networkTimeoutSeconds;constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(Y),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,r=[],s=[];if(this._networkTimeoutSeconds){let{id:i,promise:n}=this._getTimeoutPromise({request:e,logs:r,handler:t});a=i,s.push(n)}let i=this._getNetworkPromise({timeoutId:a,request:e,logs:r,handler:t});s.push(i);let n=await t.waitUntil((async()=>await t.waitUntil(Promise.race(s))||await i)());if(!n)throw new o("no-response",{url:e.url});return n}_getTimeoutPromise({request:e,logs:t,handler:a}){let r;return{promise:new Promise(t=>{r=setTimeout(async()=>{t(await a.cacheMatch(e))},1e3*this._networkTimeoutSeconds)}),id:r}}async _getNetworkPromise({timeoutId:e,request:t,logs:a,handler:r}){let s,i;try{i=await r.fetchAndCachePut(t)}catch(e){e instanceof Error&&(s=e)}return e&&clearTimeout(e),(s||!i)&&(i=await r.cacheMatch(t)),i}},er=class extends et{_networkTimeoutSeconds;constructor(e={}){super(e),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,r;try{let a=[t.fetch(e)];if(this._networkTimeoutSeconds){let e=h(1e3*this._networkTimeoutSeconds);a.push(e)}if(!(r=await Promise.race(a)))throw Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`)}catch(e){e instanceof Error&&(a=e)}if(!r)throw new o("no-response",{url:e.url,error:a});return r}};let es=e=>e&&"object"==typeof e?e:{handle:e};var ei=class{handler;match;method;catchHandler;constructor(e,t,a="GET"){this.handler=es(t),this.match=e,this.method=a}setCatchHandler(e){this.catchHandler=es(e)}},en=class e extends et{_fallbackToNetwork;static defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:e})=>!e||e.status>=400?null:e};static copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:e})=>e.redirected?await A(e):e};constructor(t={}){t.cacheName=n.getPrecacheName(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 r=await t.cacheMatch(e);return r||(t.event&&"install"===t.event.type?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,t){let a,r=t.params||{};if(this._fallbackToNetwork){let s=r.integrity,i=e.integrity,n=!i||i===s;a=await t.fetch(new Request(e,{integrity:"no-cors"!==e.mode?i||s:void 0})),s&&n&&"no-cors"!==e.mode&&(this._useDefaultCacheabilityPluginIfNeeded(),await t.cachePut(e,a.clone()))}else throw new o("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 o("bad-precaching-response",{url:e.url,status:a.status});return a}_useDefaultCacheabilityPluginIfNeeded(){let t=null,a=0;for(let[r,s]of this.plugins.entries())s!==e.copyRedirectedCacheableResponsesPlugin&&(s===e.defaultPrecacheCacheabilityPlugin&&(t=r),s.cacheWillUpdate&&a++);0===a?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):a>1&&null!==t&&this.plugins.splice(t,1)}},ec=class extends ei{_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))}};let eo=()=>!!self.registration?.navigationPreload,el=e=>{eo()&&self.addEventListener("activate",t=>{t.waitUntil(self.registration.navigationPreload.enable().then(()=>{e&&self.registration.navigationPreload.setHeaderValue(e)}))})},eh=(e,t=[])=>{for(let a of[...e.searchParams.keys()])t.some(e=>e.test(a))&&e.searchParams.delete(a);return e};var eu=class extends ei{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 ed=e=>{n.updateDetails(e)},ef=e=>{if(!e)throw new o("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 o("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 r=new URL(a,location.href),s=new URL(a,location.href);return r.searchParams.set("__WB_REVISION__",t),{cacheKey:r.href,url:s.href}};var ew=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 ey=(e,t,a)=>{if("string"==typeof e){let r=new URL(e,location.href);return new ei(({url:e})=>e.href===r.href,t,a)}if(e instanceof RegExp)return new eu(e,t,a);if("function"==typeof e)return new ei(e,t,a);if(e instanceof ei)return e;throw new o("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})},ep=async(e,t,a)=>{let r=t.map((e,t)=>({index:t,item:e})),s=async e=>{let t=[];for(;;){let s=r.pop();if(!s)return e(t);let i=await a(s.item);t.push({result:i,index:s.index})}},i=Array.from({length:e},()=>new Promise(s));return(await Promise.all(i)).flat().sort((e,t)=>e.indexe.result)},eg=(e,t,a)=>!a.some(a=>e.headers.has(a)&&t.headers.has(a))||a.every(a=>{let r=e.headers.has(a)===t.headers.has(a),s=e.headers.get(a)===t.headers.get(a);return r&&s}),em="undefined"!=typeof navigator&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),e_=e=>({cacheName:e.cacheName,updatedURL:e.request.url}),ev="cache-entries",eb=e=>{let t=new URL(e,location.href);return t.hash="",t.href};var eR=class{_cacheName;_db=null;constructor(e){this._cacheName=e}_getId(e){return`${this._cacheName}|${eb(e)}`}_upgradeDb(e){let t=e.createObjectStore(ev,{keyPath:"id"});t.createIndex("cacheName","cacheName",{unique:!1}),t.createIndex("timestamp","timestamp",{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&deleteDB(this._cacheName)}async setTimestamp(e,t){e=eb(e);let a={id:this._getId(e),cacheName:this._cacheName,url:e,timestamp:t},r=(await this.getDb()).transaction(ev,"readwrite",{durability:"relaxed"});await r.store.put(a),await r.done}async getTimestamp(e){return(await (await this.getDb()).get(ev,this._getId(e)))?.timestamp}async expireEntries(e,t){let a=await (await this.getDb()).transaction(ev,"readwrite").store.index("timestamp").openCursor(null,"prev"),r=[],s=0;for(;a;){let i=a.value;i.cacheName===this._cacheName&&(e&&i.timestamp=t?(a.delete(),r.push(i.url)):s++),a=await a.continue()}return r}async getDb(){return this._db||(this._db=await openDB("serwist-expiration",1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)})),this._db}};let eq=/^\/(\w+\/)?collect/,eE=e=>async({queue:t})=>{let a;for(;a=await t.shiftRequest();){let{request:r,timestamp:s}=a,i=new URL(r.url);try{let t="POST"===r.method?new URLSearchParams(await r.clone().text()):i.searchParams,a=s-(Number(t.get("qt"))||0),n=Date.now()-a;if(t.set("qt",String(n)),e.parameterOverrides)for(let a of Object.keys(e.parameterOverrides)){let r=e.parameterOverrides[a];t.set(a,r)}"function"==typeof e.hitFilter&&e.hitFilter.call(null,t),await fetch(new Request(i.origin+i.pathname,{body:t.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(e){throw await t.unshiftRequest(a),e}}},eD=e=>{let t=({url:e})=>"www.google-analytics.com"===e.hostname&&eq.test(e.pathname),a=new er({plugins:[e]});return[new ei(t,a,"GET"),new ei(t,a,"POST")]},eS=e=>new ei(({url:e})=>"www.google-analytics.com"===e.hostname&&"/analytics.js"===e.pathname,new ea({cacheName:e}),"GET"),eP=e=>new ei(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtag/js"===e.pathname,new ea({cacheName:e}),"GET"),ek=e=>new ei(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtm.js"===e.pathname,new ea({cacheName:e}),"GET"),eC=({serwist:e,cacheName:t,...a})=>{let r=n.getGoogleAnalyticsName(t),s=new X("serwist-google-analytics",{maxRetentionTime:2880,onSync:eE(a)});for(let t of[ek(r),eS(r),eP(r),...eD(s)])e.registerRoute(t)};var eT=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 eN=(e,t,a)=>{let r,s,i=e.size;if(a&&a>i||t&&t<0)throw new SerwistError("range-not-satisfiable",{size:i,end:a,start:t});return void 0!==t&&void 0!==a?(r=t,s=a+1):void 0!==t&&void 0===a?(r=t,s=i):void 0!==a&&void 0===t&&(r=i-a,s=i),{start:r,end:s}},eI=e=>{let t=e.trim().toLowerCase();if(!t.startsWith("bytes="))throw new SerwistError("unit-must-be-bytes",{normalizedRangeHeader:t});if(t.includes(","))throw new SerwistError("single-range-only",{normalizedRangeHeader:t});let a=/(\d*)-(\d*)/.exec(t);if(!a||!(a[1]||a[2]))throw new SerwistError("invalid-range-values",{normalizedRangeHeader:t});return{start:""===a[1]?void 0:Number(a[1]),end:""===a[2]?void 0:Number(a[2])}};var eL=class extends et{async _handle(e,t){let a,r=await t.cacheMatch(e);if(r);else try{r=await t.fetchAndCachePut(e)}catch(e){e instanceof Error&&(a=e)}if(!r)throw new o("no-response",{url:e.url,error:a});return r}},ex=class extends ei{constructor(e,t){super(({request:a})=>{let r=e.getUrlsToPrecacheKeys();for(let s of function*(e,{directoryIndex:t="index.html",ignoreURLParametersMatching:a=[/^utm_/,/^fbclid$/],cleanURLs:r=!0,urlManipulation:s}={}){let i=new URL(e,location.href);i.hash="",yield i.href;let n=eh(i,a);if(yield n.href,t&&n.pathname.endsWith("/")){let e=new URL(n.href);e.pathname+=t,yield e.href}if(r){let e=new URL(n.href);e.pathname+=".html",yield e.href}if(s)for(let e of s({url:i}))yield e.href}(a.url,t)){let t=r.get(s);if(t)return{cacheKey:t,integrity:e.getIntegrityForPrecacheKey(t)}}},e.precacheStrategy)}},eU=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}};let eB=(e,t={})=>{let{cacheName:a,plugins:r=[],fetchOptions:s,matchOptions:i,fallbackToNetwork:c,directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u,cleanupOutdatedCaches:d,concurrency:f=10,navigateFallback:w,navigateFallbackAllowlist:y,navigateFallbackDenylist:p}=t??{};return{precacheStrategyOptions:{cacheName:n.getPrecacheName(a),plugins:[...r,new eU({precacheController:e})],fetchOptions:s,matchOptions:i,fallbackToNetwork:c},precacheRouteOptions:{directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u},precacheMiscOptions:{cleanupOutdatedCaches:d,concurrency:f,navigateFallback:w,navigateFallbackAllowlist:y,navigateFallbackDenylist:p}}};new 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:r,navigationPreload:s=!1,cacheId:i,clientsClaim:n=!1,runtimeCaching:c,offlineAnalyticsConfig:o,disableDevLogs:l=!1,fallbacks:h,requestRules:u}={}){let{precacheStrategyOptions:d,precacheRouteOptions:f,precacheMiscOptions:w}=eB(this,t);if(this._concurrentPrecaching=w.concurrency,this._precacheStrategy=new en(d),this._routes=new Map,this._defaultHandlerMap=new Map,this._requestRules=u,this.handleInstall=this.handleInstall.bind(this),this.handleActivate=this.handleActivate.bind(this),this.handleFetch=this.handleFetch.bind(this),this.handleCache=this.handleCache.bind(this),r&&r.length>0&&self.importScripts(...r),s&&el(),void 0!==i&&ed({prefix:i}),a?self.skipWaiting():self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),n&&_(),e&&e.length>0&&this.addToPrecacheList(e),w.cleanupOutdatedCaches&&m(d.cacheName),this.registerRoute(new ex(this,f)),w.navigateFallback&&this.registerRoute(new ec(this.createHandlerBoundToUrl(w.navigateFallback),{allowlist:w.navigateFallbackAllowlist,denylist:w.navigateFallbackDenylist})),void 0!==o&&("boolean"==typeof o?o&&eC({serwist:this}):eC({...o,serwist:this})),void 0!==c){if(void 0!==h){let e=new eT({fallbackUrls:h.entries,serwist:this});c.forEach(t=>{t.handler instanceof et&&!t.handler.plugins.some(e=>"handlerDidError"in e)&&t.handler.plugins.push(e)})}for(let e of c)this.registerCapture(e.matcher,e.handler,e.method)}l&&M()}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:r}=ef(a),s="string"!=typeof a&&a.revision?"reload":"default";if(this._urlsToCacheKeys.has(r)&&this._urlsToCacheKeys.get(r)!==e)throw new o("add-to-cache-list-conflicting-entries",{firstEntry:this._urlsToCacheKeys.get(r),secondEntry:e});if("string"!=typeof a&&a.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==a.integrity)throw new o("add-to-cache-list-conflicting-integrities",{url:r});this._cacheKeysToIntegrities.set(e,a.integrity)}this._urlsToCacheKeys.set(r,e),this._urlsToCacheModes.set(r,s)}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),v(e,async()=>{let t=new ew;this.precacheStrategy.plugins.push(t),await ep(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let r=this._cacheKeysToIntegrities.get(a),s=this._urlsToCacheModes.get(t),i=new Request(t,{integrity:r,cache:s,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:r}=t;return{updatedURLs:a,notUpdatedURLs:r}})}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 v(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),r=[];for(let s of t)a.has(s.url)||(await e.delete(s),r.push(s.url));return{deletedCacheRequests:r}})}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,es(e))}setCatchHandler(e){this._catchHandler=es(e)}registerCapture(e,t,a){let r=ey(e,t,a);return this.registerRoute(r),r}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 o("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 o("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 o("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,r=new URL(e.url,location.href);if(!r.protocol.startsWith("http"))return;let s=r.origin===location.origin,{params:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:s,url:r}),c=n?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:r,request:e,event:t,params:i})}catch(e){a=Promise.reject(e)}let l=n?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:r,request:e,event:t,params:i})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:r,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:r}){for(let s of this._routes.get(a.method)||[]){let i,n=s.match({url:e,sameOrigin:t,request:a,event:r});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:s,params:i}}return{}}}({precacheEntries:[{'revision':'dd5c78ef188a31435ac88897c107dadc','url':'/_next/static/TRmmvzCsIJEpHVSNrsfI9/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/TRmmvzCsIJEpHVSNrsfI9/_ssgManifest.js'},{'revision':null,'url':'/_next/static/chunks/121.991963838bfc92a5.js'},{'revision':null,'url':'/_next/static/chunks/164f4fb6.f3faa5d5aba5cf04.js'},{'revision':null,'url':'/_next/static/chunks/2f0b94e8.d52fd5f53fc1f1b5.js'},{'revision':null,'url':'/_next/static/chunks/309.1d17adf5fd2dc106.js'},{'revision':null,'url':'/_next/static/chunks/327-a7ec5480fde9c98c.js'},{'revision':null,'url':'/_next/static/chunks/34.7e4259d4d488a969.js'},{'revision':null,'url':'/_next/static/chunks/399-fbdcf58268a62d3d.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-b5c413a68ae9f40b.js'},{'revision':null,'url':'/_next/static/chunks/552.f3563c52cf210686.js'},{'revision':null,'url':'/_next/static/chunks/629-fbcaa1e7fb703b17.js'},{'revision':null,'url':'/_next/static/chunks/64.1609b1901d412299.js'},{'revision':null,'url':'/_next/static/chunks/642.41e508081946a523.js'},{'revision':null,'url':'/_next/static/chunks/692.b1f6ee25d6ee0b92.js'},{'revision':null,'url':'/_next/static/chunks/740-e93a3641311a6944.js'},{'revision':null,'url':'/_next/static/chunks/751.dbdda4b83d78b403.js'},{'revision':null,'url':'/_next/static/chunks/780.1a17e96548ee08b5.js'},{'revision':null,'url':'/_next/static/chunks/797-0c10a3f91f00b70b.js'},{'revision':null,'url':'/_next/static/chunks/822.32adac280d362ee6.js'},{'revision':null,'url':'/_next/static/chunks/933-9a41eeb38bdcb37c.js'},{'revision':null,'url':'/_next/static/chunks/ad2866b8.6b876e1655c11f64.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-53439e48b6308ac6.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chat/route-c0c788ad81251a5d.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chats/all/route-e8f6a9b3b507af1d.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chats/route-3b629b9a6a475d99.js'},{'revision':null,'url':'/_next/static/chunks/app/api/clerk/webhook/route-b1d0b83ee4bf36bd.js'},{'revision':null,'url':'/_next/static/chunks/app/api/embeddings/route-51a1e54fc912d161.js'},{'revision':null,'url':'/_next/static/chunks/app/api/health/route-4485cc39c3d8cb6f.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-f7973cbc47970094.js'},{'revision':null,'url':'/_next/static/chunks/app/manifest.webmanifest/route-6c8150e22b5a9eb0.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-f761a3156b61eb05.js'},{'revision':null,'url':'/_next/static/chunks/app/page-26b8ef2cdb907eaf.js'},{'revision':null,'url':'/_next/static/chunks/app/search/%5Bid%5D/page-4b006dfcf02aed45.js'},{'revision':null,'url':'/_next/static/chunks/bc98253f.a20b3a3cf1b114d6.js'},{'revision':null,'url':'/_next/static/chunks/c36f3faa.4f93eb25a02ddfb0.js'},{'revision':null,'url':'/_next/static/chunks/d3ac728e-2a78bdd902db0a16.js'},{'revision':null,'url':'/_next/static/chunks/dc112a36-9a670afd7d3140fd.js'},{'revision':null,'url':'/_next/static/chunks/framework-6e3d659ca9a17c7d.js'},{'revision':null,'url':'/_next/static/chunks/main-84d2b2e62086cf16.js'},{'revision':null,'url':'/_next/static/chunks/main-app-103a28f346eee8b8.js'},{'revision':null,'url':'/_next/static/chunks/pages/_app-8e94039938385921.js'},{'revision':null,'url':'/_next/static/chunks/pages/_error-7b2d139042a6a5ab.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-327d0c2e28d87830.js'},{'revision':null,'url':'/_next/static/css/234ed9910f3a0167.css'},{'revision':null,'url':'/_next/static/css/4183e00ad0e88413.css'},{'revision':null,'url':'/_next/static/css/466fc450586fef10.css'},{'revision':null,'url':'/_next/static/css/911e6a603adbdfb3.css'},{'revision':null,'url':'/_next/static/css/c35610c794fcbaaa.css'},{'revision':'be7c930fceb794521be0a68e113a71d8','url':'/_next/static/media/034d78ad42e9620c-s.woff2'},{'revision':'b550bca8934bd86812d1f5e28c9cc1de','url':'/_next/static/media/0484562807a97172-s.p.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'69d9d2cdadeab7225297d50fc8e48e8b','url':'/_next/static/media/29a4aea02fdee119-s.woff2'},{'revision':'9e3ecbe4bb4c6f0b71adc1cd481c2bdc','url':'/_next/static/media/29e7bbdce9332268-s.woff2'},{'revision':'792477d09826b11d1e5a611162c9797a','url':'/_next/static/media/8888a3826f4a3af4-s.p.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.1608a09b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.4aafdb68.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.a79f1c31.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.b6770918.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.9f256b85.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.7c187121.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.b74a1a8b.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.d181c465.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.47373d1e.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.8916142b.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.9024d815.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.0462f03b.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.7f51fe03.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.572d331f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.5295ba48.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.939bc644.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.f28c23ac.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.bf59d231.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.74048478.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.03e9641d.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.07505710.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.e1e279cb.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.eae34984.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.fabc004a.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.57727022.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.5916a24f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.d6b476ec.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.9acaf01c.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.a144ef58.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.b4230e7e.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.10d95fd3.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.7a996c9d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.fbccdabe.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.6258592b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf'},{'revision':'d3aa06d13d3cf9c0558927051f3cb948','url':'/_next/static/media/a1386beebedccca4-s.woff2'},{'revision':'0bd523f6049956faaf43c254a719d06a','url':'/_next/static/media/b957ea75a84b6ea7-s.p.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'5a1b7c983a9dc0a87a2ff138e07ae822','url':'/_next/static/media/c3bc380753a8436c-s.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'9516f567cd80b0f418bba2f1299ed6d1','url':'/_next/static/media/db911767852bc875-s.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'43751174b6b810eb169101a20d8c26f8','url':'/_next/static/media/eafabf029ad39a43-s.p.woff2'},{'revision':'63af7d5e18e585fad8d0220e5d551da1','url':'/_next/static/media/f10b8e9d91f3edcb-s.woff2'},{'revision':'f2a04185547c36abfa589651236a9849','url':'/_next/static/media/fe0777f1195381cb-s.woff2'},{'revision':'460f55cf1456f5a201f259a4eb607989','url':'/icons/apple-touch-icon.png'},{'revision':'69784622e4b55d2666c5180fb954d781','url':'/icons/icon-192x192.png'},{'revision':'ab07c93bfbd862c758c4d6d31085a6db','url':'/icons/icon-512x512-maskable.png'},{'revision':'f1b0e1527b676413a8b8e0154f671984','url':'/icons/icon-512x512.png'},{'revision':'2ed79e1d8607156994a2a6462563d7f0','url':'/images/Q zoom.json'},{'revision':'d088f99e3a3f1b7eaec384f36b0866d2','url':'/images/Q.json'},{'revision':'b14dbca44bb366d8499ae9a9b24a104f','url':'/images/eva-logo.png'},{'revision':'8f6cf4c9ec412fe201f80e2d23445aa9','url':'/images/logo.svg'},{'revision':'ab57101a81d25f409febeed6eb7e32bf','url':'/images/opengraph-image.png'}],skipWaiting:!1,clientsClaim:!1,navigationPreload:!1,runtimeCaching:[{matcher:/\.(?:js|css|woff2?|png|jpg|jpeg|svg|gif|ico)$/,handler:new eL({cacheName:"static-assets"})},{matcher:e=>{let{url:t,request:a}=e,r=t.pathname.startsWith("/api/"),s="/api/chat"===t.pathname&&"POST"===a.method||"/api/chats/all"===t.pathname&&"DELETE"===a.method;return r&&!s},handler:new ea({cacheName:"api-cache",networkTimeoutSeconds:5})},{matcher:e=>{let{request:t}=e;return"navigate"===t.mode},handler:new ea({cacheName:"pages-cache",networkTimeoutSeconds:5,plugins:[{handlerDidError:async()=>caches.match("/offline")}]})}]}).addEventListeners(),self.addEventListener("push",e=>{console.log("[Service Worker] Push Received.",e)}),self.addEventListener("sync",e=>{console.log("[Service Worker] Background Sync.",e)})})(); \ No newline at end of file +This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),v(e,async()=>{let t=new ew;this.precacheStrategy.plugins.push(t),await ep(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let r=this._cacheKeysToIntegrities.get(a),s=this._urlsToCacheModes.get(t),i=new Request(t,{integrity:r,cache:s,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:r}=t;return{updatedURLs:a,notUpdatedURLs:r}})}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 v(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),r=[];for(let s of t)a.has(s.url)||(await e.delete(s),r.push(s.url));return{deletedCacheRequests:r}})}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,es(e))}setCatchHandler(e){this._catchHandler=es(e)}registerCapture(e,t,a){let r=ey(e,t,a);return this.registerRoute(r),r}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 o("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 o("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 o("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,r=new URL(e.url,location.href);if(!r.protocol.startsWith("http"))return;let s=r.origin===location.origin,{params:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:s,url:r}),c=n?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:r,request:e,event:t,params:i})}catch(e){a=Promise.reject(e)}let l=n?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:r,request:e,event:t,params:i})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:r,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:r}){for(let s of this._routes.get(a.method)||[]){let i,n=s.match({url:e,sameOrigin:t,request:a,event:r});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:s,params:i}}return{}}}({precacheEntries:[{'revision':'af2b6e592c9167a3e6669085aae379db','url':'/_next/static/RaI8lt63E1RQjaPB9_1IR/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/RaI8lt63E1RQjaPB9_1IR/_ssgManifest.js'},{'revision':null,'url':'/_next/static/chunks/121.991963838bfc92a5.js'},{'revision':null,'url':'/_next/static/chunks/164f4fb6.f3faa5d5aba5cf04.js'},{'revision':null,'url':'/_next/static/chunks/191-3ebdab1e23ffab4d.js'},{'revision':null,'url':'/_next/static/chunks/221.8cea1bbd8d7a75d0.js'},{'revision':null,'url':'/_next/static/chunks/245.71c45fa6b1e823c4.js'},{'revision':null,'url':'/_next/static/chunks/255-c78a598e090575a9.js'},{'revision':null,'url':'/_next/static/chunks/2f0b94e8.d674f0a035f460ca.js'},{'revision':null,'url':'/_next/static/chunks/309.1d17adf5fd2dc106.js'},{'revision':null,'url':'/_next/static/chunks/34.7e4259d4d488a969.js'},{'revision':null,'url':'/_next/static/chunks/399.31ee657513a3dde2.js'},{'revision':null,'url':'/_next/static/chunks/44530001-09199bfb889c2833.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-b5c413a68ae9f40b.js'},{'revision':null,'url':'/_next/static/chunks/563-469d9aaf311b30f6.js'},{'revision':null,'url':'/_next/static/chunks/590.0bd30cfd360eab78.js'},{'revision':null,'url':'/_next/static/chunks/642.2cbf92dbf1cc07c0.js'},{'revision':null,'url':'/_next/static/chunks/745-4c545fdce95c0a56.js'},{'revision':null,'url':'/_next/static/chunks/746-c335b885cf0977cc.js'},{'revision':null,'url':'/_next/static/chunks/751.b87576b52bb9f4d1.js'},{'revision':null,'url':'/_next/static/chunks/797-0c10a3f91f00b70b.js'},{'revision':null,'url':'/_next/static/chunks/822.e5a25ff0c78b4017.js'},{'revision':null,'url':'/_next/static/chunks/883ee446.8f8323ee7b61fbb5.js'},{'revision':null,'url':'/_next/static/chunks/ad2866b8.6b876e1655c11f64.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-53439e48b6308ac6.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chat/route-b4f3924ac733b034.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chats/%5Bid%5D/participants/route-b8c2aa3fc4ba663d.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chats/all/route-8057f7cd2376b981.js'},{'revision':null,'url':'/_next/static/chunks/app/api/chats/route-22ca0d4364958556.js'},{'revision':null,'url':'/_next/static/chunks/app/api/clerk/webhook/route-d3bd95716cd4028b.js'},{'revision':null,'url':'/_next/static/chunks/app/api/embeddings/route-8fa56ba6811ae879.js'},{'revision':null,'url':'/_next/static/chunks/app/api/health/route-0ef5d711349c1b67.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-bd8fcbf8fd18eab8.js'},{'revision':null,'url':'/_next/static/chunks/app/manifest.webmanifest/route-3596db319c2d2b56.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-f761a3156b61eb05.js'},{'revision':null,'url':'/_next/static/chunks/app/page-e44cf5013fc59dd4.js'},{'revision':null,'url':'/_next/static/chunks/app/search/%5Bid%5D/page-41ff0151faf31a9f.js'},{'revision':null,'url':'/_next/static/chunks/bc98253f.a20b3a3cf1b114d6.js'},{'revision':null,'url':'/_next/static/chunks/c36f3faa.abb912aa7b92c8b5.js'},{'revision':null,'url':'/_next/static/chunks/d3ac728e-2af04ca4a833bf30.js'},{'revision':null,'url':'/_next/static/chunks/dc112a36-9a670afd7d3140fd.js'},{'revision':null,'url':'/_next/static/chunks/framework-6e3d659ca9a17c7d.js'},{'revision':null,'url':'/_next/static/chunks/main-app-103a28f346eee8b8.js'},{'revision':null,'url':'/_next/static/chunks/main-bccdb076287131f3.js'},{'revision':null,'url':'/_next/static/chunks/pages/_app-8e94039938385921.js'},{'revision':null,'url':'/_next/static/chunks/pages/_error-7b2d139042a6a5ab.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-dcf397fac3660387.js'},{'revision':null,'url':'/_next/static/css/2f46e0db0d4a3aed.css'},{'revision':null,'url':'/_next/static/css/4183e00ad0e88413.css'},{'revision':null,'url':'/_next/static/css/a67336182a0a18f5.css'},{'revision':null,'url':'/_next/static/css/c35610c794fcbaaa.css'},{'revision':null,'url':'/_next/static/css/db2aa7ffab7df38d.css'},{'revision':'be7c930fceb794521be0a68e113a71d8','url':'/_next/static/media/034d78ad42e9620c-s.woff2'},{'revision':'b550bca8934bd86812d1f5e28c9cc1de','url':'/_next/static/media/0484562807a97172-s.p.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'69d9d2cdadeab7225297d50fc8e48e8b','url':'/_next/static/media/29a4aea02fdee119-s.woff2'},{'revision':'9e3ecbe4bb4c6f0b71adc1cd481c2bdc','url':'/_next/static/media/29e7bbdce9332268-s.woff2'},{'revision':'792477d09826b11d1e5a611162c9797a','url':'/_next/static/media/8888a3826f4a3af4-s.p.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.1608a09b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.4aafdb68.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_AMS-Regular.a79f1c31.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.b6770918.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.9f256b85.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.7c187121.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.b74a1a8b.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Bold.d181c465.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.47373d1e.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.8916142b.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Italic.9024d815.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.0462f03b.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.7f51fe03.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.572d331f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.5295ba48.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.939bc644.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Math-Italic.f28c23ac.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Bold.bf59d231.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.74048478.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.03e9641d.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.07505710.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.e1e279cb.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.eae34984.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size1-Regular.fabc004a.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.57727022.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.5916a24f.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size2-Regular.d6b476ec.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.9acaf01c.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.a144ef58.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Size3-Regular.b4230e7e.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.10d95fd3.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.7a996c9d.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Size4-Regular.fbccdabe.ttf'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.6258592b.woff'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2'},{'revision':null,'url':'/_next/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf'},{'revision':'d3aa06d13d3cf9c0558927051f3cb948','url':'/_next/static/media/a1386beebedccca4-s.woff2'},{'revision':'0bd523f6049956faaf43c254a719d06a','url':'/_next/static/media/b957ea75a84b6ea7-s.p.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'5a1b7c983a9dc0a87a2ff138e07ae822','url':'/_next/static/media/c3bc380753a8436c-s.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'9516f567cd80b0f418bba2f1299ed6d1','url':'/_next/static/media/db911767852bc875-s.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'43751174b6b810eb169101a20d8c26f8','url':'/_next/static/media/eafabf029ad39a43-s.p.woff2'},{'revision':'63af7d5e18e585fad8d0220e5d551da1','url':'/_next/static/media/f10b8e9d91f3edcb-s.woff2'},{'revision':'f2a04185547c36abfa589651236a9849','url':'/_next/static/media/fe0777f1195381cb-s.woff2'},{'revision':'460f55cf1456f5a201f259a4eb607989','url':'/icons/apple-touch-icon.png'},{'revision':'69784622e4b55d2666c5180fb954d781','url':'/icons/icon-192x192.png'},{'revision':'ab07c93bfbd862c758c4d6d31085a6db','url':'/icons/icon-512x512-maskable.png'},{'revision':'f1b0e1527b676413a8b8e0154f671984','url':'/icons/icon-512x512.png'},{'revision':'2ed79e1d8607156994a2a6462563d7f0','url':'/images/Q zoom.json'},{'revision':'d088f99e3a3f1b7eaec384f36b0866d2','url':'/images/Q.json'},{'revision':'b14dbca44bb366d8499ae9a9b24a104f','url':'/images/eva-logo.png'},{'revision':'8f6cf4c9ec412fe201f80e2d23445aa9','url':'/images/logo.svg'},{'revision':'ab57101a81d25f409febeed6eb7e32bf','url':'/images/opengraph-image.png'}],skipWaiting:!1,clientsClaim:!1,navigationPreload:!1,runtimeCaching:[{matcher:/\.(?:js|css|woff2?|png|jpg|jpeg|svg|gif|ico)$/,handler:new eL({cacheName:"static-assets"})},{matcher:e=>{let{url:t,request:a}=e,r=t.pathname.startsWith("/api/"),s="/api/chat"===t.pathname&&"POST"===a.method||"/api/chats/all"===t.pathname&&"DELETE"===a.method;return r&&!s},handler:new ea({cacheName:"api-cache",networkTimeoutSeconds:5})},{matcher:e=>{let{request:t}=e;return"navigate"===t.mode},handler:new ea({cacheName:"pages-cache",networkTimeoutSeconds:5,plugins:[{handlerDidError:async()=>caches.match("/offline")}]})}]}).addEventListeners(),self.addEventListener("push",e=>{console.log("[Service Worker] Push Received.",e)}),self.addEventListener("sync",e=>{console.log("[Service Worker] Background Sync.",e)})})(); \ No newline at end of file diff --git a/tests/targeted.test.ts b/tests/targeted.test.ts new file mode 100644 index 00000000..a4967cd1 --- /dev/null +++ b/tests/targeted.test.ts @@ -0,0 +1,146 @@ +import { expect, test, describe, beforeAll, afterAll } from "bun:test"; +import { db } from "@/lib/db"; +import { users, chats, messages, calendarNotes } from "@/lib/db/schema"; +import { saveChat, getChatMessages } from "@/lib/actions/chat"; +import { getNotes, saveNote } from "@/lib/actions/calendar"; +import { getUIStateFromAIState, AIState } from "@/app/actions"; +import { eq } from "drizzle-orm"; + +// Mock auth helper since we don't have session auth here +import * as auth from "@/lib/auth/get-current-user"; +const dummyUserId = "11111111-1111-1111-1111-111111111111"; + +// Mock getCurrentUserIdOnServer +const originalGetCurrentUserIdOnServer = auth.getCurrentUserIdOnServer; +auth.getCurrentUserIdOnServer = async () => dummyUserId; + +describe("Targeted QCX Persistence and Rehydration Tests", () => { + beforeAll(async () => { + // Ensure our dummy user exists in the local database + await db.insert(users).values({ + id: dummyUserId, + email: "targeted-test-user@qcx.test", + }).onConflictDoNothing(); + }); + + afterAll(async () => { + // Clean up + await db.delete(calendarNotes).where(eq(calendarNotes.userId, dummyUserId)); + await db.delete(messages).where(eq(messages.userId, dummyUserId)); + await db.delete(chats).where(eq(chats.userId, dummyUserId)); + await db.delete(users).where(eq(users.id, dummyUserId)); + }); + + test("Message type and name persistence in saveChat", async () => { + const dummyChatId = "22222222-2222-2222-2222-222222222222"; + const chatData = { + id: dummyChatId, + title: "Test Chat", + createdAt: new Date(), + userId: dummyUserId, + path: `/search/${dummyChatId}`, + messages: [ + { + id: "33333333-3333-3333-3333-333333333333", + role: "assistant" as const, + content: "Hello! This is a test response.", + type: "response" as const, + name: "TestBot", + userId: dummyUserId, + createdAt: new Date(), + }, + { + id: "44444444-4444-4444-4444-444444444444", + role: "assistant" as const, + content: "end", + type: "end" as const, + userId: dummyUserId, + createdAt: new Date(), + } + ] + }; + + // Save the chat (filtering of synthetic 'end' message should happen in actions.tsx, + // but saveChat itself maps type/name columns correctly) + const savedChatId = await saveChat(chatData, dummyUserId); + expect(savedChatId).toBe(dummyChatId); + + // Rehydrate messages and verify fields + const dbMsgs = await getChatMessages(dummyChatId); + expect(dbMsgs.length).toBe(2); + + const mainMsg = dbMsgs.find(m => m.id === "33333333-3333-3333-3333-333333333333"); + expect(mainMsg).toBeDefined(); + expect(mainMsg?.type).toBe("response"); + expect(mainMsg?.name).toBe("TestBot"); + + const endMsg = dbMsgs.find(m => m.id === "44444444-4444-4444-4444-444444444444"); + expect(endMsg).toBeDefined(); + expect(endMsg?.type).toBe("end"); + }); + + test("Calendar notes date-range retrieval using Drizzle comparators", async () => { + const dummyChatId = "55555555-5555-5555-5555-555555555555"; + await db.insert(chats).values({ + id: dummyChatId, + userId: dummyUserId, + title: "Calendar Test Chat", + }).onConflictDoNothing(); + + // Create note on a specific date + const noteDate = new Date("2026-05-15T12:00:00Z"); + const note = await saveNote({ + userId: dummyUserId, + chatId: dummyChatId, + date: noteDate, + content: "Important calendar note", + locationTags: null, + userTags: null, + mapFeatureId: null, + }); + expect(note).toBeDefined(); + expect(note?.id).toBeDefined(); + + // Fetch notes for the exact day + const fetchedNotes = await getNotes(new Date("2026-05-15T00:00:00Z"), dummyChatId); + expect(fetchedNotes.length).toBe(1); + expect(fetchedNotes[0].content).toBe("Important calendar note"); + + // Fetch notes for a different day (should be empty) + const emptyNotes = await getNotes(new Date("2026-05-16T00:00:00Z"), dummyChatId); + expect(emptyNotes.length).toBe(0); + }); + + test("getUIStateFromAIState filters correctly and has fallbacks", () => { + const aiState: AIState = { + chatId: "test-chat-id", + messages: [ + { + id: "msg-1", + role: "user", + content: "hello", + type: "input", + }, + { + id: "msg-2", + role: "user", + content: "invalid-type-msg", + type: "unrecognized_type" as any, // Unrecognized type, should return null + }, + { + id: "msg-3", + role: "assistant", + content: "end", + type: "end", // Synthetic end, should be filtered/null + } + ] + }; + + const uiState = getUIStateFromAIState(aiState); + // Unrecognized user type should fall back to return null and be dropped. + // Synthetic end message should also return null and be dropped. + // Only 'msg-1' should remain in the returned uiState list. + expect(uiState.length).toBe(1); + expect(uiState[0].id).toBe("msg-1"); + }); +});