From 7ff609022f40562cdb0017cc7de5f1d4e1756a3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9C=A4=EC=A0=95=EB=AF=BC?= Date: Mon, 13 Apr 2026 09:18:34 +0900 Subject: [PATCH] init --- .../skills/developing-genkit-dart/SKILL.md | 57 + .../references/genkit.md | 380 ++++ .../references/genkit_anthropic.md | 41 + .../references/genkit_chrome.md | 23 + .../references/genkit_firebase_ai.md | 23 + .../references/genkit_google_genai.md | 95 + .../references/genkit_mcp.md | 115 ++ .../references/genkit_middleware.md | 84 + .../references/genkit_openai.md | 54 + .../references/genkit_shelf.md | 59 + .../references/schemantic.md | 137 ++ .agents/skills/developing-genkit-go/SKILL.md | 97 + .../references/flows-and-http.md | 183 ++ .../references/generation.md | 176 ++ .../references/getting-started.md | 142 ++ .../references/prompts.md | 256 +++ .../references/providers.md | 157 ++ .../developing-genkit-go/references/tools.md | 178 ++ .agents/skills/developing-genkit-js/SKILL.md | 112 ++ .../references/best-practices.md | 31 + .../references/common-errors.md | 132 ++ .../references/docs-and-cli.md | 62 + .../references/examples.md | 157 ++ .../developing-genkit-js/references/setup.md | 46 + .agents/skills/firebase-ai-logic/SKILL.md | 109 ++ .../references/usage_patterns_web.md | 174 ++ .../firebase-app-hosting-basics/SKILL.md | 58 + .../references/cli_commands.md | 71 + .../references/configuration.md | 51 + .../references/emulation.md | 47 + .agents/skills/firebase-auth-basics/SKILL.md | 86 + .../references/client_sdk_web.md | 287 +++ .../references/security_rules.md | 38 + .agents/skills/firebase-basics/SKILL.md | 52 + .../references/firebase-cli-guide.md | 16 + .../references/firebase-project-create.md | 11 + .../references/firebase-service-init.md | 18 + .../references/local-env-setup.md | 65 + .../references/refresh-antigravity.md | 46 + .../references/refresh-claude.md | 10 + .../references/refresh-gemini-cli.md | 11 + .../references/refresh-other-agents.md | 48 + .../references/setup-antigravity.md | 63 + .../references/setup-claude_code.md | 30 + .../references/setup-cursor.md | 63 + .../references/setup-gemini_cli.md | 39 + .../references/setup-github_copilot.md | 70 + .../references/setup-other_agents.md | 65 + .../firebase-basics/references/web_setup.md | 69 + .agents/skills/firebase-data-connect/SKILL.md | 95 + .../skills/firebase-data-connect/examples.md | 377 ++++ .../reference/advanced.md | 303 ++++ .../firebase-data-connect/reference/config.md | 267 +++ .../reference/operations.md | 357 ++++ .../firebase-data-connect/reference/schema.md | 278 +++ .../firebase-data-connect/reference/sdks.md | 287 +++ .../reference/security.md | 289 +++ .../skills/firebase-data-connect/templates.md | 269 +++ .../SKILL.md | 31 + .../references/data_model.md | 54 + .../references/indexes.md | 111 ++ .../references/provisioning.md | 101 ++ .../references/python_sdk_usage.md | 126 ++ .../references/security_rules.md | 414 +++++ .../references/web_sdk_usage.md | 201 +++ .../firebase-firestore-standard/SKILL.md | 27 + .../references/indexes.md | 82 + .../references/provisioning.md | 87 + .../references/security_rules.md | 414 +++++ .../references/web_sdk_usage.md | 183 ++ .../skills/firebase-hosting-basics/SKILL.md | 46 + .../references/configuration.md | 101 ++ .../references/deploying.md | 39 + .../firestore-security-rules-auditor/SKILL.md | 45 + .../skills/developing-genkit-dart/SKILL.md | 57 + .../references/genkit.md | 380 ++++ .../references/genkit_anthropic.md | 41 + .../references/genkit_chrome.md | 23 + .../references/genkit_firebase_ai.md | 23 + .../references/genkit_google_genai.md | 95 + .../references/genkit_mcp.md | 115 ++ .../references/genkit_middleware.md | 84 + .../references/genkit_openai.md | 54 + .../references/genkit_shelf.md | 59 + .../references/schemantic.md | 137 ++ .claude/skills/developing-genkit-go/SKILL.md | 97 + .../references/flows-and-http.md | 183 ++ .../references/generation.md | 176 ++ .../references/getting-started.md | 142 ++ .../references/prompts.md | 256 +++ .../references/providers.md | 157 ++ .../developing-genkit-go/references/tools.md | 178 ++ .claude/skills/developing-genkit-js/SKILL.md | 112 ++ .../references/best-practices.md | 31 + .../references/common-errors.md | 132 ++ .../references/docs-and-cli.md | 62 + .../references/examples.md | 157 ++ .../developing-genkit-js/references/setup.md | 46 + .claude/skills/firebase-ai-logic/SKILL.md | 109 ++ .../references/usage_patterns_web.md | 174 ++ .../firebase-app-hosting-basics/SKILL.md | 58 + .../references/cli_commands.md | 71 + .../references/configuration.md | 51 + .../references/emulation.md | 47 + .claude/skills/firebase-auth-basics/SKILL.md | 86 + .../references/client_sdk_web.md | 287 +++ .../references/security_rules.md | 38 + .claude/skills/firebase-basics/SKILL.md | 52 + .../references/firebase-cli-guide.md | 16 + .../references/firebase-project-create.md | 11 + .../references/firebase-service-init.md | 18 + .../references/local-env-setup.md | 65 + .../references/refresh-antigravity.md | 46 + .../references/refresh-claude.md | 10 + .../references/refresh-gemini-cli.md | 11 + .../references/refresh-other-agents.md | 48 + .../references/setup-antigravity.md | 63 + .../references/setup-claude_code.md | 30 + .../references/setup-cursor.md | 63 + .../references/setup-gemini_cli.md | 39 + .../references/setup-github_copilot.md | 70 + .../references/setup-other_agents.md | 65 + .../firebase-basics/references/web_setup.md | 69 + .claude/skills/firebase-data-connect/SKILL.md | 95 + .../skills/firebase-data-connect/examples.md | 377 ++++ .../reference/advanced.md | 303 ++++ .../firebase-data-connect/reference/config.md | 267 +++ .../reference/operations.md | 357 ++++ .../firebase-data-connect/reference/schema.md | 278 +++ .../firebase-data-connect/reference/sdks.md | 287 +++ .../reference/security.md | 289 +++ .../skills/firebase-data-connect/templates.md | 269 +++ .../SKILL.md | 31 + .../references/data_model.md | 54 + .../references/indexes.md | 111 ++ .../references/provisioning.md | 101 ++ .../references/python_sdk_usage.md | 126 ++ .../references/security_rules.md | 414 +++++ .../references/web_sdk_usage.md | 201 +++ .../firebase-firestore-standard/SKILL.md | 27 + .../references/indexes.md | 82 + .../references/provisioning.md | 87 + .../references/security_rules.md | 414 +++++ .../references/web_sdk_usage.md | 183 ++ .../skills/firebase-hosting-basics/SKILL.md | 46 + .../references/configuration.md | 101 ++ .../references/deploying.md | 39 + .../firestore-security-rules-auditor/SKILL.md | 45 + database-debug.log | 0 firebase-debug.log | 1571 +++++++++++++++++ firestore-debug.log | 0 remoteconfig.template.json | 1 + skills-lock.json | 65 + src/constants/levels.ts | 12 + src/firebase.ts | 12 + src/handlers/adminHandlers.ts | 24 + src/handlers/authHandlers.ts | 20 + src/handlers/kboHandlers.ts | 105 ++ src/handlers/predictionHandlers.ts | 57 + src/handlers/statsHandlers.ts | 31 + src/kbo/README.md | 325 ++++ src/kbo/schedule.ts | 241 +++ src/middleware/admin.ts | 21 + src/middleware/auth.ts | 19 + src/middleware/errors.ts | 16 + src/repositories/gameRepository.ts | 37 + src/repositories/kboCacheRepository.ts | 145 ++ src/repositories/kboRepository.ts | 113 ++ src/repositories/userRepository.ts | 55 + src/repositories/voteHistoryRepository.ts | 67 + src/repositories/voteRepository.ts | 123 ++ src/scheduled/dailyArchive.ts | 54 + src/scheduled/kboRefresh.ts | 57 + src/services/authService.ts | 27 + src/services/gameResultService.ts | 55 + src/services/gameSyncService.ts | 75 + src/services/playerService.ts | 43 + src/services/predictionService.ts | 106 ++ src/services/rankService.ts | 9 + src/services/scheduleService.ts | 20 + src/services/statsService.ts | 190 ++ src/types/dateString.ts | 49 + src/types/kbo.ts | 25 + src/types/panit.ts | 47 + tests/repositories/gameRepository.test.ts | 66 + tests/repositories/kboRepository.test.ts | 78 + .../voteHistoryRepository.test.ts | 91 + tests/repositories/voteRepository.test.ts | 148 ++ tests/services/gameSyncService.test.ts | 117 ++ tests/setup.ts | 8 + vitest.config.ts | 12 + 191 files changed, 22293 insertions(+) create mode 100644 .agents/skills/developing-genkit-dart/SKILL.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_anthropic.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_chrome.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_google_genai.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_mcp.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_middleware.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_openai.md create mode 100644 .agents/skills/developing-genkit-dart/references/genkit_shelf.md create mode 100644 .agents/skills/developing-genkit-dart/references/schemantic.md create mode 100644 .agents/skills/developing-genkit-go/SKILL.md create mode 100644 .agents/skills/developing-genkit-go/references/flows-and-http.md create mode 100644 .agents/skills/developing-genkit-go/references/generation.md create mode 100644 .agents/skills/developing-genkit-go/references/getting-started.md create mode 100644 .agents/skills/developing-genkit-go/references/prompts.md create mode 100644 .agents/skills/developing-genkit-go/references/providers.md create mode 100644 .agents/skills/developing-genkit-go/references/tools.md create mode 100644 .agents/skills/developing-genkit-js/SKILL.md create mode 100644 .agents/skills/developing-genkit-js/references/best-practices.md create mode 100644 .agents/skills/developing-genkit-js/references/common-errors.md create mode 100644 .agents/skills/developing-genkit-js/references/docs-and-cli.md create mode 100644 .agents/skills/developing-genkit-js/references/examples.md create mode 100644 .agents/skills/developing-genkit-js/references/setup.md create mode 100644 .agents/skills/firebase-ai-logic/SKILL.md create mode 100644 .agents/skills/firebase-ai-logic/references/usage_patterns_web.md create mode 100644 .agents/skills/firebase-app-hosting-basics/SKILL.md create mode 100644 .agents/skills/firebase-app-hosting-basics/references/cli_commands.md create mode 100644 .agents/skills/firebase-app-hosting-basics/references/configuration.md create mode 100644 .agents/skills/firebase-app-hosting-basics/references/emulation.md create mode 100644 .agents/skills/firebase-auth-basics/SKILL.md create mode 100644 .agents/skills/firebase-auth-basics/references/client_sdk_web.md create mode 100644 .agents/skills/firebase-auth-basics/references/security_rules.md create mode 100644 .agents/skills/firebase-basics/SKILL.md create mode 100644 .agents/skills/firebase-basics/references/firebase-cli-guide.md create mode 100644 .agents/skills/firebase-basics/references/firebase-project-create.md create mode 100644 .agents/skills/firebase-basics/references/firebase-service-init.md create mode 100644 .agents/skills/firebase-basics/references/local-env-setup.md create mode 100644 .agents/skills/firebase-basics/references/refresh-antigravity.md create mode 100644 .agents/skills/firebase-basics/references/refresh-claude.md create mode 100644 .agents/skills/firebase-basics/references/refresh-gemini-cli.md create mode 100644 .agents/skills/firebase-basics/references/refresh-other-agents.md create mode 100644 .agents/skills/firebase-basics/references/setup-antigravity.md create mode 100644 .agents/skills/firebase-basics/references/setup-claude_code.md create mode 100644 .agents/skills/firebase-basics/references/setup-cursor.md create mode 100644 .agents/skills/firebase-basics/references/setup-gemini_cli.md create mode 100644 .agents/skills/firebase-basics/references/setup-github_copilot.md create mode 100644 .agents/skills/firebase-basics/references/setup-other_agents.md create mode 100644 .agents/skills/firebase-basics/references/web_setup.md create mode 100644 .agents/skills/firebase-data-connect/SKILL.md create mode 100644 .agents/skills/firebase-data-connect/examples.md create mode 100644 .agents/skills/firebase-data-connect/reference/advanced.md create mode 100644 .agents/skills/firebase-data-connect/reference/config.md create mode 100644 .agents/skills/firebase-data-connect/reference/operations.md create mode 100644 .agents/skills/firebase-data-connect/reference/schema.md create mode 100644 .agents/skills/firebase-data-connect/reference/sdks.md create mode 100644 .agents/skills/firebase-data-connect/reference/security.md create mode 100644 .agents/skills/firebase-data-connect/templates.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md create mode 100644 .agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md create mode 100644 .agents/skills/firebase-firestore-standard/SKILL.md create mode 100644 .agents/skills/firebase-firestore-standard/references/indexes.md create mode 100644 .agents/skills/firebase-firestore-standard/references/provisioning.md create mode 100644 .agents/skills/firebase-firestore-standard/references/security_rules.md create mode 100644 .agents/skills/firebase-firestore-standard/references/web_sdk_usage.md create mode 100644 .agents/skills/firebase-hosting-basics/SKILL.md create mode 100644 .agents/skills/firebase-hosting-basics/references/configuration.md create mode 100644 .agents/skills/firebase-hosting-basics/references/deploying.md create mode 100644 .agents/skills/firestore-security-rules-auditor/SKILL.md create mode 100644 .claude/skills/developing-genkit-dart/SKILL.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_anthropic.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_chrome.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_firebase_ai.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_google_genai.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_mcp.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_middleware.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_openai.md create mode 100644 .claude/skills/developing-genkit-dart/references/genkit_shelf.md create mode 100644 .claude/skills/developing-genkit-dart/references/schemantic.md create mode 100644 .claude/skills/developing-genkit-go/SKILL.md create mode 100644 .claude/skills/developing-genkit-go/references/flows-and-http.md create mode 100644 .claude/skills/developing-genkit-go/references/generation.md create mode 100644 .claude/skills/developing-genkit-go/references/getting-started.md create mode 100644 .claude/skills/developing-genkit-go/references/prompts.md create mode 100644 .claude/skills/developing-genkit-go/references/providers.md create mode 100644 .claude/skills/developing-genkit-go/references/tools.md create mode 100644 .claude/skills/developing-genkit-js/SKILL.md create mode 100644 .claude/skills/developing-genkit-js/references/best-practices.md create mode 100644 .claude/skills/developing-genkit-js/references/common-errors.md create mode 100644 .claude/skills/developing-genkit-js/references/docs-and-cli.md create mode 100644 .claude/skills/developing-genkit-js/references/examples.md create mode 100644 .claude/skills/developing-genkit-js/references/setup.md create mode 100644 .claude/skills/firebase-ai-logic/SKILL.md create mode 100644 .claude/skills/firebase-ai-logic/references/usage_patterns_web.md create mode 100644 .claude/skills/firebase-app-hosting-basics/SKILL.md create mode 100644 .claude/skills/firebase-app-hosting-basics/references/cli_commands.md create mode 100644 .claude/skills/firebase-app-hosting-basics/references/configuration.md create mode 100644 .claude/skills/firebase-app-hosting-basics/references/emulation.md create mode 100644 .claude/skills/firebase-auth-basics/SKILL.md create mode 100644 .claude/skills/firebase-auth-basics/references/client_sdk_web.md create mode 100644 .claude/skills/firebase-auth-basics/references/security_rules.md create mode 100644 .claude/skills/firebase-basics/SKILL.md create mode 100644 .claude/skills/firebase-basics/references/firebase-cli-guide.md create mode 100644 .claude/skills/firebase-basics/references/firebase-project-create.md create mode 100644 .claude/skills/firebase-basics/references/firebase-service-init.md create mode 100644 .claude/skills/firebase-basics/references/local-env-setup.md create mode 100644 .claude/skills/firebase-basics/references/refresh-antigravity.md create mode 100644 .claude/skills/firebase-basics/references/refresh-claude.md create mode 100644 .claude/skills/firebase-basics/references/refresh-gemini-cli.md create mode 100644 .claude/skills/firebase-basics/references/refresh-other-agents.md create mode 100644 .claude/skills/firebase-basics/references/setup-antigravity.md create mode 100644 .claude/skills/firebase-basics/references/setup-claude_code.md create mode 100644 .claude/skills/firebase-basics/references/setup-cursor.md create mode 100644 .claude/skills/firebase-basics/references/setup-gemini_cli.md create mode 100644 .claude/skills/firebase-basics/references/setup-github_copilot.md create mode 100644 .claude/skills/firebase-basics/references/setup-other_agents.md create mode 100644 .claude/skills/firebase-basics/references/web_setup.md create mode 100644 .claude/skills/firebase-data-connect/SKILL.md create mode 100644 .claude/skills/firebase-data-connect/examples.md create mode 100644 .claude/skills/firebase-data-connect/reference/advanced.md create mode 100644 .claude/skills/firebase-data-connect/reference/config.md create mode 100644 .claude/skills/firebase-data-connect/reference/operations.md create mode 100644 .claude/skills/firebase-data-connect/reference/schema.md create mode 100644 .claude/skills/firebase-data-connect/reference/sdks.md create mode 100644 .claude/skills/firebase-data-connect/reference/security.md create mode 100644 .claude/skills/firebase-data-connect/templates.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/SKILL.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/data_model.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/indexes.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md create mode 100644 .claude/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md create mode 100644 .claude/skills/firebase-firestore-standard/SKILL.md create mode 100644 .claude/skills/firebase-firestore-standard/references/indexes.md create mode 100644 .claude/skills/firebase-firestore-standard/references/provisioning.md create mode 100644 .claude/skills/firebase-firestore-standard/references/security_rules.md create mode 100644 .claude/skills/firebase-firestore-standard/references/web_sdk_usage.md create mode 100644 .claude/skills/firebase-hosting-basics/SKILL.md create mode 100644 .claude/skills/firebase-hosting-basics/references/configuration.md create mode 100644 .claude/skills/firebase-hosting-basics/references/deploying.md create mode 100644 .claude/skills/firestore-security-rules-auditor/SKILL.md create mode 100644 database-debug.log create mode 100644 firebase-debug.log create mode 100644 firestore-debug.log create mode 100644 remoteconfig.template.json create mode 100644 skills-lock.json create mode 100644 src/constants/levels.ts create mode 100644 src/firebase.ts create mode 100644 src/handlers/adminHandlers.ts create mode 100644 src/handlers/authHandlers.ts create mode 100644 src/handlers/kboHandlers.ts create mode 100644 src/handlers/predictionHandlers.ts create mode 100644 src/handlers/statsHandlers.ts create mode 100644 src/kbo/README.md create mode 100644 src/kbo/schedule.ts create mode 100644 src/middleware/admin.ts create mode 100644 src/middleware/auth.ts create mode 100644 src/middleware/errors.ts create mode 100644 src/repositories/gameRepository.ts create mode 100644 src/repositories/kboCacheRepository.ts create mode 100644 src/repositories/kboRepository.ts create mode 100644 src/repositories/userRepository.ts create mode 100644 src/repositories/voteHistoryRepository.ts create mode 100644 src/repositories/voteRepository.ts create mode 100644 src/scheduled/dailyArchive.ts create mode 100644 src/scheduled/kboRefresh.ts create mode 100644 src/services/authService.ts create mode 100644 src/services/gameResultService.ts create mode 100644 src/services/gameSyncService.ts create mode 100644 src/services/playerService.ts create mode 100644 src/services/predictionService.ts create mode 100644 src/services/rankService.ts create mode 100644 src/services/scheduleService.ts create mode 100644 src/services/statsService.ts create mode 100644 src/types/dateString.ts create mode 100644 src/types/kbo.ts create mode 100644 src/types/panit.ts create mode 100644 tests/repositories/gameRepository.test.ts create mode 100644 tests/repositories/kboRepository.test.ts create mode 100644 tests/repositories/voteHistoryRepository.test.ts create mode 100644 tests/repositories/voteRepository.test.ts create mode 100644 tests/services/gameSyncService.test.ts create mode 100644 tests/setup.ts create mode 100644 vitest.config.ts diff --git a/.agents/skills/developing-genkit-dart/SKILL.md b/.agents/skills/developing-genkit-dart/SKILL.md new file mode 100644 index 0000000..706023b --- /dev/null +++ b/.agents/skills/developing-genkit-dart/SKILL.md @@ -0,0 +1,57 @@ +--- +name: developing-genkit-dart +description: Generates code and provides documentation for the Genkit Dart SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or integrate LLMs into Dart/Flutter applications. +metadata: + genkit-managed: true +--- + +# Genkit Dart + +Genkit Dart is an AI SDK for Dart that provides a unified interface for code generation, structured outputs, tools, flows, and AI agents. + +## Core Features and Usage +If you need help with initializing Genkit (`Genkit()`), Generation (`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings (`ai.embedMany`), streaming, or calling remote flow endpoints, please load the core framework reference: +[references/genkit.md](references/genkit.md) + +## Genkit CLI (recommended) + +The Genkit CLI provides a local development UI for running Flow, tracing executions, playing with models, and evaluating outputs. + +check if the user has it installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash # Native CLI +# OR +npm install -g genkit-cli # Via npm +``` + +**Usage:** +Wrap your run command with `genkit start` to attach the Genkit developer UI and tracing: +```bash +genkit start -- dart run main.dart +``` + +## Plugin Ecosystem +Genkit relies on a large suite of plugins to perform generative AI actions, interface with external LLMs, or host web servers. + +When asked to use any given plugin, always verify usage by referring to its corresponding reference below. You should load the reference when you need to know the specific initialization arguments, tools, models, and usage patterns for the plugin: + +| Plugin Name | Reference Link | Description | +| ---- | ---- | ---- | +| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. | +| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. | +| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. | +| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. | +| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). | +| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. | +| `genkit_shelf` | [references/genkit_shelf.md](references/genkit_shelf.md) | Load for Integrating Genkit Flow actions over HTTP using Dart Shelf. | +| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). | + +## External Dependencies +Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you must use the [schemantic](https://pub.dev/packages/schemantic) library. +To learn how to use schemantic, ensure you read [references/schemantic.md](references/schemantic.md) for how to implement type safe generated Dart code. This is particularly relevant when you encounter symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix. Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill to understand for using Genkit Dart. + +## Best Practices +- Always check that code cleanly compiles using `dart analyze` before generating the final response. +- Always use the Genkit CLI for local development and debugging. diff --git a/.agents/skills/developing-genkit-dart/references/genkit.md b/.agents/skills/developing-genkit-dart/references/genkit.md new file mode 100644 index 0000000..7dd33e5 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit.md @@ -0,0 +1,380 @@ +# Genkit Core Framework + +Genkit Dart is an AI SDK for Dart that provides a unified interface for text generation, structured output, tool calling, and agentic workflows. + +## Initialization + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; // Or any other plugin + +void main() async { + // Pass plugins to use into the Genkit constructor + final ai = Genkit(plugins: [googleAI()]); +} +``` + +## Generate Text + +```dart +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), // Needs a model reference from a plugin + prompt: 'Explain quantum computing in simple terms.', +); + +print(response.text); +``` + +## Stream Responses +```dart +final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a short story about a robot learning to paint.', +); + +await for (final chunk in stream) { + print(chunk.text); +} +``` + +## Embed Text +```dart +final embeddings = await ai.embedMany( + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], + embedder: googleAI.textEmbedding('text-embedding-004'), +); + +print(embeddings.first.embedding); +``` + +## Define Tools +Models can use define actions and access external data via custom defined tools. +Requires the `schemantic` library for schema definitions. + +```dart +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $WeatherInput { + String get location; +} + +final weatherTool = ai.defineTool( + name: 'getWeather', + description: 'Gets the current weather for a location', + inputSchema: WeatherInput.$schema, + fn: (input, _) async { + // Call your weather API here + return 'Weather in ${input.location}: 72°F and sunny'; + }, +); + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'What\'s the weather like in San Francisco?', + toolNames: ['getWeather'], // Use the tools +); +``` + +## Structured Output + +You can ensure the generative model returns a typed JSON object by providing an `outputSchema`. + +```dart +@Schema() +abstract class $Person { + String get name; + int get age; +} + +// ... inside main ... + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Generate a person named John Doe, age 30', + outputSchema: Person.$schema, // Force the model to return this schema +); + +final person = response.output; // Typed Person object +print('Name: ${person.name}, Age: ${person.age}'); +``` + +## Define Flows +Wrap your AI logic in flows for better observability, testing, and deployment: + +```dart +final jokeFlow = ai.defineFlow( + name: 'tellJoke', + inputSchema: .string(), + outputSchema: .string(), + fn: (topic, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about $topic', + ); + return response.text; // Value return + }, +); + +final joke = await jokeFlow('programming'); +print(joke); +``` + +### Streaming Flows +Stream data from your flows using `context.sendChunk(...)` and returning the final value: + +```dart +final streamStory = ai.defineFlow( + name: 'streamStory', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), + fn: (topic, context) async { + final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a story about $topic', + ); + + await for (final chunk in stream) { + context.sendChunk(chunk.text); // Stream the chunks + } + return 'Story complete'; // Value return + }, +); +``` + +## Calling remote Flows from a dart client +The `genkit` package provides `package:genkit/client.dart` representing remote Genkit actions that can be invoked or streamed using type-safe definitions. + +1. Defines a remote action +```dart +import 'package:genkit/client.dart'; + +final stringAction = defineRemoteAction( + url: 'http://localhost:3400/my-flow', + inputSchema: .string(), + outputSchema: .string(), +); +``` + +2. Call the Remote Action (Non-streaming) +```dart +final response = await stringAction(input: 'Hello from Dart!'); +print('Flow Response: $response'); +``` + +3. Call the Remote Action (Streaming) +Use the `.stream()` method on the action flow, and access `stream.onResult` to wait on the async return value. +```dart +final streamAction = defineRemoteAction( + url: 'http://localhost:3400/stream-story', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), +); + +final stream = streamAction.stream( + input: 'Tell me a short story about a Dart developer.', +); + +await for (final chunk in stream) { + print('Chunk: $chunk'); +} + +final finalResult = await stream.onResult; +print('\nFinal Response: $finalResult'); +``` + +## Calling remote Flows from a Javascript client + +Install `genkit` npm package: + +```bash +npm install genkit +``` + +1. Call a remote flow (non-streaming) + +```ts +import { runFlow } from 'genkit/beta/client'; + +async function callHelloFlow() { + try { + const result = await runFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Genkit User' }, + }); + console.log('Non-streaming result:', result.greeting); + } catch (error) { + console.error('Error calling helloFlow:', error); + } +} + +callHelloFlow(); +``` + +2. Call a remote flow (streaming) + +```ts +import { streamFlow } from 'genkit/beta/client'; + +async function streamHelloFlow() { + try { + const result = streamFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Streaming User' }, + }); + + // Process the stream chunks as they arrive + for await (const chunk of result.stream) { + console.log('Stream chunk:', chunk); + } + + // Get the final complete response + const finalOutput = await result.output; + console.log('Final streaming output:', finalOutput.greeting); + } catch (error) { + console.error('Error streaming helloFlow:', error); + } +} + +streamHelloFlow(); +``` + +## Data Models + +Genkit uses standard data models for representing prompts (messages & parts) and responses. These classes are implemented using schemantic library. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $MyDataModel { + // uses Genkit's Message schema (not schemantic's Message) + List<$Message> get messages; + List<$Part> get parts; +} + +void example() { + // --- Parts --- + // A Text part + final textPart = TextPart(text: 'some text', metadata: {'foo': 'bar'}); + + // A Media/Image part + final mediaPart = MediaPart( + media: Media(url: 'https://...', contentType: 'image/png'), + metadata: {'foo': 'bar'}, + ); + + // A Tool Request initiated by the model + final toolRequestPart = ToolRequestPart( + toolRequest: ToolRequest( + name: 'get_weather', + ref: 'abc', + input: {'location': 'Paris, France'}, + ), + metadata: {'foo': 'bar'}, + ); + + // The resulting data from a Tool execution + final toolResponsePart = ToolResponsePart( + toolResponse: ToolResponse( + name: 'get_weather', + ref: 'abc', + output: {'temperature': '20C'}, + ), + metadata: {'foo': 'bar'}, + ); + + // Model reasoning (e.g. for Claude's "thinking" models) + final reasoningPart = ReasoningPart( + reasoning: 'thinking...', + metadata: {'foo': 'bar'}, + ); + + // A custom fallback part + final customPart = CustomPart( + custom: {'provider': {'specific': 'data'}}, + metadata: {'foo': 'bar'}, + ); + + // --- Messages --- + final systemMessage = Message( + role: Role.system, + content: [textPart, mediaPart], + metadata: {'foo': 'bar'}, + ); + + final userMessage = Message( + role: Role.user, + content: [textPart, mediaPart], // Can contain media (multimodal) + ); + + final modelMessage = Message( + role: Role.model, + // Models can emit text, tool requests, reasoning, or custom parts + content: [textPart, toolRequestPart, reasoningPart, customPart], + ); + + // --- Ergonomic Data Access (schema_extensions.dart) --- + // The Genkit SDK provides extensions on `Message` and `Part` to easily access fields + // without needing to cast them manually. + + // Get concatenated text from all TextParts in a Message + print(modelMessage.text); + + // Get the first Media object from a Message + print(modelMessage.media?.url); + + // Iterate over tool requests in a Message + for (final toolReq in modelMessage.toolRequests) { + print(toolReq.name); + } + + // Inspect individual parts + for (final part in modelMessage.content) { + if (part.isText) print(part.text); + if (part.isMedia) print(part.media?.url); + if (part.isToolRequest) print(part.toolRequest?.name); + if (part.isToolResponse) print(part.toolResponse?.name); + if (part.isReasoning) print(part.reasoning); + if (part.isCustom) print(part.custom); + } + + // --- Streaming Chunks --- + // Data emitted by ai.generateStream() calls + final generateResponseChunk = ModelResponseChunk( + content: [textPart], + index: 0, // Index of the message this chunk belongs to + aggregated: false, + ); + + // Chunks also have text and media accessors + print(generateResponseChunk.text); + + // --- Advanced: Schemas --- + // Use Genkit type schemas directly in Schemantic validations + final messageSchema = Message.$schema; + final partSchema = Part.$schema; + + final mySchema = SchemanticType.map( + .string(), + .list(Message.$schema), // Requires a list of Messages + ); + + // --- Generate Response --- + // ai.generate() returns a GenerateResponseHelper which provides ergonomic getters + // over the underlying ModelResponse: + final response = await ai.generate(...); + + print(response.text); // Concatenated text + print(response.media?.url); // First media part + print(response.toolRequests); // All tool requests + print(response.interrupts); // Tool requests that triggered an interrupt + print(response.messages); // Full history of the conversation, including the request and response + print(response.output); // Structured typed output (if outputSchema was used) +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md new file mode 100644 index 0000000..2e420a3 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md @@ -0,0 +1,41 @@ +# Genkit Anthropic Plugin (`genkit_anthropic`) + +The Anthropic plugin for Genkit Dart, used for interacting with the Claude models. + +## Usage + +Requires `ANTHROPIC_API_KEY` to be passed to the init block. + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_anthropic/genkit_anthropic.dart'; + +void main() async { + final ai = Genkit( + plugins: [anthropic(apiKey: Platform.environment['ANTHROPIC_API_KEY']!)], + ); + + final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Claude Thinking Configurations + +Provides specific configurations for utilizing Claude 3.7+ "thinking" model capabilities. + +```dart +final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Solve this 24 game: 2, 3, 10, 10', + config: AnthropicOptions(thinking: ThinkingConfig(budgetTokens: 2048)), +); + +// The thinking content is available in the message parts +print(response.message?.content); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_chrome.md b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md new file mode 100644 index 0000000..8152369 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md @@ -0,0 +1,23 @@ +# Genkit Chrome AI Plugin (`genkit_chrome`) + +Chrome Built-in AI (Gemini Nano) plugin for Genkit Dart, allowing local offline execution within a Chrome application. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_chrome/genkit_chrome.dart'; + +void main() async { + final ai = Genkit(plugins: [ChromeAIPlugin()]); + + final stream = ai.generateStream( + model: modelRef('chrome/gemini-nano'), + prompt: 'Write a story about a robot.', + ); + + await for (final chunk in stream) { + print(chunk.text); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md new file mode 100644 index 0000000..7ec462d --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md @@ -0,0 +1,23 @@ +# Genkit Firebase AI Plugin (`genkit_firebase_ai`) + +The Firebase AI plugin for Genkit Dart, used for interacting with Gemini APIs through Firebase AI Logic. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_firebase_ai/genkit_firebase_ai.dart'; + +void main() async { + // Initialize Genkit with the Firebase AI plugin + final ai = Genkit(plugins: [firebaseAI()]); + + // Generate text + final response = await ai.generate( + model: firebaseAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md new file mode 100644 index 0000000..92d3ec4 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md @@ -0,0 +1,95 @@ +# Genkit Google GenAI Plugin (`genkit_google_genai`) + +The Google AI plugin provides an interface against the official Google AI Gemini API. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; + +void main() async { + // Initialize Genkit with the Google AI plugin + final ai = Genkit(plugins: [googleAI()]); + + // Generate text + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Embeddings + +```dart +final embeddings = await ai.embedMany( + embedder: googleAI.textEmbedding('text-embedding-004'), + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], +); +``` + +## Image Generation + +The plugin also supports image generation models such as `gemini-2.5-flash-image`. + +### Example (Nano Banana) + +```dart +// Define an image generation flow +ai.defineFlow( + name: 'imageGenerator', + inputSchema: .string(defaultValue: 'A banana riding a bike'), + outputSchema: Media.$schema, + fn: (input, context) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-image'), + prompt: input, + ); + if (response.media == null) { + throw Exception('No media generated'); + } + return response.media!; + }, +); +``` + +The media (url field) contain base64 encoded data uri. You can decode it and save it as a file. + +## Text-to-Speech (TTS) + +You can use text-to-speech models to generate audio from text. The generated `Media` object will contain base64 encoded PCM audio in its data URI. + +```dart +// Define a TTS flow +ai.defineFlow( + name: 'textToSpeech', + inputSchema: .string(defaultValue: 'Genkit is an amazing AI framework!'), + outputSchema: Media.$schema, + fn: (prompt, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-preview-tts'), + prompt: prompt, + config: GeminiTtsOptions( + responseModalities: ['AUDIO'], + speechConfig: SpeechConfig( + voiceConfig: VoiceConfig( + prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Puck'), + ), + ), + ), + ); + + if (response.media != null) { + return response.media!; + } + throw Exception('No audio generated'); + }, +); +``` + +Google AI also supports multi-speaker TTS by configuring a `MultiSpeakerVoiceConfig` inside `SpeechConfig`. diff --git a/.agents/skills/developing-genkit-dart/references/genkit_mcp.md b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md new file mode 100644 index 0000000..ce8ddb0 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md @@ -0,0 +1,115 @@ +# Genkit MCP (`genkit_mcp`) + +MCP (Model Context Protocol) integration for Genkit Dart. + +## MCP Host (Recommended) +Connect to one or more MCP servers and aggregate their capabilities into the Genkit registry automatically. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final host = defineMcpHost( + ai, + McpHostOptionsWithCache( + name: 'my-host', + mcpServers: { + 'fs': McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + }, + ), + ); + + // Tools can be discovered and executed dynamically using a wildcard... + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Summarize the contents of README.md', + toolNames: ['my-host:tool/fs/*'], + ); + + // ...or by specifying the exact tool name + final exactResponse = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read README.md', + toolNames: ['my-host:tool/fs/read_file'], + ); +} +``` + +## MCP Client (Advanced / Single Server) +Connecting to a single MCP server with a client object is an advanced usecase for when you need manual control over the client lifecycle. Standalone clients do not automatically register tools into the registry, so they must be passed into `generate` or `defineDynamicActionProvider` manually. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final client = createMcpClient( + McpClientOptions( + name: 'my-client', + mcpServer: McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + ), + ); + + await client.ready(); + + // Retrieve the tools from the connected client + final tools = await client.getActiveTools(ai); + + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read the contents of README.md', + tools: tools, + ); +} +``` + +## MCP Server +Expose Genkit actions (tools, prompts, resources) over MCP. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + ai.defineTool( + name: 'add', + description: 'Add two numbers together', + inputSchema: .map(.string(), .dynamicSChema()), + fn: (input, _) async => (input['a'] + input['b']).toString(), + ); + + ai.defineResource( + name: 'my-resource', + uri: 'my://resource', + fn: (_, _) async => ResourceOutput(content: [TextPart(text: 'my resource')]), + ); + + // Stdio transport by default + final server = createMcpServer(ai, McpServerOptions(name: 'my-server')); + await server.start(); +} +``` + +### Streamable HTTP Transport +```dart +import 'dart:io'; + +final transport = await StreamableHttpServerTransport.bind( + address: InternetAddress.loopbackIPv4, + port: 3000, +); +await server.start(transport); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_middleware.md b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md new file mode 100644 index 0000000..24cff79 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md @@ -0,0 +1,84 @@ +# Genkit Middleware (`genkit_middleware`) + +A collection of useful middleware for Genkit Dart to enhance your agent's capabilities. Register plugins when initializing Genkit: + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_middleware/genkit_middleware.dart'; + +void main() { + final ai = Genkit( + plugins: [ + FilesystemPlugin(), + SkillsPlugin(), + ToolApprovalPlugin(), + ], + ); +} +``` + +## Filesystem Middleware +Allows the agent to list, read, write, and search/replace files within a restricted root directory. + +```dart +final response = await ai.generate( + prompt: 'Check the logs in the current directory.', + use: [ + filesystem(rootDirectory: '/path/to/secure/workspace'), + ], +); +``` + +**Tools Provided:** +- `list_files`, `read_file`, `write_file`, `search_and_replace` + +## Skills Middleware +Injects specialized instructions (skills) into the system prompt from `SKILL.md` files located in specified directories. + +```dart +final response = await ai.generate( + prompt: 'Help me debug this issue.', + use: [ + skills(skillPaths: ['/path/to/skills']), + ], +); +``` + +**Tools Provided:** +- `use_skill`: Retrieve the full content of a skill by name. + +## Tool Approval Middleware +Intercepts tool execution for specified tools and requires explicit approval. Returns `FinishReason.interrupted`. + +```dart +final response = await ai.generate( + prompt: 'Delete the database.', + use: [ + // Require approval for all tools EXCEPT those below + toolApproval(approved: ['read_file', 'list_files']), + ], +); + +if (response.finishReason == FinishReason.interrupted) { + final interrupt = response.interrupts.first; + + // Ask user for approval + final isApproved = await askUser(); + + if (isApproved) { + final resumeResponse = await ai.generate( + messages: response.messages, // Pass history + toolChoice: ToolChoice.none, // Prevent immediate re-call + interruptRestart: [ + ToolRequestPart( + toolRequest: interrupt.toolRequest, + metadata: { + ...?interrupt.metadata, + 'tool-approved': true + }, + ), + ], + ); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_openai.md b/.agents/skills/developing-genkit-dart/references/genkit_openai.md new file mode 100644 index 0000000..42344db --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_openai.md @@ -0,0 +1,54 @@ +# Genkit OpenAI Plugin (`genkit_openai`) + +OpenAI-compatible API plugin for Genkit Dart. Supports OpenAI models and other compatible APIs (xAI, DeepSeek, Together AI, Groq, etc.). + +## Basic Usage + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_openai/genkit_openai.dart'; + +void main() async { + final ai = Genkit(plugins: [ + openAI(apiKey: Platform.environment['OPENAI_API_KEY']), + ]); + + final response = await ai.generate( + model: openAI.model('gpt-4o'), + prompt: 'Tell me a joke.', + ); +} +``` + +## Options + +`OpenAIOptions` allows configuring sampling temperature, nucleus sampling, token generation, seed, etc: +`config: OpenAIOptions(temperature: 0.7, maxTokens: 100)` + +## Groq API override + +Specify custom `baseUrl` and custom models to integrate with third-party providers. + +```dart +final ai = Genkit(plugins: [ + openAI( + apiKey: Platform.environment['GROQ_API_KEY'], + baseUrl: 'https://api.groq.com/openai/v1', + models: [ + CustomModelDefinition( + name: 'llama-3.3-70b-versatile', + info: ModelInfo( + label: 'Llama 3.3 70B', + supports: {'multiturn': true, 'tools': true, 'systemRole': true}, + ), + ), + ], + ), +]); + +final response = await ai.generate( + model: openAI.model('llama-3.3-70b-versatile'), + prompt: 'Hello!', +); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_shelf.md b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md new file mode 100644 index 0000000..1887f80 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md @@ -0,0 +1,59 @@ +# Genkit Shelf Plugin (`genkit_shelf`) + +Shelf integration for Genkit Dart, used to serve Genkit Flows. + +## Standalone Server +Serve Genkit Flows easily on an isolated HTTP server using `startFlowServer`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + await startFlowServer( + flows: [flow], + port: 8080, + ); +} +``` + +## Existing Shelf Application +Mount Genkit Flow endpoints directly to an existing Shelf `Router` using `shelfHandler`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as io; +import 'package:shelf_router/shelf_router.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + final router = Router(); + + // Mount the flow handler at a specific path + router.post('/myFlow', shelfHandler(flow)); + + // Start the server + await io.serve(router.call, 'localhost', 8080); +} +``` + +Access deployed flows using genkit client libraries (from Dart or JS). diff --git a/.agents/skills/developing-genkit-dart/references/schemantic.md b/.agents/skills/developing-genkit-dart/references/schemantic.md new file mode 100644 index 0000000..45939b2 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/schemantic.md @@ -0,0 +1,137 @@ +# Schemantic + +Schemantic is a general-purpose Dart library used for defining strongly typed data classes that automatically bind to reusable runtime JSON schemas. It is standard for the `genkit-dart` framework but works independently as well. + +## Core Concepts + +Always use `schemantic` when strongly typed JSON parsing or programmatic schema validation is required. + +- Annotate your abstract classes with `@Schema()`. +- Use the `$` prefix for abstract schema class names (e.g., `abstract class $User`). +- Always run `dart run build_runner build` to generate the `.g.dart` schema files. + +## Installation + +Add dependencies: + +```bash +dart pub add schemantic +``` + +## Basic Usage + +1. **Defining a schema:** + +```dart +import 'package:schemantic/schemantic.dart'; + +part 'my_file.g.dart'; // Must match the filename + +@Schema() +abstract class $MyObj { + String get name; + $MySubObj get subObj; +} + +@Schema() +abstract class $MySubObj { + String get foo; +} +``` + +2. **Using the Generated Class:** + +The builder creates a concrete class `MyObj` (no `$`) with a factory constructor (`MyObj.fromJson`) and a regular constructor. + +```dart +// Creating an instance +final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar')); + +// Serializing to JSON +print(obj.toJson()); + +// Parsing from JSON +final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}}); +``` + +3. **Accessing Schemas at Runtime:** + +The generated data classes have a static `$schema` field (of type `SchemanticType`) which can be used to pass the definition into functions or to extract the raw JSON schema. + +```dart +// Access JSON schema +final schema = MyObj.$schema.jsonSchema; +print(schema.toJson()); + +// Validate arbitrary JSON at runtime +final validationErrors = await schema.validate({'invalid': 'data'}); +``` + +## Primitive Schemas + +When a full data class is not required, Schemantic provides functions to create schemas dynamically. + +```dart +final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0); +final nameSchema = SchemanticType.string(minLength: 2); +final nothingSchema = SchemanticType.voidSchema(); +final anySchema = SchemanticType.dynamicSchema(); + +final userSchema = SchemanticType.map(.string(), .integer()); // Map +final tagsSchema = SchemanticType.list(.string()); // List +``` + +## Union Types (AnyOf) + +To allow a field to accept multiple types, use `@AnyOf`. + +```dart +@Schema() +abstract class $Poly { + @AnyOf([int, String, $MyObj]) + Object? get id; +} +``` + +Schemantic generates a specific helper class (e.g., `PolyId`) to handle the values: + +```dart +final poly1 = Poly(id: PolyId.int(123)); +final poly2 = Poly(id: PolyId.string('abc')); +``` + +## Field Annotations + +You can use specialized annotations for more validation boundaries: + +```dart +@Schema() +abstract class $User { + @IntegerField( + name: 'years_old', // Change JSON key + description: 'Age of the user', + minimum: 0, + defaultValue: 18, + ) + int? get age; + + @StringField( + minLength: 2, + enumValues: ['user', 'admin'], + ) + String get role; +} +``` + +## Recursive Schemas + +For recursive structures (like trees), must use `useRefs: true` inside the generated jsonSchema property. You define it normally: + +```dart +@Schema() +abstract class $Node { + String get id; + List<$Node>? get children; +} +``` +*Note*: `Node.$schema.jsonSchema(useRefs: true)` generates schemas with JSON Schema `$ref`. \ No newline at end of file diff --git a/.agents/skills/developing-genkit-go/SKILL.md b/.agents/skills/developing-genkit-go/SKILL.md new file mode 100644 index 0000000..5e49c35 --- /dev/null +++ b/.agents/skills/developing-genkit-go/SKILL.md @@ -0,0 +1,97 @@ +--- +name: developing-genkit-go +description: Develop AI-powered applications using Genkit in Go. Use when the user asks to build AI features, agents, flows, or tools in Go using Genkit, or when working with Genkit Go code involving generation, prompts, streaming, tool calling, or model providers. +metadata: + genkit-managed: true +--- + +# Genkit Go + +Genkit Go is an AI SDK for Go that provides generation, structured output, streaming, tool calling, prompts, and flows with a unified interface across model providers. + +## Hello World + +```go +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/genkit-ai/genkit/go/ai" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" + "github.com/genkit-ai/genkit/go/plugins/server" +) + +func main() { + ctx := context.Background() + g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) + + genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }) + + mux := http.NewServeMux() + for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) + } + log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +} +``` + +## Core Features + +Load the appropriate reference based on what you need: + +| Feature | Reference | When to load | +| --- | --- | --- | +| Initialization | [references/getting-started.md](references/getting-started.md) | Setting up `genkit.Init`, plugins, the `*Genkit` instance pattern | +| Generation | [references/generation.md](references/generation.md) | `Generate`, `GenerateText`, `GenerateData`, streaming, output formats | +| Prompts | [references/prompts.md](references/prompts.md) | `DefinePrompt`, `DefineDataPrompt`, `.prompt` files, schemas | +| Tools | [references/tools.md](references/tools.md) | `DefineTool`, tool interrupts, `RestartWith`/`RespondWith` | +| Flows & HTTP | [references/flows-and-http.md](references/flows-and-http.md) | `DefineFlow`, `DefineStreamingFlow`, `genkit.Handler`, HTTP serving | +| Model Providers | [references/providers.md](references/providers.md) | Google AI, Vertex AI, Anthropic, OpenAI-compatible, Ollama setup | + +## Genkit CLI + +Check if installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Key commands:** + +```bash +# Start app with Developer UI (tracing, flow testing) at http://localhost:4000 +genkit start -- go run . +genkit start -o -- go run . # also opens browser + +# Run a flow directly from the CLI +genkit flow:run myFlow '{"data": "input"}' +genkit flow:run myFlow '{"data": "input"}' --stream # with streaming +genkit flow:run myFlow '{"data": "input"}' --wait # wait for completion + +# Look up Genkit documentation +genkit docs:search "streaming" go +genkit docs:list go +genkit docs:read go/flows.md +``` + +See [references/getting-started.md](references/getting-started.md) for full CLI and Developer UI details. + +## Key Guidance + +- **Pass `g` explicitly.** The `*Genkit` instance returned by `genkit.Init` is the central registry. Pass it to all Genkit functions rather than storing it as a global. This is a core pattern throughout the SDK. +- **Wrap AI logic in flows.** Flows give you tracing, observability, HTTP deployment via `genkit.Handler`, and the ability to test from the Developer UI and CLI. Any generation call worth keeping should live in a flow. +- **Use `jsonschema:"description=..."` struct tags on output types.** The model uses these descriptions to understand what each field should contain. Without them, structured output quality drops significantly. +- **Write good tool descriptions.** The model decides which tools to call based on their description string. Vague descriptions lead to missed or incorrect tool calls. +- **Use `.prompt` files for complex prompts.** They separate prompt content from Go code, support Handlebars templating, and can be iterated on without recompilation. Code-defined prompts are better for simple, single-line cases. +- **Look up the latest model IDs.** Model names change frequently. Check provider documentation for current model IDs rather than relying on hardcoded names. See [references/providers.md](references/providers.md). diff --git a/.agents/skills/developing-genkit-go/references/flows-and-http.md b/.agents/skills/developing-genkit-go/references/flows-and-http.md new file mode 100644 index 0000000..92f99a2 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/flows-and-http.md @@ -0,0 +1,183 @@ +# Flows & HTTP + +## DefineFlow + +Wrap AI logic in a flow for observability, tracing, and HTTP deployment. + +```go +jokeFlow := genkit.DefineFlow(g, "jokeFlow", + func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }, +) +``` + +### Running a Flow Directly + +```go +result, err := jokeFlow.Run(ctx, "cats") +``` + +## DefineStreamingFlow + +Flows that stream chunks back to the caller. Two common patterns: + +### Pattern 1: Passthrough Streaming + +Pass the stream callback directly through to `WithStreaming`. The callback type is `ai.ModelStreamCallback` = `func(context.Context, *ai.ModelResponseChunk) error`: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk ai.ModelStreamCallback) (string, error) { + resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ai.WithStreaming(sendChunk), // passthrough + ) + if err != nil { + return "", err + } + return resp.Text(), nil + }, +) +``` + +### Pattern 2: Manual String Streaming + +Use `core.StreamCallback[string]` to stream extracted text: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk core.StreamCallback[string]) (string, error) { + stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ) + for result, err := range stream { + if err != nil { + return "", err + } + if result.Done { + return result.Response.Text(), nil + } + sendChunk(ctx, result.Chunk.Text()) + } + return "", nil + }, +) +``` + +### Typed Streaming Flows + +Use `core.StreamCallback[T]` with `GenerateDataStream` for typed chunks: + +```go +genkit.DefineStreamingFlow(g, "structuredStream", + func(ctx context.Context, input JokeRequest, sendChunk core.StreamCallback[*Joke]) (*Joke, error) { + stream := genkit.GenerateDataStream[*Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", input.Topic), + ) + for result, err := range stream { + if err != nil { return nil, err } + if result.Done { return result.Output, nil } + sendChunk(ctx, result.Chunk) + } + return nil, nil + }, +) +``` + +## Named Sub-Steps + +Use `core.Run` inside a flow for traced sub-steps: + +```go +genkit.DefineFlow(g, "pipeline", + func(ctx context.Context, input string) (string, error) { + subject, err := core.Run(ctx, "extract-subject", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Extract the subject from: %s", input), + ) + }) + if err != nil { return "", err } + + joke, err := core.Run(ctx, "generate-joke", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Tell me a joke about %s", subject), + ) + }) + return joke, err + }, +) +``` + +## HTTP Handlers + +### genkit.Handler + +Convert any flow into an `http.HandlerFunc`: + +```go +mux := http.NewServeMux() +for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) +} +log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +``` + +### Request/Response Format + +**Non-streaming request:** +```bash +curl -X POST http://localhost:8080/jokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Response: `{"result": "Why did the banana go to the doctor?..."}` + +**Streaming request:** +```bash +curl -N -X POST http://localhost:8080/streamingJokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Streaming responses use Server-Sent Events (SSE) format. + +### genkit.HandlerFunc + +For frameworks that expect error-returning handlers: + +```go +handler := genkit.HandlerFunc(myFlow) +// handler is func(http.ResponseWriter, *http.Request) error +``` + +### Context Providers + +Inject request context (e.g., auth headers) into flow execution: + +```go +mux.HandleFunc("POST /myFlow", genkit.Handler(myFlow, + genkit.WithContextProviders(func(ctx context.Context, rd core.RequestData) (api.ActionContext, error) { + // rd.Headers contains HTTP headers + return api.ActionContext{"userId": rd.Headers.Get("X-User-Id")}, nil + }), +)) +``` + +### ListFlows + +Get all registered flows for dynamic route setup: + +```go +flows := genkit.ListFlows(g) // []api.Action +for _, f := range flows { + fmt.Println(f.Name()) +} +``` diff --git a/.agents/skills/developing-genkit-go/references/generation.md b/.agents/skills/developing-genkit-go/references/generation.md new file mode 100644 index 0000000..5934575 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/generation.md @@ -0,0 +1,176 @@ +# Generation + +## GenerateText + +Simplest form. Returns a string. + +```go +text, err := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +``` + +## Generate + +Returns a full `*ModelResponse` with metadata, usage stats, and history. + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithSystem("You are a helpful assistant."), + ai.WithPrompt("Explain %s", topic), +) +fmt.Println(resp.Text()) // concatenated text +fmt.Println(resp.FinishReason) // ai.FinishReasonStop, etc. +fmt.Println(resp.Usage) // token counts +``` + +## GenerateData (Structured Output) + +Returns a typed Go value parsed from the model's JSON output. + +```go +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup of the joke"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +joke, resp, err := genkit.GenerateData[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +// joke is *Joke, resp is *ModelResponse +``` + +## Streaming + +### GenerateStream + +Returns an iterator. Each value has `.Done`, `.Chunk`, and `.Response`. + +```go +stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long story about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalText := result.Response.Text() + break + } + fmt.Print(result.Chunk.Text()) // incremental text +} +``` + +### GenerateDataStream (Structured Streaming) + +Streams typed partial objects as they arrive. + +```go +stream := genkit.GenerateDataStream[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalJoke := result.Output // *Joke + break + } + partialJoke := result.Chunk // *Joke (partial) +} +``` + +### Callback-Based Streaming + +Use `ai.WithStreaming` with `Generate` for callback-style streaming. The callback receives `*ai.ModelResponseChunk`: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a story"), + ai.WithStreaming(func(ctx context.Context, chunk *ai.ModelResponseChunk) error { + fmt.Print(chunk.Text()) // extract text from chunk + return nil + }), +) +// resp contains the final complete response +``` + +## Common Options + +```go +// Model selection +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)) // model reference +ai.WithModelName("googleai/gemini-flash-latest") // by name string + +// Content +ai.WithPrompt("Tell me about %s", topic) // user message (supports fmt verbs) +ai.WithSystem("You are a pirate.") // system instructions +ai.WithMessages(msg1, msg2) // conversation history +ai.WithDocs(doc1, doc2) // context documents +ai.WithTextDocs("context 1", "context 2") // context as strings + +// Model config (provider-specific) +ai.WithConfig(map[string]any{"temperature": 0.7}) +``` + +## Output Formats + +Control how the model structures its output. + +### By Go Type + +```go +// Automatically uses JSON format and instructs model to match the type +ai.WithOutputType(MyStruct{}) +``` + +### By Format String + +```go +ai.WithOutputFormat(ai.OutputFormatJSON) // single JSON object +ai.WithOutputFormat(ai.OutputFormatJSONL) // JSON Lines (one object per line) +ai.WithOutputFormat(ai.OutputFormatArray) // JSON array +ai.WithOutputFormat(ai.OutputFormatEnum) // constrained enum value +ai.WithOutputFormat(ai.OutputFormatText) // plain text (default) +``` + +### Enum Output + +```go +type Color string +const ( + Red Color = "red" + Green Color = "green" + Blue Color = "blue" +) + +text, err := genkit.GenerateText(ctx, g, + ai.WithPrompt("What color is the sky?"), + ai.WithOutputEnums(Red, Green, Blue), +) +``` + +### Custom Output Instructions + +```go +ai.WithOutputInstructions("Return a JSON object with fields: name (string), age (number)") +``` + +### Combining Format + Schema + +```go +// JSONL with a typed schema (useful for streaming lists) +genkit.DefinePrompt(g, "characters", + ai.WithPrompt("Generate 5 story characters"), + ai.WithOutputType([]StoryCharacter{}), + ai.WithOutputFormat(ai.OutputFormatJSONL), +) +``` diff --git a/.agents/skills/developing-genkit-go/references/getting-started.md b/.agents/skills/developing-genkit-go/references/getting-started.md new file mode 100644 index 0000000..950b616 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/getting-started.md @@ -0,0 +1,142 @@ +# Getting Started + +## Project Setup + +```bash +mkdir my-genkit-app && cd my-genkit-app +go mod init my-genkit-app +go get github.com/genkit-ai/genkit/go@latest +``` + +Add provider plugin(s) for the models you want to use: +```bash +go get github.com/genkit-ai/genkit/go/plugins/googlegenai # Google AI / Vertex AI +go get github.com/genkit-ai/genkit/go/plugins/anthropic # Anthropic Claude +go get github.com/genkit-ai/genkit/go/plugins/compat_oai # OpenAI-compatible +go get github.com/genkit-ai/genkit/go/plugins/ollama # Ollama (local) +``` + +After writing your code, run `go mod tidy` to resolve all dependencies. + +## Initialization + +Every Genkit app starts with `genkit.Init`, which returns a `*Genkit` instance: + +```go +import ( + "context" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" +) + +ctx := context.Background() +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), +) +``` + +### The `*Genkit` Instance + +The `*Genkit` value `g` is the central registry. Pass it to every Genkit function: + +```go +// Defining resources +genkit.DefineFlow(g, "myFlow", ...) +genkit.DefineTool(g, "myTool", ...) +genkit.DefinePrompt(g, "myPrompt", ...) + +// Generating content +genkit.GenerateText(ctx, g, ...) +genkit.Generate(ctx, g, ...) +``` + +Do not store `g` in a global variable. Pass it explicitly through your call chain. + +### Init Options + +```go +g := genkit.Init(ctx, + // Register one or more plugins + genkit.WithPlugins(&googlegenai.GoogleAI{}, &anthropic.Anthropic{}), + + // Set a default model (used when no model is specified) + genkit.WithDefaultModel("googleai/gemini-flash-latest"), + + // Set directory for .prompt files (default: "prompts") + genkit.WithPromptDir("my-prompts"), + + // Or embed prompts using Go's embed package + // genkit.WithPromptFS(promptsFS), +) +``` + +### Embedding Prompts + +Use `go:embed` to bundle `.prompt` files into the binary: + +```go +//go:embed prompts +var promptsFS embed.FS + +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), + genkit.WithPromptFS(promptsFS), +) +``` + +## Genkit CLI + +The Genkit CLI provides a local Developer UI for running flows, tracing executions, and inspecting model interactions. + +**Install:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Verify:** +```bash +genkit --version +``` + +### Developer UI + +Start your app with the Developer UI attached: + +```bash +genkit start -- go run . +``` + +This launches: +- Your app (with tracing enabled) +- The Developer UI at `http://localhost:4000` +- A telemetry API at `http://localhost:4033` + +Add `-o` to auto-open the UI in your browser: +```bash +genkit start -o -- go run . +``` + +The Developer UI lets you: +- Run and test flows interactively +- View traces for each generation call (inputs, outputs, latency, token usage) +- Inspect prompt rendering and tool calls +- Debug multi-step flows with per-step trace data + +### Without the CLI + +Set `GENKIT_ENV=dev` to enable the reflection API without the CLI: + +```bash +GENKIT_ENV=dev go run . +``` + +## Import Paths + +```go +import ( + "github.com/genkit-ai/genkit/go/genkit" // Core: Init, Generate*, DefineFlow, etc. + "github.com/genkit-ai/genkit/go/ai" // Types: WithModel, WithPrompt, Message, Part, etc. + "github.com/genkit-ai/genkit/go/core" // Low-level: Run (sub-steps), Flow types + "github.com/genkit-ai/genkit/go/plugins/server" // server.Start for HTTP +) +``` diff --git a/.agents/skills/developing-genkit-go/references/prompts.md b/.agents/skills/developing-genkit-go/references/prompts.md new file mode 100644 index 0000000..610d563 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/prompts.md @@ -0,0 +1,256 @@ +# Prompts + +## DefinePrompt + +Define a reusable prompt in code with a default model and template. + +```go +jokePrompt := genkit.DefinePrompt(g, "joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithInputType(JokeRequest{Topic: "example"}), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +fmt.Println(resp.Text()) +``` + +### ExecuteStream + +```go +stream := jokePrompt.ExecuteStream(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +for result, err := range stream { + if err != nil { return err } + if result.Done { break } + fmt.Print(result.Chunk.Text()) +} +``` + +### Override Options at Execution + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), + ai.WithModelName("googleai/gemini-pro-latest"), // override model + ai.WithConfig(map[string]any{"temperature": 0.9}), + ai.WithTools(myTool), +) +``` + +## DefineDataPrompt (Typed Input/Output) + +Strongly-typed prompts with Go generics. + +```go +type JokeRequest struct { + Topic string `json:"topic"` +} + +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +jokePrompt := genkit.DefineDataPrompt[JokeRequest, *Joke](g, "structured-joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute (typed) + +```go +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +// joke is *Joke, resp is *ModelResponse +``` + +### ExecuteStream (typed) + +```go +stream := jokePrompt.ExecuteStream(ctx, JokeRequest{Topic: "cats"}) +for result, err := range stream { + if err != nil { return err } + if result.Done { + finalJoke := result.Output // *Joke + break + } + fmt.Print(result.Chunk) // partial *Joke +} +``` + +## .prompt Files (Dotprompt) + +Define prompts in separate files with YAML frontmatter and Handlebars templates. + +### Basic .prompt File + +`prompts/joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string +--- +Tell me a joke about {{topic}}. +``` + +### Load and Use + +```go +// LookupPrompt returns Prompt (untyped: map[string]any input, string output) +jokePrompt := genkit.LookupPrompt(g, "joke") +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +``` + +### Typed .prompt File + +`prompts/structured-joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +config: + thinkingConfig: + thinkingBudget: 0 +input: + schema: JokeRequest +output: + format: json + schema: Joke +--- +Tell me a joke about {{topic}}. +``` + +Register Go types so the .prompt file can reference them by name: +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) + +jokePrompt := genkit.LookupDataPrompt[JokeRequest, *Joke](g, "structured-joke") +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +``` + +### LoadPrompt (Explicit Path) + +```go +prompt := genkit.LoadPrompt(g, "./prompts/countries.prompt", "countries") +resp, err := prompt.Execute(ctx) +``` + +### .prompt File Features + +**Multi-message prompts with roles:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + question: string +--- +{{ role "system" }} +You are a helpful assistant. + +{{ role "user" }} +{{question}} +``` + +**Media in prompts:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + videoUrl: string + contentType: string +--- +{{ role "user" }} +Summarize this video: +{{media url=videoUrl contentType=contentType}} +``` + +**Conditionals and loops:** +``` +--- +input: + schema: + topic: string + dietaryRestrictions?(array): string +--- +Write a recipe about {{topic}}. +{{#if dietaryRestrictions}} +Dietary restrictions: {{#each dietaryRestrictions}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}. +{{/if}} +``` + +**Inline schema in .prompt file:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string + style?: string +output: + format: json + schema: + title: string + body: string + tags(array): string +--- +Write an article about {{topic}}. +{{#if style}}Write in a {{style}} style.{{/if}} +``` + +## Schemas + +### DefineSchemaFor (from Go type) + +Registers a Go struct as a named schema for use in `.prompt` files. + +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) +``` + +The schema name matches the Go type name. Use `jsonschema` struct tags for metadata: + +```go +type Recipe struct { + Title string `json:"title" jsonschema:"description=The recipe title"` + Difficulty string `json:"difficulty" jsonschema:"enum=easy,enum=medium,enum=hard"` + Ingredients []Ingredient `json:"ingredients"` + Steps []string `json:"steps"` +} + +type Ingredient struct { + Name string `json:"name"` + Amount float64 `json:"amount"` + Unit string `json:"unit"` +} +``` + +### DefineSchema (manual JSON Schema) + +```go +genkit.DefineSchema(g, "Recipe", map[string]any{ + "type": "object", + "properties": map[string]any{ + "title": map[string]any{"type": "string"}, + "ingredients": map[string]any{ + "type": "array", + "items": map[string]any{"type": "object"}, + }, + }, + "required": []string{"title", "ingredients"}, +}) +``` diff --git a/.agents/skills/developing-genkit-go/references/providers.md b/.agents/skills/developing-genkit-go/references/providers.md new file mode 100644 index 0000000..dbf137c --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/providers.md @@ -0,0 +1,157 @@ +# Model Providers + +## Google AI (Gemini) + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) +``` + +**Env var:** `GEMINI_API_KEY` or `GOOGLE_API_KEY` + +Model names follow the format `googleai/`. Look up the latest model IDs at https://ai.google.dev/gemini-api/docs/models. + +```go +// By name string +ai.WithModelName("googleai/gemini-flash-latest") + +// Model ref with provider-specific config +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", &genai.GenerateContentConfig{ + ThinkingConfig: &genai.ThinkingConfig{ + ThinkingBudget: genai.Ptr[int32](0), // disable thinking + }, +})) + +// Lookup a model instance +m := googlegenai.GoogleAIModel(g, "gemini-flash-latest") +``` + +## Vertex AI + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.VertexAI{})) +``` + +**Env vars:** `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION` (or `GOOGLE_CLOUD_REGION`) + +Uses Application Default Credentials (`gcloud auth application-default login`). + +Model names follow the format `vertexai/`. Same model IDs as Google AI. + +```go +ai.WithModelName("vertexai/gemini-flash-latest") +``` + +## Anthropic (Claude) + +```go +import ( + "github.com/anthropics/anthropic-sdk-go" // Anthropic SDK types + ant "github.com/genkit-ai/genkit/go/plugins/anthropic" // Genkit plugin +) + +g := genkit.Init(ctx, genkit.WithPlugins(&ant.Anthropic{})) +``` + +**Env var:** `ANTHROPIC_API_KEY` + +Model names follow the format `anthropic/`. Look up the latest model IDs at https://docs.anthropic.com/en/docs/about-claude/models. + +```go +// By name +ai.WithModelName("anthropic/claude-sonnet-4-6") + +// With provider-specific config (uses Anthropic SDK types via ai.WithConfig) +ai.WithConfig(&anthropic.MessageNewParams{ + Temperature: anthropic.Float(1.0), + MaxTokens: *anthropic.IntPtr(2000), + Thinking: anthropic.ThinkingConfigParamUnion{ + OfEnabled: &anthropic.ThinkingConfigEnabledParam{ + BudgetTokens: *anthropic.IntPtr(1024), + }, + }, +}) +``` + +## OpenAI-Compatible (compat_oai) + +Works with any OpenAI-compatible API: OpenAI, DeepSeek, xAI, etc. + +```go +import "github.com/genkit-ai/genkit/go/plugins/compat_oai" + +openaiPlugin := &compat_oai.OpenAICompatible{ + Provider: "openai", // unique identifier + APIKey: os.Getenv("OPENAI_API_KEY"), + // BaseURL: "https://custom-endpoint/v1", // for non-OpenAI providers +} +g := genkit.Init(ctx, genkit.WithPlugins(openaiPlugin)) +``` + +Define models explicitly (not auto-discovered): + +```go +model := openaiPlugin.DefineModel("openai", "gpt-4o", compat_oai.ModelOptions{}) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Ollama (Local Models) + +```go +import "github.com/genkit-ai/genkit/go/plugins/ollama" + +ollamaPlugin := &ollama.Ollama{ + ServerAddress: "http://localhost:11434", + Timeout: 60, // seconds +} +g := genkit.Init(ctx, genkit.WithPlugins(ollamaPlugin)) +``` + +Define models explicitly: + +```go +model := ollamaPlugin.DefineModel(g, + ollama.ModelDefinition{ + Name: "llama3.1", + Type: "chat", // or "generate" + }, + nil, // optional *ModelOptions +) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Multiple Providers + +Register multiple plugins in a single Genkit instance: + +```go +g := genkit.Init(ctx, + genkit.WithPlugins( + &googlegenai.GoogleAI{}, + &ant.Anthropic{}, + ), + genkit.WithDefaultModel("googleai/gemini-flash-latest"), +) + +// Use different models per call +text1, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Hello from Gemini"), +) + +text2, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("anthropic/claude-sonnet-4-6"), + ai.WithPrompt("Hello from Claude"), +) +``` diff --git a/.agents/skills/developing-genkit-go/references/tools.md b/.agents/skills/developing-genkit-go/references/tools.md new file mode 100644 index 0000000..d4a37de --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/tools.md @@ -0,0 +1,178 @@ +# Tools + +## DefineTool + +Define a tool the model can call during generation. + +```go +type WeatherInput struct { + Location string `json:"location" jsonschema:"description=City name"` +} + +type WeatherOutput struct { + Temperature float64 `json:"temperature"` + Conditions string `json:"conditions"` +} + +weatherTool := genkit.DefineTool(g, "getWeather", + "Gets the current weather for a location.", + func(ctx *ai.ToolContext, input WeatherInput) (WeatherOutput, error) { + // Call your weather API + return WeatherOutput{Temperature: 72, Conditions: "sunny"}, nil + }, +) +``` + +## Using Tools in Generation + +Pass tools to `Generate`, `GenerateText`, or prompts: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("What's the weather in San Francisco?"), + ai.WithTools(weatherTool), +) +// The model calls the tool automatically and incorporates the result +fmt.Println(resp.Text()) +``` + +### Tool Choice + +```go +ai.WithToolChoice(ai.ToolChoiceAuto) // model decides (default) +ai.WithToolChoice(ai.ToolChoiceRequired) // model must use a tool +ai.WithToolChoice(ai.ToolChoiceNone) // model cannot use tools +``` + +### Max Turns + +Limit how many tool-call round trips the model can make: + +```go +ai.WithMaxTurns(3) // default is 5 +``` + +## DefineMultipartTool + +Tools that return both structured output and media content: + +```go +screenshotTool := genkit.DefineMultipartTool(g, "screenshot", + "Takes a screenshot of the current page", + func(ctx *ai.ToolContext, input any) (*ai.MultipartToolResponse, error) { + return &ai.MultipartToolResponse{ + Output: map[string]any{"success": true}, + Content: []*ai.Part{ai.NewMediaPart("image/png", base64Data)}, + }, nil + }, +) +``` + +## Tool Interrupts + +Pause tool execution to request human input before continuing. + +### Interrupting + +```go +type TransferInput struct { + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` +} + +type TransferOutput struct { + Status string `json:"status"` + Message string `json:"message"` + Balance float64 `json:"balance"` +} + +type TransferInterrupt struct { + Reason string `json:"reason"` + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` + Balance float64 `json:"balance"` +} + +transferTool := genkit.DefineTool(g, "transferMoney", + "Transfers money to another account.", + func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if input.Amount > accountBalance { + return TransferOutput{}, ai.InterruptWith(ctx, TransferInterrupt{ + Reason: "insufficient_balance", + ToAccount: input.ToAccount, + Amount: input.Amount, + Balance: accountBalance, + }) + } + // Process transfer... + return TransferOutput{Status: "success", Balance: newBalance}, nil + }, +) +``` + +### Handling Interrupts + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithTools(transferTool), + ai.WithPrompt(userRequest), +) + +for resp.FinishReason == ai.FinishReasonInterrupted { + var restarts, responses []*ai.Part + + for _, interrupt := range resp.Interrupts() { + meta, ok := ai.InterruptAs[TransferInterrupt](interrupt) + if !ok { + continue + } + + switch meta.Reason { + case "insufficient_balance": + // RestartWith: re-execute the tool with adjusted input + part, err := transferTool.RestartWith(interrupt, + ai.WithNewInput(TransferInput{ + ToAccount: meta.ToAccount, + Amount: meta.Balance, // transfer what's available + }), + ) + if err != nil { return err } + restarts = append(restarts, part) + + case "confirm_large": + // RespondWith: provide a response directly without re-executing + part, err := transferTool.RespondWith(interrupt, + TransferOutput{Status: "cancelled", Message: "User declined"}, + ) + if err != nil { return err } + responses = append(responses, part) + } + } + + // Continue generation with the resolved interrupts + resp, err = genkit.Generate(ctx, g, + ai.WithMessages(resp.History()...), + ai.WithTools(transferTool), + ai.WithToolRestarts(restarts...), + ai.WithToolResponses(responses...), + ) + if err != nil { return err } +} +``` + +### Checking Resume State + +Inside a tool function, check if the tool is being resumed from an interrupt: + +```go +func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if ctx.IsResumed() { + // This is a resumed call after an interrupt + original, ok := ai.OriginalInputAs[TransferInput](ctx) + // original contains the input from the first call + } + // ... +} +``` diff --git a/.agents/skills/developing-genkit-js/SKILL.md b/.agents/skills/developing-genkit-js/SKILL.md new file mode 100644 index 0000000..d8e1e76 --- /dev/null +++ b/.agents/skills/developing-genkit-js/SKILL.md @@ -0,0 +1,112 @@ +--- +name: developing-genkit-js +description: Develop AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems. +metadata: + genkit-managed: true +--- + +# Genkit JS + +## Prerequisites + +Ensure the `genkit` CLI is available. +- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0** +- If not found or if an older version (1.x < 1.29.0) is present, install/upgrade it: `npm install -g genkit-cli@^1.29.0`. + +**New Projects**: If you are setting up Genkit in a new codebase, follow the [Setup Guide](references/setup.md). + +## Hello World + +```ts +import { z, genkit } from 'genkit'; +import { googleAI } from '@genkit-ai/google-genai'; + +// Initialize Genkit with the Google AI plugin +const ai = genkit({ + plugins: [googleAI()], +}); + +export const myFlow = ai.defineFlow({ + name: 'myFlow', + inputSchema: z.string().default('AI'), + outputSchema: z.string(), +}, async (subject) => { + const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: `Tell me a joke about ${subject}`, + }); + return response.text; +}); +``` + +## Critical: Do Not Trust Internal Knowledge + +Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended: + +```sh +genkit docs:read js/get-started.md +genkit docs:read js/flows.md +``` + +See [Common Errors](references/common-errors.md) for a list of deprecated APIs (e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x replacements. + +**ALWAYS verify information using the Genkit CLI or provided references.** + +## Error Troubleshooting Protocol + +**When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):** + +1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md) +2. Identify if the error matches a known pattern +3. Apply the documented solution +4. Only if not found in common-errors.md, then consult other sources (e.g. `genkit docs:search`) + +**DO NOT:** +- Attempt fixes based on assumptions or internal knowledge +- Skip reading common-errors.md "because you think you know the fix" +- Rely on patterns from pre-1.0 Genkit + +**This protocol is non-negotiable for error handling.** + +## Development Workflow + +1. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.). + - If the user does not specify a provider, default to **Google AI**. + - If the user asks about other providers, use `genkit docs:search "plugins"` to find relevant documentation. +2. **Detect Framework**: Check `package.json` to identify the runtime (Next.js, Firebase, Express). + - Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or `@genkit-ai/google-cloud`. + - Adapt implementation to the specific framework's patterns. +3. **Follow Best Practices**: + - See [Best Practices](references/best-practices.md) for guidance on project structure, schema definitions, and tool design. + - **Be Minimal**: Only specify options that differ from defaults. When unsure, check docs/source. +4. **Ensure Correctness**: + - Run type checks (e.g., `npx tsc --noEmit`) after making changes. + - If type checks fail, consult [Common Errors](references/common-errors.md) before searching source code. +5. **Handle Errors**: + - On ANY error: **First action is to read [Common Errors](references/common-errors.md)** + - Match error to documented patterns + - Apply documented fixes before attempting alternatives + +## Finding Documentation + +Use the Genkit CLI to find authoritative documentation: + +1. **Search topics**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` +2. **List all docs**: `genkit docs:list` +3. **Read a guide**: `genkit docs:read ` + - Example: `genkit docs:read js/flows.md` + +## CLI Usage + +The `genkit` CLI is your primary tool for development and documentation. +- See [CLI Reference](references/docs-and-cli.md) for common tasks, workflows, and command usage. +- Use `genkit --help` for a full list of commands. + +## References + +- [Best Practices](references/best-practices.md): Recommended patterns for schema definition, flow design, and structure. +- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search, CLI tasks, and workflows. +- [Common Errors](references/common-errors.md): Critical "gotchas", migration guide, and troubleshooting. +- [Setup Guide](references/setup.md): Manual setup instructions for new projects. +- [Examples](references/examples.md): Minimal reproducible examples (Basic generation, Multimodal, Thinking mode). diff --git a/.agents/skills/developing-genkit-js/references/best-practices.md b/.agents/skills/developing-genkit-js/references/best-practices.md new file mode 100644 index 0000000..f6e4b7b --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/best-practices.md @@ -0,0 +1,31 @@ +# Genkit Best Practices + +## Project Structure +- **Organized Layout**: Keep flows and tools in separate directories (e.g., `src/flows`, `src/tools`) to maintain a clean codebase. +- **Index Exports**: Use `index.ts` files to export flows and tools, making it easier to import them into your main configuration. + +## Model Selection (Google AI) +- **Gemini Models**: If using Google AI, ALWAYS use the latest generation (`gemini-3-*` or `gemini-2.5-*`). + - **NEVER** use `gemini-2.0-*` or `gemini-1.5-*` series, as they are decommissioned and won't work. + - **Recommended**: `gemini-2.5-flash` or `gemini-3-flash-preview` for general use, `gemini-3.1-pro-preview` for complex tasks. + +## Model Selection (Other Providers) +- **Consult Documentation**: For other providers (OpenAI, Anthropic, etc.), refer to the provider's official documentation for the latest recommended model versions. + +## Schema Definition +- **Use `z` from `genkit`**: Always import `z` from the `genkit` package to ensure compatibility. + ```ts + import { z } from "genkit"; + ``` +- **Descriptive Schemas**: Use `.describe()` on Zod fields. LLMs use these descriptions to understand how to populate the fields. + +## Flow & Tool Design +- **Modularize**: Keep flows and tools in separate files/modules and import them into your main Genkit configuration. +- **Single Responsibility**: Tools should do one thing well. Complex logic should be broken down. + +## Configuration +- **Environment Variables**: Store sensitive keys (like API keys) in environment variables or `.env` files. Do not hardcode them. + +## Development +- **Use Dev Mode**: Run your app with `genkit start -- ` to enable the Developer UI. +- It is recommended to configure a watcher to auto-reload your app (e.g. `node --watch` or `tsx --watch`) diff --git a/.agents/skills/developing-genkit-js/references/common-errors.md b/.agents/skills/developing-genkit-js/references/common-errors.md new file mode 100644 index 0000000..d7162e6 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/common-errors.md @@ -0,0 +1,132 @@ +# Common Errors & Pitfalls + +## When Typecheck Fails + +**Before searching source code or docs**, check the sections below. Many type errors are caused by deprecated APIs or incorrect imports. + +## Genkit v1.x vs Pre-1.0 Migration + +Genkit v1.x introduced significant API changes. This section covers critical syntax updates. + +### Package Imports + +- **Correct (v1.x)**: Import core functionality (zod, genkit) from the main `genkit` package and plugins from their specific packages. + ```ts + import { z, genkit } from 'genkit'; + import { googleAI } from '@genkit-ai/google-genai'; + ``` + +- **Incorrect (Pre-1.0)**: Importing from `@genkit-ai/ai`, `@genkit-ai/core`, or `@genkit-ai/flow`. These packages are internal/deprecated for direct use. + ```ts + import { genkit } from "@genkit-ai/core"; // INCORRECT + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + ``` + +### Model References + +- **Correct**: Use plugin-specific model factories or string identifiers (prefaced by plugin name). + ```ts + // Using model factory (v1.x - Preferred) + await ai.generate({ model: googleAI.model('gemini-2.5-flash'), ... }); + + // Using string identifier + await ai.generate({ model: 'googleai/gemini-2.5-flash', ...}); + // Or + await ai.generate({ model: 'vertexai/gemini-2.5-flash', ...}); + ``` +- **Incorrect**: Using imported model objects directly or string identifiers without plugin name. + ```ts + await ai.generate({ model: gemini15Pro, ... }); // INCORRECT (Pre-1.0) + await ai.generate({ model: 'gemini-2.5-flash', ... }); // INCORRECT (No plugin prefix) + ``` + +### Model Selection (Gemini) + +- **Preferred**: Use `gemini-2.5-*` models for best performance and features. + ```ts + model: googleAI.model('gemini-2.5-flash') // PREFERRED + ``` +- **DEPRECATED**: `gemini-1.5-*` models are deprecated and will throw errors. + ```ts + model: googleAI.model('gemini-1.5-flash') // ERROR (Deprecated) + ``` + +### Response Access + +- **Correct (v1.x)**: Access properties directly. + ```ts + response.text; // CORRECT + response.output; // CORRECT + ``` +- **Incorrect (Pre-1.0)**: Calling as methods. + ```ts + response.text(); // INCORRECT + response.output(); // INCORRECT + ``` + +### Streaming Generation + +- **Correct (v1.x)**: Do NOT await `generateStream`. Iterate over `stream` directly. Await `response` property for final result. + ```ts + const {stream, response} = ai.generateStream(...); // NO await here + for await (const chunk of stream) { ... } // Iterate stream + const finalResponse = await response; // Await response property + ``` +- **Incorrect (Pre-1.0)**: Calling stream as a function or awaiting the generator incorrectly. + ```ts + for await (const chunk of stream()) { ... } // INCORRECT + await response(); // INCORRECT + ``` + +### Initialization + +- **Correct (v1.x)**: Instantiate `genkit`. + ```ts + const ai = genkit({ plugins: [...] }); + ``` +- **Incorrect (Pre-1.0)**: Global configuration. + ```ts + configureGenkit({ plugins: [...] }); // INCORRECT + ``` + +### Flow Definitions + +- **Correct (v1.x)**: Define flows on the `ai` instance. + ```ts + ai.defineFlow({...}, (input) => {...}); + ``` +- **Incorrect (Pre-1.0)**: Importing `defineFlow` globally. + ```ts + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + +You should never import `@genkit-ai/flow`, `@genkit-ai/ai` or `@genkit-ai/core` packages directly. + +## Zod & Schema Errors + +- **Import Source**: ALWAYS use `import { z } from "genkit"`. + - Using `zod` directly from `zod` package may cause instance mismatches or compatibility issues. +- **Supported Types**: Stick to basic types: scalar (`string`, `number`, `boolean`), `object`, and `array`. + - Avoid complex Zod features unless strictly necessary and verified. +- **Descriptions**: Always use `.describe('...')` for fields in output schemas to guide the LLM. + +## Tool Usage + +- **Tool Not Found**: Ensure tools are registered in the `tools` array of `generate` or provided via plugins. +- **MCP Tools**: Use the `ServerName:tool_name` format when referencing MCP tools. + +## Multimodal & Image Generation + +- **Missing responseModalities**: When using image generation models (like `gemini-2.5-flash-image`), you **MUST** specify the response modalities in the config. + ```ts + config: { + responseModalities: ["TEXT", "IMAGE"] + } + ``` + Failure to do so will result in errors or incorrect output format. + +## Audio & Speech Generation + +- **Raw PCM Data vs MP3**: Some providers (e.g., Google GenAI) return raw PCM data, while others (e.g., OpenAI) return MP3. + - **DO NOT assume MP3 format.** + - **DO NOT embed raw PCM in HTML audio tags.** + - **Action**: Run `genkit docs:search "speech audio"` to find provider-specific conversion steps (e.g., PCM to WAV). diff --git a/.agents/skills/developing-genkit-js/references/docs-and-cli.md b/.agents/skills/developing-genkit-js/references/docs-and-cli.md new file mode 100644 index 0000000..3561721 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/docs-and-cli.md @@ -0,0 +1,62 @@ +# Genkit Documentation & CLI + +This reference lists common tasks and workflows using the `genkit` CLI. For authoritative command details, always run `genkit --help` or `genkit --help`. + +## Prerequisites: + +Ensure that the CLI is on `genkit-cli` version >= 1.29.0. If not, or if an older version (1.x < 1.29.0) is present, update the Genkit CLI version. Alternatively, to run commands with a specific version or without global installation, prefix them with `npx -y genkit-cli@^1.29.0`. + +## Documentation + +- **Search docs**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` + - Example: `genkit docs:search "rag retrieval"` +- **Read doc**: `genkit docs:read ` + - Example: `genkit docs:read js/overview.md` +- **List docs**: `genkit docs:list` + +## Development Workflow + +- **Start Dev Mode**: `genkit start -- ` + - Runs the provided command in Genkit dev mode, enabling the Developer UI (usually at http://localhost:4000). + - **Node.js (TypeScript)**: + ```bash + genkit start -- npx tsx --watch src/index.ts + ``` + - **Next.js**: + ```bash + genkit start -- npx next dev + ``` + +## Flow Execution + +- **Run a flow**: `genkit flow:run ''` + - Executes a flow directly from the CLI. Useful for testing. + - **Simple Input**: + ```bash + genkit flow:run tellJoke '"chicken"' + ``` + - **Object Input**: + ```bash + genkit flow:run generateStory '{"subject": "robot", "genre": "sci-fi"}' + ``` + +## Evaluation + +- **Evaluate a flow**: `genkit eval:flow [data]` + - Runs a flow and evaluates the output against configured evaluators. + - **Example (Single Input)**: + ```bash + genkit eval:flow answerQuestion '[{"testCaseId": "1", "input": {"question": "What is Genkit?"}}]' + ``` + - **Example (Batch Input)**: + ```bash + genkit eval:flow answerQuestion --input inputs.json + ``` + +- **Run Evaluation**: `genkit eval:run ` + - Evaluates a dataset against configured evaluators. + - **Example**: + ```bash + genkit eval:run dataset.json --output results.json + ``` \ No newline at end of file diff --git a/.agents/skills/developing-genkit-js/references/examples.md b/.agents/skills/developing-genkit-js/references/examples.md new file mode 100644 index 0000000..2279b4e --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/examples.md @@ -0,0 +1,157 @@ +# Genkit Examples + +This reference contains minimal, reproducible examples (MREs) for common Genkit patterns. + +> **Disclaimer**: These examples use **Google AI** models (`googleAI`, `gemini-*`) for demonstration. The patterns apply to **any provider**. To use a different provider: +> 1. Search the docs for the correct plugin: `genkit docs:search "plugins"`. +> 2. Install and configure the plugin. +> 3. Swap the model reference in the code. + +## Basic Text Generation + +```ts +import { genkit } from "genkit"; +import { googleAI } from "@genkit-ai/google-genai"; + +const ai = genkit({ + plugins: [googleAI()], +}); + +const { text } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a story in a pirate accent', +}); +``` + +## Structured Output + +```ts +import { z } from 'genkit'; + +const JokeSchema = z.object({ + setup: z.string().describe('The setup of the joke'), + punchline: z.string().describe('The punchline'), +}); + +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a joke about developers.', + output: { schema: JokeSchema }, +}); + +// response.output is strongly typed +const joke = response.output; +if (joke) { + console.log(`${joke.setup} ... ${joke.punchline}`); +} +``` + +## Streaming + +```ts +const { stream, response } = ai.generateStream({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell a long story about a developer using Genkit.', +}); + +for await (const chunk of stream) { + console.log(chunk.text); +} + +// Await the final response +const finalResponse = await response; +console.log('Complete:', finalResponse.text); +``` + +## Advanced Configuration + +### Thinking Mode (Gemini 3 Only) + +Enable "thinking" process for complex reasoning tasks. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-3.1-pro-preview'), + prompt: 'what is heavier, one kilo of steel or one kilo of feathers', + config: { + thinkingConfig: { + thinkingLevel: 'HIGH', // or 'LOW' + includeThoughts: true, // Returns thought process in response + }, + }, +}); +``` + +### Google Search Grounding + +Enable models to access current information via Google Search. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'What are the top tech news stories this week?', + config: { + googleSearchRetrieval: true, + }, +}); + +// Access grounding metadata (sources) +const groundingMetadata = (response.custom as any)?.candidates?.[0]?.groundingMetadata; +if (groundingMetadata) { + console.log('Sources:', groundingMetadata.groundingChunks); +} +``` + +## Multimodal Generation + +### Image Generation / Editing + +**Critical**: You MUST set `responseModalities: ['TEXT', 'IMAGE']` when using image generation models. + +```ts +// Generate an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: "generate a picture of a unicorn wearing a space suit on the moon", +}); +// media.url contains the data URI +``` + +```ts +// Edit an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: [ + { text: "change the person's outfit to a banana costume" }, + { media: { url: "https://example.com/photo.jpg" } }, + ], +}); +``` + +### Speech Generation (TTS) + +Generate audio from text. + +```ts +import { writeFile } from 'node:fs/promises'; + +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-preview-tts'), + config: { + responseModalities: ['AUDIO'], + speechConfig: { + voiceConfig: { + prebuiltVoiceConfig: { voiceName: 'Algenib' }, // Options: 'Puck', 'Charon', 'Fenrir', etc. + }, + }, + }, + prompt: 'Genkit is an amazing library', +}); + +// The response contains raw PCM data in media.url (base64 encoded). +// CAUTION: This is NOT an MP3/WAV file. It requires conversion (e.g., PCM to WAV). +// DO NOT GUESS. Run `genkit docs:search "speech audio"` to find the correct +// conversion code for your provider. +``` diff --git a/.agents/skills/developing-genkit-js/references/setup.md b/.agents/skills/developing-genkit-js/references/setup.md new file mode 100644 index 0000000..dcbc8bd --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/setup.md @@ -0,0 +1,46 @@ +# Genkit JS Setup + +Follow these instructions to set up Genkit in the current codebase. These instructions are general-purpose and have not been written with specific codebase knowledge, so use your best judgement when following them. + +0. Tell the user "I'm going to check out your workspace and set you up to use Genkit for GenAI workflows." +1. If the current workspace is empty or is a starter template, your goal will be to create a simple image generation flow that allows someone to generate an image based on a prompt and selectable style. If the current workspace is not empty, you will create a simple example flow to help get the user started. +2. Check to see if any Genkit provider plugin (such as `@genkit-ai/google-genai` or `@genkit-ai/oai-compat` or others, may start with `genkitx-*`) is installed. + - If not, ask the user which provider they want to use. + - **For non-Google providers**: Use `genkit docs:search "plugins"` to find the correct package and installation instructions. + - If they have no preference, default to `@genkit-ai/google-genai` for a quick start. + - If this is a Next.js app, install `@genkit-ai/next` as well. +3. Search the codebase for the exact string `genkit(` (remember to escape regexes properly) which would indicate that the user has already set up Genkit in the codebase. If found, no need to set it up again, tell the user "Genkit is already configured in this app." and exit this workflow. +4. Create an `ai` directory in the primary source directory of the project (this may be e.g. `src` but is project-dependent). Adapt this path if your project uses a different structure. +5. Create `{sourceDir}/ai/genkit.ts` and populate it using the example below. DO NOT add a `next` plugin to the file, ONLY add a model provider plugin to the plugins array: + +```ts +import { genkit, z } from 'genkit'; +// Import your chosen provider plugin here. Example: +import { googleAI } from '@genkit-ai/google-genai'; + +export const ai = genkit({ + plugins: [ + googleAI(), // Add your provider plugin here + ], + model: googleAI.model('gemini-2.5-flash'), // Set your provider's model here +}); + +export { z }; +``` + +6. Create `{sourceDir}/ai/tools` and `{sourceDir}/ai/flows` directories, but leave them empty for now. +7. Create `{sourceDir}/ai/index.ts` and populate it with the following (change the import to match import aliases in `tsconfig.json` as needed): + +```ts +import './genkit.js'; +// import each created flow, tool, etc. here for use in the Genkit Dev UI +``` + +8. Add a `genkit:ui` script to `package.json` that runs `genkit start -- npx tsx --watch {sourceDir}/ai/index.ts` (or `npx genkit-cli` or `pnpm dlx` or `yarn dlx` for those package managers, if CLI is not locally installed). DO NOT try to run the script now. +9. Tell the user "Genkit is now configured and ready for use." as setup is now complete. Also remind them to set appropriate env variables (e.g. `GEMINI_API_KEY` for Google providers). Wait for the user to prompt further before creating any specific flows. + +## Next Steps & Troubleshooting + +- **Documentation**: Use the [CLI](docs-and-cli.md) to access documentation (e.g., `genkit docs:search`). +- **Building Flows**: See [examples.md](examples.md) for patterns on creating flows, adding tools, and advanced configuration. +- **Troubleshooting**: If you encounter issues during setup or initialization, check [common-errors.md](common-errors.md) for solutions. diff --git a/.agents/skills/firebase-ai-logic/SKILL.md b/.agents/skills/firebase-ai-logic/SKILL.md new file mode 100644 index 0000000..f7ec367 --- /dev/null +++ b/.agents/skills/firebase-ai-logic/SKILL.md @@ -0,0 +1,109 @@ +--- +name: firebase-ai-logic +description: Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security. +version: 1.0.0 +--- + +# Firebase AI Logic Basics + +## Overview + +Firebase AI Logic is a product of Firebase that allows developers to add gen AI to their mobile and web apps using client-side SDKs. You can call Gemini models directly from your app without managing a dedicated backend. Firebase AI Logic, which was previously known as "Vertex AI for Firebase", represents the evolution of Google's AI integration platform for mobile and web developers. + +It supports the two Gemini API providers: +- **Gemini Developer API**: It has a free tier ideal for prototyping, and pay-as-you-go for production +- **Vertex AI Gemini API**: Ideal for scale with enterprise-grade production readiness, requires Blaze plan + +Use the Gemini Developer API as a default, and only Vertex AI Gemini API if the application requires it. + +## Setup & Initialization + +### Prerequisites + +- Before starting, ensure you have **Node.js 16+** and npm installed. Install them if they aren’t already available. +- Identify the platform the user is interested in building on prior to starting: Android, iOS, Flutter or Web. +- If their platform is unsupported, Direct the user to Firebase Docs to learn how to set up AI Logic for their application (share this link with the user https://firebase.google.com/docs/ai-logic/get-started) + +### Installation + +The library is part of the standard Firebase Web SDK. + +`npm install -g firebase@latest` + +If you're in a firebase directory (with a firebase.json) the currently selected project will be marked with "current" using this command: + +`npx -y firebase-tools@latest projects:list` + +Ensure there's at least one app associated with the current project + +`npx -y firebase-tools@latest apps:list` + +Initialize AI logic SDK with the init command + +`npx -y firebase-tools@latest init # Choose AI logic` + +This will automatically enable the Gemini Developer API in the Firebase console. + +More info in [Firebase AI Logic Getting Started](https://firebase.google.com/docs/ai-logic/get-started.md.txt) + +## Core Capabilities + +### Text-Only Generation + +### Multimodal (Text + Images/Audio/Video/PDF input) + +Firebase AI Logic allows Gemini models to analyze image files directly from your app. This enables features like creating captions, answering questions about images, detecting objects, and categorizing images. Beyond images, Gemini can analyze other media types like audio, video, and PDFs by passing them as inline data with their MIME type. For files larger than 20 megabytes (which can cause HTTP 413 errors as inline data), store them in Cloud Storage for Firebase and pass their URLs to the Gemini Developer API. + +### Chat Session (Multi-turn) + +Maintain history automatically using `startChat`. + +### Streaming Responses + +To improve the user experience by showing partial results as they arrive (like a typing effect), use `generateContentStream` instead of `generateContent` for faster display of results. + +### Generate Images with Nano Banana + +- Start with Gemini for most use cases, and choose Imagen for specialized tasks where image quality and specific styles are critical. (Example: gemini-2.5-flash-image) +- Requires an upgraded Blaze pay-as-you-go billing plan. + +### Search Grounding with the built in googleSearch tool + +## Supported Platforms and Frameworks + +Supported Platforms and Frameworks include Kotlin and Java for Android, Swift for iOS, JavaScript for web apps, Dart for Flutter, and C Sharp for Unity. + +## Advanced Features + +### Structured Output (JSON) + +Enforce a specific JSON schema for the response. + +### On-Device AI (Hybrid) + +Hybrid on-device inference for web apps, where the Firebase Javascript SDK automatically checks for Gemini Nano's availability (after installation) and switches between on-device or cloud-hosted prompt execution. This requires specific steps to enable model usage in the Chrome browser, more info in the [hybrid-on-device-inference documentation](https://firebase.google.com/docs/ai-logic/hybrid-on-device-inference.md.txt). + +## Security & Production + +### App Check + +Recommended: The developer must enable Firebase App Check to prevent unauthorized clients from using their API quota. see [App-check recaptcha enterprise](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider.md.txt). + +### Remote Config + +Consider that you do not need to hardcode model names (e.g., `gemini-flash-lite-latest`). Use Firebase Remote Config to update model versions dynamically without deploying new client code. See [Changing model names remotely](https://firebase.google.com/docs/ai-logic/change-model-name-remotely.md.txt) + +## Initialization Code References + +| Language, Framework, Platform | Gemini API provider | Context URL | +| :---- | :---- | :---- | +| Web Modular API | Gemini Developer API (Developer API) | firebase://docs/ai-logic/get-started | + +**Always use the most recent version of Gemini (gemini-flash-latest) unless another model is requested by the docs or the user. DO NOT USE gemini-1.5-flash** + +## References + +[Web SDK code examples and usage patterns](references/usage_patterns_web.md) + + + diff --git a/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md new file mode 100644 index 0000000..e6435bb --- /dev/null +++ b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md @@ -0,0 +1,174 @@ +# Firebase AI Logic Basics + +## Initialization Pattern +You must initialize the ai-logic service after the main Firebase App. +```JavaScript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; + + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // ... your firebase config +}; + +const app = initializeApp(firebaseConfig); + +// Initialize the AI Logic service (defaults to Gemini Developer API) +// To set the AI provider, set the backend as the second parameter +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +const generationConfig = { + candidate_count: 1, + maxOutputTokens: 2048, + stopSequences: [], + temperature: 0.7, // Balanced: creative but focused + topP: 0.95, // Standard: allows a wide range of probable tokens + topK: 40, // Standard: considers the top 40 tokens +}; + +// Specify the config as part of creating the `GenerativeModel` instance +const model = getGenerativeModel(ai, { model: "gemini-2.5-flash-lite", generationConfig }); +``` + +## Core Capabilities +Text-Only Generation +```JavaScript +async function generateText(prompt) { + const result = await model.generateContent(prompt); + const response = await result.response; + return response.text(); +} +``` + +## Multimodal (Text + Images/Audio/Video/PDF input) +Firebase AI Logic accepts Base64 encoded data or specific file references. +```JavaScript +// Helper to convert file to base64 generic object +async function fileToGenerativePart(file) { + const base64EncodedDataPromise = new Promise((resolve) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result.split(',')[1]); + reader.readAsDataURL(file); + }); + + return { + inlineData: { + data: await base64EncodedDataPromise, + mimeType: file.type, + }, + }; +} + +async function analyzeImage(prompt, imageFile) { + const imagePart = await fileToGenerativePart(imageFile); + const result = await model.generateContent([prompt, imagePart]); + return result.response.text(); +} +``` + +## Chat Session (Multi-turn) +Maintain history automatically using startChat. +```JavaScript +const chat = model.startChat({ + history: [ + { + role: "user", + parts: [{ text: "Hello, I am a developer." }], + }, + { + role: "model", + parts: [{ text: "Great to meet you. How can I help with code?" }], + }, + ], +}); + +async function sendMessage(msg) { + const result = await chat.sendMessage(msg); + return result.response.text(); +} +``` + +## Streaming Responses +For real-time UI updates (like a typing effect). +```JavaScript +async function streamResponse(prompt) { + const result = await model.generateContentStream(prompt); + for await (const chunk of result.stream) { + const chunkText = chunk.text(); + console.log("Stream chunk:", chunkText); + // Update UI here + } +} +``` + +Generate Images with Nano Banana + +```Javascript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai"; + + +// Initialize FirebaseApp +const firebaseApp = initializeApp(firebaseConfig); + +// Initialize the Gemini Developer API backend service +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +// Create a `GenerativeModel` instance with a model that supports your use case +const model = getGenerativeModel(ai, { + model: "gemini-2.5-flash-image", + // Configure the model to respond with text and images (required) + generationConfig: { + responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE], + }, +}); + +// Provide a text prompt instructing the model to generate an image +const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.'; + +// To generate an image, call `generateContent` with the text input +const result = model.generateContent(prompt); + +// Handle the generated image +try { + const inlineDataParts = result.response.inlineDataParts(); + if (inlineDataParts?.[0]) { + const image = inlineDataParts[0].inlineData; + console.log(image.mimeType, image.data); + } +} catch (err) { + console.error('Prompt or candidate was blocked:', err); +} +``` + +## Advanced Features +Structured Output (JSON) +Enforce a specific JSON schema for the response. +```JavaScript +import { getGenerativeModel, Schema } from "firebase/ai"; +const jsonModel = getGenerativeModel(ai, { + model: "gemini-2.5-flash-lite", + generationConfig: { + responseMimeType: "application/json", + // Optional: Define a schema + schema = Schema.object({ ... }); + } +}); + +async function getJsonData(prompt) { + const result = await jsonModel.generateContent(prompt); + return JSON.parse(result.response.text()); +} +``` + +On-Device AI (Hybrid) +Automatically switch between local Gemini Nano and cloud models based on device capability. +```JavaScript +import {getGenerativeModel, InferenceMode } from "firebase/ai"; + +const hybridModel = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE }); +``` + diff --git a/.agents/skills/firebase-app-hosting-basics/SKILL.md b/.agents/skills/firebase-app-hosting-basics/SKILL.md new file mode 100644 index 0000000..4aa23b7 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/SKILL.md @@ -0,0 +1,58 @@ +--- +name: firebase-app-hosting-basics +description: Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends. +--- + +# App Hosting Basics + +## Description +This skill enables the agent to deploy and manage modern, full-stack web applications (Next.js, Angular, etc.) using Firebase App Hosting. + +**Important**: In order to use App Hosting, your Firebase project must be on the Blaze pricing plan. Direct the user to https://console.firebase.google.com/project/_/overview?purchaseBillingPlan=metered to upgrade their plan. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Deploying to App Hosting + +### Deploy from Source + +This is the recommended flow for most users. +1. Configure `firebase.json` with an `apphosting` block. + ```json + { + "apphosting": { + "backendId": "my-app-id", + "rootDir": "/", + "ignore": [ + "node_modules", + ".git", + "firebase-debug.log", + "firebase-debug.*.log", + "functions" + ] + } + } + ``` +2. Create or edit `apphosting.yaml`- see [Configuration](references/configuration.md) for more information on how to do so. +3. If the app needs safe access to sensitive keys, use `npx -y firebase-tools@latest apphosting:secrets` commands to set and grant access to secrets. +4. Run `npx -y firebase-tools@latest deploy` when you are ready to deploy. + +### Automated deployment via GitHub (CI/CD) + +Alternatively, set up a backend connected to a GitHub repository for automated deployments "git push" deployments. +This is only recommended for more advanced users, and is not required to use App Hosting. +See [CLI Commands](references/cli_commands.md) for more information on how to set this up using CLI commands. + +## Emulation + +See [Emulation](references/emulation.md) for more information on how to test your app locally using the Firebase Local Emulator Suite. diff --git a/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md new file mode 100644 index 0000000..c758c9d --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md @@ -0,0 +1,71 @@ +# App Hosting CLI Commands + +The Firebase CLI provides a comprehensive suite of commands to manage App Hosting resources. These commands are often faster and more scriptable than using the Firebase Console. + +## Initialization + +### `npx -y firebase-tools@latest init apphosting` + +- **Purpose**: Interactive command that sets up App Hosting in your local project. +Use this command only if you are able to handle interactive CLI inputs well. +Alternatively, you can manually edit `firebase.json` and `apphosting.yml`. + +- **Effect**: + - Detects your web framework. + - Creates/updates `apphosting.yaml`. + - Can optionally create a backend if one doesn't exist. + +## Backend Management + +### `npx -y firebase-tools@latest apphosting:backends:list` + +- **Purpose**: Lists all backends in the current project. + +### `npx -y firebase-tools@latest apphosting:backends:get ` + +- **Purpose**: Shows details for a specific backend. + +### `npx -y firebase-tools@latest apphosting:backends:delete ` + +- **Purpose**: Deletes a backend and its associated resources. + +### `npx -y firebase-tools@latest apphosting:rollouts:list ` + +- **Purpose**: Lists the history of rollouts for a backend. + +## Secrets Management + +App Hosting uses Cloud Secret Manager to securely handle sensitive environment variables (like API keys). + +### `npx -y firebase-tools@latest apphosting:secrets:set ` + +- **Purpose**: Creates or updates a secret in Cloud Secret Manager and makes it available to App Hosting. +- **Behavior**: Prompts for the secret value (hidden input). + +### `npx -y firebase-tools@latest apphosting:secrets:grantaccess ` + +- **Purpose**: Grants the App Hosting service account permission to access the secret. +- **Note**: Often handled automatically by `secrets:set`, but useful for debugging permission issues or granting access to existing secrets. + +## Automated deployment via GitHub (CI/CD) + +**IMPORTANT** Only use these commands if you are setting up automated deployments via GitHub. If you are managing deployments using `npx -y firebase-tools@latest deploy`, DO NOT use these commands. + +### `npx -y firebase-tools@latest apphosting:rollouts:create ` + +- **Purpose**: Manually triggers a new rollout (deployment). +- **Options**: + - `--git-branch `: Deploy the latest commit from a specific branch. + - `--git-commit `: Deploy a specific commit. +- **Use Case**: Useful for redeploying without code changes, or rolling back to a specific commit. + +### `npx -y firebase-tools@latest apphosting:backends:create` + +- **Purpose**: Creates a new App Hosting backend. Use this when setting up automated deployments via GitHub. +- **Options**: + - `--app `: The ID of an existing Firebase web app to associate with the backend. + - `--backend `: The ID of the new backend. + - `--primary-region `: The primary region for the backend. + - `--root-dir `: The root directory for the backend. If omitted, defaults to the root directory of the project. + - `--service-account `: The service account used to run the server. If omitted, defaults to the default service account. + \ No newline at end of file diff --git a/.agents/skills/firebase-app-hosting-basics/references/configuration.md b/.agents/skills/firebase-app-hosting-basics/references/configuration.md new file mode 100644 index 0000000..da10766 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/configuration.md @@ -0,0 +1,51 @@ +# App Hosting Configuration (`apphosting.yaml`) + +The `apphosting.yaml` file is the source of truth for your backend's configuration. It must be located in the root of your app's directory (or the specific root directory if using a monorepo). + +## File Structure + +```yaml +# apphosting.yaml + +# Cloud Run service configuration +runConfig: + cpu: 1 + memoryMiB: 512 + minInstances: 0 + maxInstances: 100 + concurrency: 80 + +# Environment variables +env: + - variable: STORAGE_BUCKET + value: mybucket.app + availability: + - BUILD + - RUNTIME + - variable: API_KEY + secret: myApiKeySecret +``` + +## `runConfig` +Controls the resources allocated to the Cloud Run service that serves your app. +- `cpu`: Number of vCPUs. Note: If `< 1`, concurrency MUST be set to `1`. +- `memoryMiB`: RAM in MiB (128 to 32768). +- `minInstances`: Minimum containers to keep warm (default 0). Set to >= 1 to avoid cold starts. +- `maxInstances`: Maximum scaling limit (default 100). +- `concurrency`: Max concurrent requests per instance (default 80). + +### Resource Constraints +- **CPU vs Memory**: Higher memory often requires higher CPU. + - > 4GiB RAM -> Needs >= 2 vCPU + - > 8GiB RAM -> Needs >= 4 vCPU + +## `env` (Environment Variables) +Defines environment variables available during build and/or runtime. + +- `variable`: The name of the env var (e.g., `NEXT_PUBLIC_API_URL`). +- `value`: A literal string value. +- `secret`: The name of a secret in Cloud Secret Manager. use `npx -y firebase-tools@latest apphosting:secrets:set` to create these. +- `availability`: Where the variable is needed. + - `BUILD`: Available during the `npm run build` process. + - `RUNTIME`: Available when the app is serving requests. + - Defaults to both if not specified. diff --git a/.agents/skills/firebase-app-hosting-basics/references/emulation.md b/.agents/skills/firebase-app-hosting-basics/references/emulation.md new file mode 100644 index 0000000..299dcde --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/emulation.md @@ -0,0 +1,47 @@ +# App Hosting Emulation + +You can test your App Hosting setup locally using the Firebase Local Emulator Suite. This allows you to verify your app's behavior with environment variables and secrets before deploying. + +## Configuration: `apphosting.emulator.yaml` +This optional file overrides `apphosting.yaml` settings specifically for the local emulator. Use it to provide local secret values or override resource configs. If it contains sensitive values such as API keys, do not commit it to source control. + +```yaml +# apphosting.emulator.yaml (gitignored usually) +runConfig: + cpu: 1 + memoryMiB: 512 + +env: + - variable: API_KEY + value: "local-dev-api-key" # Override secret with local value +``` + +## Running the Emulator +To start the App Hosting emulator: + +```bash +npx -y firebase-tools@latest emulators:start --only apphosting +``` + +Or, if you are also using other emulators (Auth, Firestore, etc.): + +```bash +npx -y firebase-tools@latest emulators:start +``` + +## Capabilities +- **Builds your app**: Runs the build command defined in your `package.json` to generate the serving artifact. +- **Serves locally**: Runs the app on `localhost:5004` (default). +Configurable by setting `host` and `port` in the `emulators` block of `firebase.json`, like so: + +```json +{ + "emulators": { + "apphosting": { + "host": "localhost", + "port": 5004 + } + } +} +``` +- **Env Var Injection**: Injects variables defined in `apphosting.yaml` and `apphosting.emulator.yaml` into the process. diff --git a/.agents/skills/firebase-auth-basics/SKILL.md b/.agents/skills/firebase-auth-basics/SKILL.md new file mode 100644 index 0000000..bac12ad --- /dev/null +++ b/.agents/skills/firebase-auth-basics/SKILL.md @@ -0,0 +1,86 @@ +--- +name: firebase-auth-basics +description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +## Prerequisites + +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). + +## Core Concepts + +Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. + +### Users + +A user is an entity that can sign in to your app. Each user is identified by a unique ID (`uid`) which is guaranteed to be unique across all providers. +User properties include: +- `uid`: Unique identifier. +- `email`: User's email address (if available). +- `displayName`: User's display name (if available). +- `photoURL`: URL to user's photo (if available). +- `emailVerified`: Boolean indicating if the email is verified. + +### Identity Providers + +Firebase Auth supports multiple ways to sign in: +- **Email/Password**: Basic email and password authentication. +- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub, Microsoft, Apple, etc. +- **Phone Number**: SMS-based authentication. +- **Anonymous**: Temporary guest accounts that can be linked to permanent accounts later. +- **Custom Auth**: Integrate with your existing auth system. + +Google Sign In is recommended as a good and secure default provider. + +### Tokens + +When a user signs in, they receive an ID Token (JWT). This token is used to identify the user when making requests to Firebase services (Realtime Database, Cloud Storage, Firestore) or your own backend. +- **ID Token**: Short-lived (1 hour), verifies identity. +- **Refresh Token**: Long-lived, used to get new ID tokens. + +## Workflow + +### 1. Provisioning + +#### Option 1. Enabling Authentication via CLI + +Only Google Sign In, anonymous auth, and email/password auth can be enabled via CLI. For other providers, use the Firebase Console. + +Configure Firebase Authentication in `firebase.json` by adding an 'auth' block: + +``` +{ + "auth": { + "providers": { + "anonymous": true, + "emailPassword": true, + "googleSignIn": { + "oAuthBrandDisplayName": "Your Brand Name", + "supportEmail": "support@example.com", + "authorizedRedirectUris": ["https://example.com"] + } + } + } +} +``` + +#### Option 2. Enabling Authentication in Console + +Enable other providers in the Firebase Console. + +1. Go to the https://console.firebase.google.com/project/_/authentication/providers +2. Select your project. +3. Enable the desired Sign-in providers (e.g., Email/Password, Google). + +### 2. Client Setup & Usage + +**Web** +See [references/client_sdk_web.md](references/client_sdk_web.md). + +### 3. Security Rules + +Secure your data using `request.auth` in Firestore/Storage rules. + +See [references/security_rules.md](references/security_rules.md). diff --git a/.agents/skills/firebase-auth-basics/references/client_sdk_web.md b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md new file mode 100644 index 0000000..493a66a --- /dev/null +++ b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md @@ -0,0 +1,287 @@ +# Firebase Authentication Web SDK + +## Initialization + +First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize the Auth service: + +```javascript +import { getAuth } from "firebase/auth"; +import { app } from "./firebase"; // Your initialized Firebase App + +const auth = getAuth(app); +export { auth }; +``` + +## Connect to Emulator + +If you are running the Authentication emulator (usually on port 9099), connect to it immediately after initialization. + +```javascript +import { getAuth, connectAuthEmulator } from "firebase/auth"; + +const auth = getAuth(); +// Connect to emulator if running locally +if (location.hostname === "localhost") { + connectAuthEmulator(auth, "http://localhost:9099"); +} +``` + +## Sign Up with Email/Password + +```javascript +import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; + +const auth = getAuth(); +createUserWithEmailAndPassword(auth, email, password) + .then((userCredential) => { + const user = userCredential.user; + // ... + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + // .. + }); +``` + +## Sign In with Google (Popup) + +```javascript +import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GoogleAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // This gives you a Google Access Token. You can use it to access the Google API. + const credential = GoogleAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + // The signed-in user info. + const user = result.user; + // ... + }) + .catch((error) => { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // ... + }); +``` + +## Sign In with Facebook (Popup) + +```javascript +import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new FacebookAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // The signed-in user info. + const user = result.user; + // This gives you a Facebook Access Token. You can use it to access the Facebook API. + const credential = FacebookAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Apple (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('apple.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Apple credential + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Twitter (Popup) + +```javascript +import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new TwitterAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Twitter credential + const credential = TwitterAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + const secret = credential.secret; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with GitHub (Popup) + +```javascript +import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GithubAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = GithubAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Microsoft (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('microsoft.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Yahoo (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('yahoo.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In Anonymously + +```javascript +import { getAuth, signInAnonymously } from "firebase/auth"; + +const auth = getAuth(); +signInAnonymously(auth) + .then(() => { + // Signed in.. + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + }); +``` + +## Email Link Authentication + +**1. Send Auth Link** + +```javascript +import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; + +const auth = getAuth(); +const actionCodeSettings = { + // URL you want to redirect back to. The domain must be in the authorized domains list in Firebase Console. + url: 'https://www.example.com/finishSignUp?cartId=1234', + handleCodeInApp: true, +}; + +sendSignInLinkToEmail(auth, email, actionCodeSettings) + .then(() => { + // Save the email locally so you don't need to ask the user for it again + window.localStorage.setItem('emailForSignIn', email); + }) + .catch((error) => { + // Error + }); +``` + +**2. Complete Sign In (on landing page)** + +```javascript +import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth"; + +const auth = getAuth(); + +if (isSignInWithEmailLink(auth, window.location.href)) { + let email = window.localStorage.getItem('emailForSignIn'); + if (!email) { + email = window.prompt('Please provide your email for confirmation'); + } + + signInWithEmailLink(auth, email, window.location.href) + .then((result) => { + window.localStorage.removeItem('emailForSignIn'); + // You can check result.user + }) + .catch((error) => { + // Error + }); +} +``` + +## Observe Auth State + +Recommended way to get the current user. This listener triggers whenever the user signs in or out. + +```javascript +import { getAuth, onAuthStateChanged } from "firebase/auth"; + +const auth = getAuth(); +onAuthStateChanged(auth, (user) => { + if (user) { + // User is signed in, see docs for a list of available properties + // https://firebase.google.com/docs/reference/js/firebase.User + const uid = user.uid; + // ... + } else { + // User is signed out + // ... + } +}); +``` + +## Sign Out + +```javascript +import { getAuth, signOut } from "firebase/auth"; + +const auth = getAuth(); +signOut(auth).then(() => { + // Sign-out successful. +}).catch((error) => { + // An error happened. +}); +``` diff --git a/.agents/skills/firebase-auth-basics/references/security_rules.md b/.agents/skills/firebase-auth-basics/references/security_rules.md new file mode 100644 index 0000000..5de862a --- /dev/null +++ b/.agents/skills/firebase-auth-basics/references/security_rules.md @@ -0,0 +1,38 @@ +# Authentication in Security Rules + +Firebase Security Rules work with Firebase Authentication to provide rule-based access control. For better advice on writing safe security rules, +enable the `firebase-firestore-basics` or `firebase-storage-basics` skills. + +The `request.auth` variable contains authentication information for the user requesting data. + +## Basic Checks + +### Check if user is signed in +``` +allow read, write: if request.auth != null; +``` + +### Check if user owns the data +Access data only if the document ID matches the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == userId; +``` +(Where `userId` is a path variable, e.g., `match /users/{userId}`) + +### Check if user owns the document (field-based) +Access data only if the document has a `owner_uid` field matching the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == resource.data.owner_uid; +``` + +## Token Properties +`request.auth.token` contains standard JWT claims and custom claims. + +- `request.auth.token.email`: The user's email address. +- `request.auth.token.email_verified`: If the email is verified. +- `request.auth.token.name`: The user's display name. + +### Example: Email Verification Check +``` +allow create: if request.auth.token.email_verified == true; +``` diff --git a/.agents/skills/firebase-basics/SKILL.md b/.agents/skills/firebase-basics/SKILL.md new file mode 100644 index 0000000..25909bb --- /dev/null +++ b/.agents/skills/firebase-basics/SKILL.md @@ -0,0 +1,52 @@ +--- +name: firebase-basics +description: The definitive, foundational skill for ANY Firebase task. Make sure to ALWAYS use this skill whenever the user mentions or interacts with Firebase, even if they do not explicitly ask for it. This skill covers everything from the bare minimum INITIAL setup (Node.js setup, Firebase CLI installation, first-time login) to ongoing operations (core principles, workflows, building, service setup, executing Firebase CLI commands, troubleshooting, refreshing, or updating an existing environment). +--- +# Prerequisites + +Please complete these setup steps before proceeding, and remember your progress to avoid repeating them in future interactions. + +1. **Local Environment Setup:** Verify the environment is properly set up so we can use Firebase tools: + - Run `npx -y firebase-tools@latest --version` to check if the Firebase CLI is installed. + - Verify if the Firebase MCP server is installed using your existing tools. + - If either of these checks fails, please review [references/local-env-setup.md](references/local-env-setup.md) to get the environment ready. + +2. **Authentication:** + Ensure you are logged in to Firebase so that commands have the correct permissions. Run `npx -y firebase-tools@latest login`. For environments without a browser (e.g., remote shells), use `npx -y firebase-tools@latest login --no-localhost`. + - The command should output the current user. + - If you are not logged in, follow the interactive instructions from this command to authenticate. + +3. **Active Project:** + Most Firebase tasks require an active project context. Check the current project by running `npx -y firebase-tools@latest use`. + - If the command outputs `Active Project: `, you can proceed with your task. + - If not, ask the user if they have an existing Firebase Project ID. + - If yes: Set it as the active project and add a default alias by running: + ```bash + npx -y firebase-tools@latest use --add + ``` + - If no: Follow the project creation instructions in [references/firebase-project-create.md](references/firebase-project-create.md). + +# Firebase Usage Principles + +Please adhere to these principles when working with Firebase, as they ensure reliability and up-to-date project tools: + +1. **Use npx for CLI commands:** To ensure you always use the latest version of the Firebase CLI, always prepend commands with `npx -y firebase-tools@latest` instead of just `firebase`. (e.g., use `npx -y firebase-tools@latest --version` instead of `firebase --version`). +2. **Prioritize official knowledge:** For any Firebase-related knowledge, consult the `developerknowledge_search_documents` MCP tool before falling back to Google Search or your internal knowledge base. Including "Firebase" in your search query significantly improves relevance. +3. **Follow Agent Skills for implementation guidance:** Skills provide opinionated workflows (CUJs), security rules, and best practices. Always consult them to understand *how* to implement Firebase features correctly instead of relying on general knowledge. +4. **Use Firebase MCP Server tools instead of direct API calls:** Whenever you need to interact with remote Firebase APIs (such as fetching Crashlytics logs or executing Data Connect queries), use the tools provided by the Firebase MCP Server instead of attempting manual API calls. +5. **Keep Plugin / Agent Skills updated:** Since Firebase best practices evolve quickly, remind the user to regularly check for and install updates to their Firebase plugin or Agent Skills, ensuring you both operate with the latest workflows. Similarly, if you encounter issues with outdated tools or commands, follow the steps below based on your agent environment: + - **Antigravity**: Follow [references/refresh-antigravity.md](references/refresh-antigravity.md) + - **Gemini CLI**: Follow [references/refresh-gemini-cli.md](references/refresh-gemini-cli.md) + - **Claude Code**: Follow [references/refresh-claude.md](references/refresh-claude.md) + - **Cursor**: Follow [references/refresh-cursor.md](references/refresh-cursor.md) + - **Others**: Follow [references/refresh-other.md](references/refresh-other-agents.md) + +# References + +- **Initialize Firebase:** See [references/firebase-service-init.md](references/firebase-service-init.md) when you need to initialize new Firebase services using the CLI. +- **Exploring Commands:** See [references/firebase-cli-guide.md](references/firebase-cli-guide.md) to discover and understand CLI functionality. +- **SDK Setup:** For detailed guides on adding Firebase to a web app, see [references/web_setup.md](references/web_setup.md). + +# Common Issues + +- **Login Issues:** If the browser fails to open during the login step, use `npx -y firebase-tools@latest login --no-localhost` instead. diff --git a/.agents/skills/firebase-basics/references/firebase-cli-guide.md b/.agents/skills/firebase-basics/references/firebase-cli-guide.md new file mode 100644 index 0000000..36a4480 --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-cli-guide.md @@ -0,0 +1,16 @@ +# Exploring Commands + +The Firebase CLI documents itself. Use help commands to discover functionality. + +- **Global Help**: List all available commands and categories. + ```bash + npx -y firebase-tools@latest --help + ``` + +- **Command Help**: Get detailed usage for a specific command. + ```bash + npx -y firebase-tools@latest [command] --help + # Example: + npx -y firebase-tools@latest deploy --help + npx -y firebase-tools@latest firestore:indexes --help + ``` diff --git a/.agents/skills/firebase-basics/references/firebase-project-create.md b/.agents/skills/firebase-basics/references/firebase-project-create.md new file mode 100644 index 0000000..02b0566 --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-project-create.md @@ -0,0 +1,11 @@ +# Creating a Project + +To create a new Firebase project from the CLI: + +```bash +npx -y firebase-tools@latest projects:create +``` + +You will be prompted to: +1. Enter a **Project ID** (must be 6-30 chars, lowercase, digits, and hyphens; must be unique globally). +2. Enter a **display name**. diff --git a/.agents/skills/firebase-basics/references/firebase-service-init.md b/.agents/skills/firebase-basics/references/firebase-service-init.md new file mode 100644 index 0000000..13800aa --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-service-init.md @@ -0,0 +1,18 @@ +# Initialization + +Before initializing, check if you are already in a Firebase project directory by looking for `firebase.json`. + +1. **Project Directory:** + Navigate to the root directory of the codebase. + *(Only if starting a completely new project from scratch without an existing codebase, create a directory first: `mkdir my-project && cd my-project`)* + +2. **Initialize Services:** + Run the initialization command: + ```bash + npx -y firebase-tools@latest init + ``` + +The CLI will guide you through: +- Selecting features (Firestore, Functions, Hosting, etc.). +- Associating with an existing project or creating a new one. +- Configuring files (e.g. `firebase.json`, `.firebaserc`). diff --git a/.agents/skills/firebase-basics/references/local-env-setup.md b/.agents/skills/firebase-basics/references/local-env-setup.md new file mode 100644 index 0000000..99e6019 --- /dev/null +++ b/.agents/skills/firebase-basics/references/local-env-setup.md @@ -0,0 +1,65 @@ +# Firebase Local Environment Setup + +This skill documents the bare minimum setup required for a full Firebase experience for the agent. Before starting to use any Firebase features, you MUST verify that each of the following steps has been completed. + +## 1. Verify Node.js +- **Action**: Run `node --version`. +- **Handling**: Ensure Node.js is installed and the version is `>= 20`. If Node.js is missing or `< v20`, install it based on the operating system: + + **Recommended: Use a Node Version Manager** + This avoids permission issues when installing global packages. + + **For macOS or Linux:** + 1. Guide the user to the [official nvm repository](https://github.com/nvm-sh/nvm#installing-and-updating). + 2. Request the user to manually install `nvm` and reply when finished. **Stop and wait** for the user's confirmation. + 3. Make `nvm` available in the current terminal session by sourcing the appropriate profile: + ```bash + # For Bash + source ~/.bash_profile + source ~/.bashrc + + # For Zsh + source ~/.zprofile + source ~/.zshrc + ``` + 4. Install Node.js: + ```bash + nvm install 24 + nvm use 24 + ``` + + **For Windows:** + 1. Guide the user to download and install [nvm-windows](https://github.com/coreybutler/nvm-windows/releases). + 2. Request the user to manually install `nvm-windows` and Node.js, and reply when finished. **Stop and wait** for the user's confirmation. + 3. After the user confirms, verify Node.js is available: + ```bash + node --version + ``` + + **Alternative: Official Installer** + 1. Guide the user to download and install the LTS version from [nodejs.org](https://nodejs.org/en/download). + 2. Request the user to manually install Node.js and reply when finished. **Stop and wait** for the user's confirmation. + +## 2. Verify Firebase CLI +The Firebase CLI is the primary tool for interacting with Firebase services. +- **Action**: Run `npx -y firebase-tools@latest --version`. +- **Handling**: Ensure this command runs successfully and outputs a version number. + +## 3. Verify Firebase Authentication +You must be authenticated to manage Firebase projects. +- **Action**: Run `npx -y firebase-tools@latest login`. +- **Handling**: If the environment is remote or restricted (no browser access), run `npx -y firebase-tools@latest login --no-localhost` instead. + +## 4. Install Agent Skills and MCP Server +To fully manage Firebase, the agent needs specific skills and the Firebase MCP server installed. Identify the agent environment you are currently running in and follow the corresponding setup document strictly. + +**Read the setup document for your current agent:** +- **Gemini CLI**: Review [setup-gemini_cli.md](setup-gemini_cli.md) +- **Antigravity**: Review [setup-antigravity.md](setup-antigravity.md) +- **Claude Code**: Review [setup-claude_code.md](setup-claude_code.md) +- **Cursor**: Review [setup-cursor.md](setup-cursor.md) +- **GitHub Copilot**: Review [setup-github_copilot.md](setup-github_copilot.md) +- **Other Agents** (Windsurf, Cline, etc.): Review [setup-other_agents.md](setup-other_agents.md) + +--- +**CRITICAL AGENT RULE:** Do NOT proceed with any other Firebase tasks until EVERY step above has been successfully verified and completed. diff --git a/.agents/skills/firebase-basics/references/refresh-antigravity.md b/.agents/skills/firebase-basics/references/refresh-antigravity.md new file mode 100644 index 0000000..6f5ee32 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-antigravity.md @@ -0,0 +1,46 @@ +# Refresh Antigravity Local Environment + +Follow these steps to refresh Antigravity's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Antigravity relies on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent antigravity + + # Check global-level skills + npx -y skills list --agent antigravity --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to Antigravity.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent antigravity --yes + + # Update global-level skills + npx -y skills update --agent antigravity --global --yes + ``` diff --git a/.agents/skills/firebase-basics/references/refresh-claude.md b/.agents/skills/firebase-basics/references/refresh-claude.md new file mode 100644 index 0000000..772314e --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-claude.md @@ -0,0 +1,10 @@ +# Refresh Claude Code Local Environment + +Follow these steps to refresh Claude Code's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use Claude Code's native plugin manager instead of `npx`. + +1. **Update the Plugin:** Run the specific CLI command to update the Firebase plugin: + ```bash + claude plugin update firebase@firebase + ``` \ No newline at end of file diff --git a/.agents/skills/firebase-basics/references/refresh-gemini-cli.md b/.agents/skills/firebase-basics/references/refresh-gemini-cli.md new file mode 100644 index 0000000..6cc1467 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-gemini-cli.md @@ -0,0 +1,11 @@ +# Refresh Gemini CLI Local Environment + +Follow these steps to refresh Gemini CLI's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use the native Gemini CLI extension manager instead of `npx`. + +1. **Update the Extension:** Run the specific CLI command to update: + ```bash + gemini extensions update firebase + ``` + *Note: If the extension is named differently, replace `firebase` with the correct name from `gemini extensions list`.* diff --git a/.agents/skills/firebase-basics/references/refresh-other-agents.md b/.agents/skills/firebase-basics/references/refresh-other-agents.md new file mode 100644 index 0000000..f624c96 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-other-agents.md @@ -0,0 +1,48 @@ +# Refresh Other Local Environment + +Follow these steps to refresh the local environment of other agents, ensuring that their agent skills and plugins are fully up-to-date. + +Other agents rely on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +Replace `` with the actual agent name, which can be found in the [skills repository README](https://github.com/vercel-labs/skills/blob/main/README.md). + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked for the agent at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent + + # Check global-level skills + npx -y skills list --agent --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to the agent.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent --yes + + # Update global-level skills + npx -y skills update --agent --global --yes + ``` diff --git a/.agents/skills/firebase-basics/references/setup-antigravity.md b/.agents/skills/firebase-basics/references/setup-antigravity.md new file mode 100644 index 0000000..7817673 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-antigravity.md @@ -0,0 +1,63 @@ +# Antigravity Setup + +To get the most out of Firebase in Antigravity, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `ls -d .agent/skills/firebase-basics` or `ls -d .agents/skills/firebase-basics`. If the directory exists, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent antigravity + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent antigravity --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Antigravity to interact directly with Firebase projects. + +1. **Locate `mcp_config.json`**: Find the configuration file for your operating system: + - macOS / Linux: `~/.gemini/antigravity/mcp_config.json` + - Windows: `%USERPROFILE%\\.gemini\\antigravity\\mcp_config.json` + + *Note: If the `.gemini/antigravity/` directory or `mcp_config.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp_config.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp_config.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Antigravity**: Instruct the user to restart the Antigravity application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Antigravity UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-claude_code.md b/.agents/skills/firebase-basics/references/setup-claude_code.md new file mode 100644 index 0000000..fe8eba6 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-claude_code.md @@ -0,0 +1,30 @@ +# Claude Code Setup + +To get the most out of Firebase in Claude Code, follow these steps to install the agent skills and the MCP server. + +## Recommended Method: Using Plugins + +The recommended method is using the plugin marketplace to install both the agent skills and the MCP functionality. + +### 1. Install and Verify Plugins + +Check if the plugins are already installed before proceeding: + +1. **Check Existing Skills**: Run `npx skills list --agent claude-code` to check for local skills. Run `npx skills list --global --agent claude-code` to check for global skills. Note whether the output includes `firebase-basics`. +2. **Check Existing MCP Configuration**: Run `claude mcp list -s user` and `claude mcp list -s project`. Note whether the output of either command includes `firebase`. +3. **Determine Installation Path**: + - If **both** skills and MCP configuration are found, the plugin is fully installed. **Stop here and skip all remaining setup steps in this document.** + - If **neither** are found, proceed to step 4. + - If **only one** is found (e.g., skills are installed but MCP is missing, or vice versa), **stop and prompt the user**. Explain the mixed state and ask if they want to proceed with installing the Firebase plugin before continuing to step 4. +4. **Add Marketplace**: Run the following command to add the marketplace (this uses the default User scope): + ```bash + claude plugin marketplace add firebase/agent-skills + ``` +5. **Install Plugins**: Run the following command to install the plugin: + ```bash + claude plugin install firebase@firebase + ``` +6. **Verify Installation**: Re-run the checks in steps 1 and 2 to confirm the skills and the MCP server are now available. + +### 2. Restart and Verify Connection +1. **Restart Claude Code**: Instruct the user to restart Claude Code. **Stop and wait** for their confirmation before proceeding. diff --git a/.agents/skills/firebase-basics/references/setup-cursor.md b/.agents/skills/firebase-basics/references/setup-cursor.md new file mode 100644 index 0000000..c74360e --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-cursor.md @@ -0,0 +1,63 @@ +# Cursor Setup + +To get the most out of Firebase in Cursor, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent cursor`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent cursor + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent cursor --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Cursor to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your operating system: + - Global: `~/.cursor/mcp.json` + - Project: `.cursor/mcp.json` + + *Note: If the directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Cursor**: Instruct the user to restart the Cursor application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Cursor UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-gemini_cli.md b/.agents/skills/firebase-basics/references/setup-gemini_cli.md new file mode 100644 index 0000000..ebadeaa --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-gemini_cli.md @@ -0,0 +1,39 @@ +# Gemini CLI Setup + +To get the most out of Firebase in the Gemini CLI, follow these steps to install the agent extension and the MCP server. + +## Recommended: Installing Extensions + +The best way to get both the agent skills and the MCP server is via the Gemini extension. + +### 1. Install and Verify Firebase Extension +Check if the extension is already installed before proceeding: + +1. **Check Existing Extensions**: Run `gemini extensions list`. If the output includes `firebase`, the extension is already installed. +2. **Install Extension**: If not found, run the following command to install the Firebase agent skills and MCP server: + ```bash + gemini extensions install https://github.com/firebase/agent-skills + ``` +3. **Verify Installation**: Run the following checks to confirm installation: + - `gemini mcp list` -> Output should include `firebase-tools`. + - `gemini skills list` -> Output should include `firebase-basic`. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI if any new installation occurred. **Stop and wait** for their confirmation before proceeding. + +--- + +## Alternative: Manual MCP Configuration (Project Scope) + +If the user only wants to use the MCP server for the current project: + +### 1. Configure and Verify Firebase MCP Server +1. **Check Existing Configuration**: Run `gemini mcp list`. If the output includes `firebase-tools`, the MCP server is already configured. +2. **Add the MCP Server**: If not found, run the following command to configure the Firebase MCP Server: + ```bash + gemini mcp add -e IS_GEMINI_CLI_EXTENSION=true firebase npx -y firebase-tools@latest mcp + ``` +3. **Verify Configuration**: Re-run `gemini mcp list` to confirm `firebase-tools` is connected. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI. **Stop and wait** for their confirmation before proceeding. diff --git a/.agents/skills/firebase-basics/references/setup-github_copilot.md b/.agents/skills/firebase-basics/references/setup-github_copilot.md new file mode 100644 index 0000000..1704cb5 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-github_copilot.md @@ -0,0 +1,70 @@ +# GitHub Copilot Setup + +To get the most out of Firebase with GitHub Copilot in VS Code, follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent github-copilot`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent github-copilot + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent github-copilot --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows GitHub Copilot to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your environment: + - Workspace: `.vscode/mcp.json` + - Global: User Settings `mcp.json` file. + + *Note: If the `.vscode/` directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcp": { "servers": {} } }` before proceeding.* +2. **Check Existing Configuration**: Open the `mcp.json` file and check the `mcp.servers` object for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "type": "stdio", + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcp.servers` object: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file under the `mcp.servers` object. You MUST preserve any other existing servers inside `mcp.servers`.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart VS Code**: Instruct the user to restart VS Code. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the VS Code Copilot UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-other_agents.md b/.agents/skills/firebase-basics/references/setup-other_agents.md new file mode 100644 index 0000000..d45a608 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-other_agents.md @@ -0,0 +1,65 @@ +# Other Agents Setup + +If you use another agent (like Windsurf, Cline, or Claude Desktop), follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent `. If the output includes `firebase-basics`, the skills are already installed locally. Replace `` with the actual agent name, which can be found [here](https://github.com/vercel-labs/skills/blob/main/README.md). +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows the agent to interact directly with Firebase projects. + +1. **Locate MCP Configuration**: Find the configuration file for your agent (e.g., `~/.codeium/windsurf/mcp_config.json`, `cline_mcp_settings.json`, or `claude_desktop_config.json`). + + *Note: If the document or its containing directory does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open the configuration file and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Agent**: Instruct the user to restart the agent application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the agent's UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/web_setup.md b/.agents/skills/firebase-basics/references/web_setup.md new file mode 100644 index 0000000..b696118 --- /dev/null +++ b/.agents/skills/firebase-basics/references/web_setup.md @@ -0,0 +1,69 @@ +# Firebase Web Setup Guide + +## 1. Create a Firebase Project and App +If you haven't already created a project: + +```bash +npx -y firebase-tools@latest projects:create +``` + +Register your web app: +```bash +npx -y firebase-tools@latest apps:create web my-web-app +``` +(Note the **App ID** returned by this command). + +## 2. Installation +Install the Firebase SDK via npm: + +```bash +npm install firebase +``` + +## 3. Initialization +Create a `firebase.js` (or `firebase.ts`) file. You can fetch your config object using the CLI: + +```bash +npx -y firebase-tools@latest apps:sdkconfig +``` + +Copy the output config object into your initialization file: + +```javascript +import { initializeApp } from "firebase/app"; +import { getAuth } from "firebase/auth"; + +// Your web app's Firebase configuration +const firebaseConfig = { + apiKey: "API_KEY", + authDomain: "PROJECT_ID.firebaseapp.com", + projectId: "PROJECT_ID", + storageBucket: "PROJECT_ID.firebasestorage.app", + messagingSenderId: "SENDER_ID", + appId: "APP_ID", + measurementId: "G-MEASUREMENT_ID" +}; + +// Initialize Firebase +const app = initializeApp(firebaseConfig); +const auth = getAuth(app); + +export { app }; +``` + +## 4. Using Services +Import specific services as needed (Modular API): + +```javascript +import { getFirestore, collection, getDocs } from "firebase/firestore"; +import { app } from "./firebase"; // Import the initialized app + +const db = getFirestore(app); + +async function getUsers() { + const querySnapshot = await getDocs(collection(db, "users")); + querySnapshot.forEach((doc) => { + console.log(`${doc.id} => ${doc.data()}`); + }); +} +``` diff --git a/.agents/skills/firebase-data-connect/SKILL.md b/.agents/skills/firebase-data-connect/SKILL.md new file mode 100644 index 0000000..e87a3c1 --- /dev/null +++ b/.agents/skills/firebase-data-connect/SKILL.md @@ -0,0 +1,95 @@ +--- +name: firebase-data-connect +description: Build and deploy Firebase Data Connect backends with PostgreSQL. Use for schema design, GraphQL queries/mutations, authorization, and SDK generation for web, Android, iOS, and Flutter apps. +--- + +# Firebase Data Connect + +Firebase Data Connect is a relational database service using Cloud SQL for PostgreSQL with GraphQL schema, auto-generated queries/mutations, and type-safe SDKs. + +## Project Structure + +``` +dataconnect/ +├── dataconnect.yaml # Service configuration +├── schema/ +│ └── schema.gql # Data model (types with @table) +└── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Queries + └── mutations.gql # Mutations +``` + +## Development Workflow + +Follow this strict workflow to build your application. You **must** read the linked reference files for each step to understand the syntax and available features. + +### 1. Define Data Model (`schema/schema.gql`) +Define your GraphQL types, tables, and relationships. +> **Read [reference/schema.md](reference/schema.md)** for: +> * `@table`, `@col`, `@default` +> * Relationships (`@ref`, one-to-many, many-to-many) +> * Data types (UUID, Vector, JSON, etc.) + +### 2. Define Operations (`connector/queries.gql`, `connector/mutations.gql`) +Write the queries and mutations your client will use. Data Connect generates the underlying SQL. +> **Read [reference/operations.md](reference/operations.md)** for: +> * **Queries**: Filtering (`where`), Ordering (`orderBy`), Pagination (`limit`/`offset`). +> * **Mutations**: Create (`_insert`), Update (`_update`), Delete (`_delete`). +> * **Upserts**: Use `_upsert` to "insert or update" records (CRITICAL for user profiles). +> * **Transactions**: use `@transaction` for multi-step atomic operations. + +### 3. Secure Your App (`connector/` files) +Add authorization logic closely with your operations. +> **Read [reference/security.md](reference/security.md)** for: +> * `@auth(level: ...)` for PUBLIC, USER, or NO_ACCESS. +> * `@check` and `@redact` for row-level security and validation. + +### 4. Generate & Use SDKs +Generate type-safe code for your client platform. +> **Read [reference/sdks.md](reference/sdks.md)** for: +> * Android (Kotlin), iOS (Swift), Web (TypeScript), Flutter (Dart). +> * How to initialize and call your queries/mutations. +> * **Nested Data**: See how to access related fields (e.g., `movie.reviews`). + +--- + +## Feature Capability Map + +If you need to implement a specific feature, consult the mapped reference file: + +| Feature | Reference File | Key Concepts | +| :--- | :--- | :--- | +| **Data Modeling** | [reference/schema.md](reference/schema.md) | `@table`, `@unique`, `@index`, Relations | +| **Vector Search** | [reference/advanced.md](reference/advanced.md) | `Vector`, `@col(dataType: "vector")` | +| **Full-Text Search** | [reference/advanced.md](reference/advanced.md) | `@searchable` | +| **Upserting Data** | [reference/operations.md](reference/operations.md) | `_upsert` mutations | +| **Complex Filters** | [reference/operations.md](reference/operations.md) | `_or`, `_and`, `_not`, `eq`, `contains` | +| **Transactions** | [reference/operations.md](reference/operations.md) | `@transaction`, `response` binding | +| **Environment Config** | [reference/config.md](reference/config.md) | `dataconnect.yaml`, `connector.yaml` | + +--- + +## Deployment & CLI + +> **Read [reference/config.md](reference/config.md)** for deep dive on configuration. + +Common commands (run from project root): + +```bash +# Initialize Data Connect +npx -y firebase-tools@latest init dataconnect + +# Start local emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDK code +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +## Examples + +For complete, working code examples of schemas and operations, see **[examples.md](examples.md)**. diff --git a/.agents/skills/firebase-data-connect/examples.md b/.agents/skills/firebase-data-connect/examples.md new file mode 100644 index 0000000..87a6e3d --- /dev/null +++ b/.agents/skills/firebase-data-connect/examples.md @@ -0,0 +1,377 @@ +# Examples + +Complete, working examples for common Data Connect use cases. + +--- + +## Movie Review App + +A complete schema for a movie database with reviews, actors, and user authentication. + +### Schema + +```graphql +# schema.gql + +# Users +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movies +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + releaseYear: Int + genre: String @index + rating: Float + description: String + posterUrl: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movie metadata (one-to-one) +type MovieMetadata @table { + movie: Movie! @unique + director: String + runtime: Int + budget: Int64 +} + +# Actors +type Actor @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + birthDate: Date +} + +# Movie-Actor relationship (many-to-many) +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # "lead" or "supporting" + character: String +} + +# Reviews (user-owned) +type Review @table @unique(fields: ["movie", "user"]) { + id: UUID! @default(expr: "uuidV4()") + movie: Movie! + user: User! + rating: Int! + text: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Queries + +```graphql +# queries.gql + +# Public: List movies with filtering +query ListMovies($genre: String, $minRating: Float, $limit: Int) + @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ rating: DESC }], + limit: $limit + ) { + id title genre rating releaseYear posterUrl + } +} + +# Public: Get movie with full details +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre rating releaseYear description + metadata: movieMetadata_on_movie { director runtime } + actors: actors_via_MovieActor { name } + reviews: reviews_on_movie(orderBy: [{ createdAt: DESC }], limit: 10) { + rating text createdAt + user { displayName } + } + } +} + +# User: Get my reviews +query MyReviews @auth(level: USER) { + reviews(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + id rating text createdAt + movie { id title posterUrl } + } +} +``` + +### Mutations + +```graphql +# mutations.gql + +# User: Create/update profile on first login +mutation UpsertUser($email: String!, $displayName: String) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + displayName: $displayName + }) +} + +# User: Add review (one per movie per user) +mutation AddReview($movieId: UUID!, $rating: Int!, $text: String) + @auth(level: USER) { + review_upsert(data: { + movie: { id: $movieId }, + user: { uid_expr: "auth.uid" }, + rating: $rating, + text: $text + }) +} + +# User: Delete my review +mutation DeleteReview($id: UUID!) @auth(level: USER) { + review_delete( + first: { where: { + id: { eq: $id }, + user: { uid: { eq_expr: "auth.uid" }} + }} + ) +} +``` + +--- + +## E-Commerce Store + +Products, orders, and cart management with user authentication. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String + shippingAddress: String +} + +type Product @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @index + description: String + price: Float! + stock: Int! @default(value: 0) + category: String @index + imageUrl: String +} + +type CartItem @table(key: ["user", "product"]) { + user: User! + product: Product! + quantity: Int! +} + +enum OrderStatus { + PENDING + PAID + SHIPPED + DELIVERED + CANCELLED +} + +type Order @table { + id: UUID! @default(expr: "uuidV4()") + user: User! + status: OrderStatus! @default(value: PENDING) + total: Float! + shippingAddress: String! + createdAt: Timestamp! @default(expr: "request.time") +} + +type OrderItem @table { + id: UUID! @default(expr: "uuidV4()") + order: Order! + product: Product! + quantity: Int! + priceAtPurchase: Float! +} +``` + +### Operations + +```graphql +# Public: Browse products +query ListProducts($category: String, $search: String) @auth(level: PUBLIC) { + products(where: { + category: { eq: $category }, + name: { contains: $search }, + stock: { gt: 0 } + }) { + id name price stock imageUrl + } +} + +# User: View cart +query MyCart @auth(level: USER) { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + quantity + product { id name price imageUrl stock } + } +} + +# User: Add to cart +mutation AddToCart($productId: UUID!, $quantity: Int!) @auth(level: USER) { + cartItem_upsert(data: { + user: { uid_expr: "auth.uid" }, + product: { id: $productId }, + quantity: $quantity + }) +} + +# User: Checkout (transactional) +mutation Checkout($shippingAddress: String!) + @auth(level: USER) + @transaction { + # Query cart items + query @redact { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) + @check(expr: "this.size() > 0", message: "Cart is empty") { + quantity + product { id price } + } + } + # Create order (in real app, calculate total from cart) + order_insert(data: { + user: { uid_expr: "auth.uid" }, + shippingAddress: $shippingAddress, + total: 0 # Calculate in app logic + }) +} +``` + +--- + +## Blog with Permissions + +Multi-author blog with role-based permissions. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String! + bio: String +} + +enum UserRole { + VIEWER + AUTHOR + EDITOR + ADMIN +} + +type BlogPermission @table(key: ["user"]) { + user: User! + role: UserRole! @default(value: VIEWER) +} + +enum PostStatus { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! + title: String! @searchable + content: String! @searchable + status: PostStatus! @default(value: DRAFT) + publishedAt: Timestamp + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} + +type Comment @table { + id: UUID! @default(expr: "uuidV4()") + post: Post! + author: User! + content: String! + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Operations with Role Checks + +```graphql +# Public: Read published posts +query PublishedPosts @auth(level: PUBLIC) { + posts( + where: { status: { eq: PUBLISHED }}, + orderBy: [{ publishedAt: DESC }] + ) { + id title content publishedAt + author { name } + } +} + +# Author+: Create post +mutation CreatePost($title: String!, $content: String!) + @auth(level: USER) + @transaction { + # Check user is at least AUTHOR + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) + @check(expr: "this != null", message: "No permission record") { + role @check(expr: "this in ['AUTHOR', 'EDITOR', 'ADMIN']", message: "Must be author+") + } + } + post_insert(data: { + author: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +# Editor+: Publish any post +mutation PublishPost($id: UUID!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this in ['EDITOR', 'ADMIN']", message: "Must be editor+") + } + } + post_update(id: $id, data: { + status: PUBLISHED, + publishedAt_expr: "request.time" + }) +} + +# Admin: Grant role +mutation GrantRole($userUid: String!, $role: UserRole!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this == 'ADMIN'", message: "Must be admin") + } + } + blogPermission_upsert(data: { + user: { uid: $userUid }, + role: $role + }) +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/advanced.md b/.agents/skills/firebase-data-connect/reference/advanced.md new file mode 100644 index 0000000..bdffe7c --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/advanced.md @@ -0,0 +1,303 @@ +# Advanced Features Reference + +## Contents +- [Vector Similarity Search](#vector-similarity-search) +- [Full-Text Search](#full-text-search) +- [Cloud Functions Integration](#cloud-functions-integration) +- [Data Seeding & Bulk Operations](#data-seeding--bulk-operations) + +--- + +## Vector Similarity Search + +Semantic search using Vertex AI embeddings and PostgreSQL's `pgvector`. + +### Schema Setup + +```graphql +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + description: String + # Vector field for embeddings - size must match model output (768 for gecko) + descriptionEmbedding: Vector! @col(size: 768) +} +``` + +### Generate Embeddings in Mutations + +Use `_embed` server value to auto-generate embeddings via Vertex AI: + +```graphql +mutation CreateMovieWithEmbedding($title: String!, $description: String!) + @auth(level: USER) { + movie_insert(data: { + title: $title, + description: $description, + descriptionEmbedding_embed: { + model: "textembedding-gecko@003", + text: $description + } + }) +} +``` + +### Similarity Search Query + +Data Connect generates `_similarity` fields for Vector columns: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare_embed: { model: "textembedding-gecko@003", text: $query }, + method: L2, # L2, COSINE, or INNER_PRODUCT + within: 2.0, # Max distance threshold + limit: 5 + ) { + id + title + description + _metadata { distance } # See how close each result is + } +} +``` + +### Similarity Parameters + +| Parameter | Description | +|-----------|-------------| +| `compare` | Raw Vector to compare against | +| `compare_embed` | Generate embedding from text via Vertex AI | +| `method` | Distance function: `L2`, `COSINE`, `INNER_PRODUCT` | +| `within` | Max distance (results further are excluded) | +| `where` | Additional filters | +| `limit` | Max results to return | + +### Custom Embeddings + +Pass pre-computed vectors directly: + +```graphql +mutation StoreCustomEmbedding($id: UUID!, $embedding: Vector!) @auth(level: USER) { + movie_update(id: $id, data: { descriptionEmbedding: $embedding }) +} + +query SearchWithCustomVector($vector: Vector!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare: $vector, + method: COSINE, + limit: 10 + ) { id title } +} +``` + +--- + +## Full-Text Search + +Fast keyword/phrase search using PostgreSQL's full-text capabilities. + +### Enable with @searchable + +```graphql +type Movie @table { + title: String! @searchable + description: String @searchable(language: "english") + genre: String @searchable +} +``` + +### Search Query + +Data Connect generates `_search` fields: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + queryFormat: QUERY, # QUERY, PLAIN, PHRASE, or ADVANCED + limit: 20 + ) { + id title description + _metadata { relevance } # Relevance score + } +} +``` + +### Query Formats + +| Format | Description | +|--------|-------------| +| `QUERY` | Web-style (default): quotes, AND, OR supported | +| `PLAIN` | Match all words, any order | +| `PHRASE` | Match exact phrase | +| `ADVANCED` | Full tsquery syntax | + +### Tuning Results + +```graphql +query SearchWithThreshold($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + relevanceThreshold: 0.05, # Min relevance score + where: { genre: { eq: "Action" }}, + orderBy: [{ releaseYear: DESC }] + ) { id title } +} +``` + +### Supported Languages + +`english` (default), `french`, `german`, `spanish`, `italian`, `portuguese`, `dutch`, `danish`, `finnish`, `norwegian`, `swedish`, `russian`, `arabic`, `hindi`, `simple` + +--- + +## Cloud Functions Integration + +Trigger Cloud Functions when mutations execute. + +### Basic Trigger (Node.js) + +```typescript +import { onMutationExecuted } from "firebase-functions/dataconnect"; +import { logger } from "firebase-functions"; + +export const onUserCreate = onMutationExecuted( + { + service: "myService", + connector: "default", + operation: "CreateUser", + region: "us-central1" // Must match Data Connect location + }, + (event) => { + const variables = event.data.payload.variables; + const returnedData = event.data.payload.data; + + logger.info("User created:", returnedData); + // Send welcome email, sync to analytics, etc. + } +); +``` + +### Basic Trigger (Python) + +```python +from firebase_functions import dataconnect_fn, logger + +@dataconnect_fn.on_mutation_executed( + service="myService", + connector="default", + operation="CreateUser" +) +def on_user_create(event: dataconnect_fn.Event): + variables = event.data.payload.variables + returned_data = event.data.payload.data + logger.info("User created:", returned_data) +``` + +### Event Data + +```typescript +// event.authType: "app_user" | "unauthenticated" | "admin" +// event.authId: Firebase Auth UID (for app_user) +// event.data.payload.variables: mutation input variables +// event.data.payload.data: mutation response data +// event.data.payload.errors: any errors that occurred +``` + +### Filtering with Wildcards + +```typescript +// Trigger on all User* mutations +export const onUserMutation = onMutationExecuted( + { operation: "User*" }, + (event) => { /* ... */ } +); + +// Capture operation name +export const onAnyMutation = onMutationExecuted( + { service: "myService", operation: "{operationName}" }, + (event) => { + console.log("Operation:", event.params.operationName); + } +); +``` + +### Use Cases + +- **Data sync**: Replicate to Firestore, BigQuery, external APIs +- **Notifications**: Send emails, push notifications on events +- **Async workflows**: Image processing, data aggregation +- **Audit logging**: Track all data changes + +> ⚠️ **Avoid infinite loops**: Don't trigger mutations that would fire the same trigger. Use filters to exclude self-triggered events. + +--- + +## Data Seeding & Bulk Operations + +### Local Prototyping with _insertMany + +```graphql +mutation SeedMovies @transaction { + movie_insertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" }, + { id: "uuid-3", title: "Movie 3", genre: "Comedy" } + ]) +} +``` + +### Reset Data with _upsertMany + +```graphql +mutation ResetData { + movie_upsertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } + ]) +} +``` + +### Clear All Data + +```graphql +mutation ClearMovies { + movie_deleteMany(all: true) +} +``` + +### Production: Admin SDK Bulk Operations + +```typescript +import { initializeApp } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +const app = initializeApp(); +const dc = getDataConnect({ location: "us-central1", serviceId: "my-service" }); + +const movies = [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } +]; + +// Bulk insert +await dc.insertMany("movie", movies); + +// Bulk upsert +await dc.upsertMany("movie", movies); + +// Single operations +await dc.insert("movie", movies[0]); +await dc.upsert("movie", movies[0]); +``` + +### Emulator Data Persistence + +```bash +# Export emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with saved data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` diff --git a/.agents/skills/firebase-data-connect/reference/config.md b/.agents/skills/firebase-data-connect/reference/config.md new file mode 100644 index 0000000..c7e5c52 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/config.md @@ -0,0 +1,267 @@ +# Configuration Reference + +## Contents +- [Project Structure](#project-structure) +- [dataconnect.yaml](#dataconnectyaml) +- [connector.yaml](#connectoryaml) +- [Firebase CLI Commands](#firebase-cli-commands) +- [Emulator](#emulator) +- [Deployment](#deployment) + +--- + +## Project Structure + +``` +project-root/ +├── firebase.json # Firebase project config +└── dataconnect/ + ├── dataconnect.yaml # Service configuration + ├── schema/ + │ └── schema.gql # Data model (types, relationships) + └── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Query operations + └── mutations.gql # Mutation operations (optional separate file) +``` + +--- + +## dataconnect.yaml + +Main Data Connect service configuration: + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schemaValidation: "STRICT" # or "COMPATIBLE" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +| Field | Description | +|-------|-------------| +| `specVersion` | Always `"v1"` | +| `serviceId` | Unique identifier for the service | +| `location` | GCP region (us-central1, us-east4, europe-west1, etc.) | +| `schemaValidation` | Deployment mode: `"STRICT"` (must match exactly) or `"COMPATIBLE"` (backward compatible) | +| `schema.source` | Path to schema directory | +| `schema.datasource` | PostgreSQL connection config | +| `connectorDirs` | List of connector directories | + +### Cloud SQL Configuration + +```yaml +schema: + datasource: + postgresql: + database: "my-database" # Database name + cloudSql: + instanceId: "my-instance" # Cloud SQL instance ID +``` + +--- + +## connector.yaml + +Connector configuration and SDK generation: + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" +``` + +### SDK Generation Options + +| SDK | Fields | +|-----|--------| +| `javascriptSdk` | `outputDir`, `package` | +| `kotlinSdk` | `outputDir`, `package` | +| `swiftSdk` | `outputDir` | +| `nodeAdminSdk` | `outputDir`, `package` (for Admin SDK) | + +--- + +## Firebase CLI Commands + +### Initialize Data Connect + +```bash +# Interactive setup +npx -y firebase-tools@latest init dataconnect + +# Set project +npx -y firebase-tools@latest use +``` + +### Local Development + +```bash +# Start emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Start with database seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Watch for schema changes (auto-regenerate) +npx -y firebase-tools@latest dataconnect:sdk:generate --watch +``` + +### Schema Management + +```bash +# Compare local schema to production +npx -y firebase-tools@latest dataconnect:sql:diff + + +# Apply migration +npx -y firebase-tools@latest dataconnect:sql:migrate +``` + +### Deployment + +```bash +# Deploy Data Connect service +npx -y firebase-tools@latest deploy --only dataconnect + +# Deploy specific connector +npx -y firebase-tools@latest deploy --only dataconnect:connector-id + +# Deploy with schema migration +npx -y firebase-tools@latest deploy --only dataconnect --force +``` + +--- + +## Emulator + +### Start Emulator + +```bash +npx -y firebase-tools@latest emulators:start --only dataconnect +``` + +Default ports: +- Data Connect: `9399` +- PostgreSQL: `9939` (local PostgreSQL instance) + +### Emulator Configuration (firebase.json) + +```json +{ + "emulators": { + "dataconnect": { + "port": 9399 + } + } +} +``` + +### Connect from SDK + +```typescript +// Web +import { connectDataConnectEmulator } from 'firebase/data-connect'; +connectDataConnectEmulator(dc, 'localhost', 9399); + +// Android +connector.dataConnect.useEmulator("10.0.2.2", 9399) + +// iOS +connector.useEmulator(host: "localhost", port: 9399) + + +``` + +### Seed Data + +Create seed data files and import: + +```bash +# Export current emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` + +--- + +## Deployment + +### Deploy Workflow + +1. **Test locally** with emulator +2. **Generate SQL diff**: `npx -y firebase-tools@latest dataconnect:sql:diff` +3. **Review migration**: Check breaking changes +4. **Deploy**: `npx -y firebase-tools@latest deploy --only dataconnect` + +### Schema Migrations + +Data Connect auto-generates PostgreSQL migrations: + +```bash +# Preview migration +npx -y firebase-tools@latest dataconnect:sql:diff + +# Apply migration (interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate + +# Force migration (non-interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate --force +``` + +### Breaking Changes + +Some schema changes require special handling: +- Removing required fields +- Changing field types +- Removing tables + +Use `--force` flag to acknowledge breaking changes during deploy. + +### CI/CD Integration + +```yaml +# GitHub Actions example +- name: Deploy Data Connect + run: | + npx -y firebase-tools@latest deploy --only dataconnect --token ${{ secrets.FIREBASE_TOKEN }} --force +``` + +--- + +## VS Code Extension + +Install "Firebase Data Connect" extension for: +- Schema intellisense and validation +- GraphQL operation testing +- Emulator integration +- SDK generation on save + +### Extension Settings + +```json +{ + "firebase.dataConnect.autoGenerateSdk": true, + "firebase.dataConnect.emulator.port": 9399 +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/operations.md b/.agents/skills/firebase-data-connect/reference/operations.md new file mode 100644 index 0000000..6fe7e73 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/operations.md @@ -0,0 +1,357 @@ +# Operations Reference + +## Contents +- [Generated Fields](#generated-fields) +- [Queries](#queries) +- [Mutations](#mutations) +- [Key Scalars](#key-scalars) +- [Multi-Step Operations](#multi-step-operations) + +--- + +## Generated Fields + +Data Connect auto-generates fields for each `@table` type: + +| Generated Field | Purpose | Example | +|-----------------|---------|---------| +| `movie(id: UUID, key: Key, first: Row)` | Get single record | `movie(id: $id)` or `movie(first: {where: ...})` | +| `movies(where: ..., orderBy: ..., limit: ..., offset: ..., distinct: ..., having: ...)` | List/filter records | `movies(where: {...})` | +| `movie_insert(data: ...)` | Create record | Returns key | +| `movie_insertMany(data: [...])` | Bulk create | Returns keys | +| `movie_update(id: ..., data: ...)` | Update by ID | Returns key or null | +| `movie_updateMany(where: ..., data: ...)` | Bulk update | Returns count | +| `movie_upsert(data: ...)` | Insert or update | Returns key | +| `movie_delete(id: ...)` | Delete by ID | Returns key or null | +| `movie_deleteMany(where: ...)` | Bulk delete | Returns count | + +### Relation Fields +For a `Post` with `author: User!`: +- `post.author` - Navigate to related User +- `user.posts_on_author` - Reverse: all Posts by User + +For many-to-many via `MovieActor`: +- `movie.actors_via_MovieActor` - Get all actors +- `actor.movies_via_MovieActor` - Get all movies + +--- + +## Queries + +### Basic Query + +```graphql +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre releaseYear + } +} +``` + +### List with Filtering + +```graphql +query ListMovies($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ releaseYear: DESC }, { title: ASC }], + limit: 20, + offset: 0 + ) { + id title genre rating + } +} +``` + +### Filter Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `eq` | Equals | `{ title: { eq: "Matrix" }}` | +| `ne` | Not equals | `{ status: { ne: "deleted" }}` | +| `gt`, `ge` | Greater than (or equal) | `{ rating: { ge: 4 }}` | +| `lt`, `le` | Less than (or equal) | `{ releaseYear: { lt: 2000 }}` | +| `in` | In list | `{ genre: { in: ["Action", "Drama"] }}` | +| `nin` | Not in list | `{ status: { nin: ["deleted", "hidden"] }}` | +| `isNull` | Is null check | `{ description: { isNull: true }}` | +| `contains` | String contains | `{ title: { contains: "war" }}` | +| `startsWith` | String starts with | `{ title: { startsWith: "The" }}` | +| `endsWith` | String ends with | `{ email: { endsWith: "@gmail.com" }}` | +| `includes` | Array includes | `{ tags: { includes: "sci-fi" }}` | + +### Expression Operators (Compare with Server Values) + +Use `_expr` suffix to compare with server-side values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +query RecentPosts @auth(level: PUBLIC) { + posts(where: { publishedAt: { lt_expr: "request.time" }}) { + id title + } +} +``` + +### Logical Operators + +```graphql +query ComplexFilter($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies(where: { + _or: [ + { genre: { eq: $genre }}, + { rating: { ge: $minRating }} + ], + _and: [ + { releaseYear: { ge: 2000 }}, + { status: { ne: "hidden" }} + ], + _not: { genre: { eq: "Horror" }} + }) { id title } +} +``` + +### Relational Queries + +```graphql +# Navigate relationships +query MovieWithDetails($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + title + # One-to-one + metadata: movieMetadata_on_movie { director } + # One-to-many + reviews: reviews_on_movie { rating user { name }} + # Many-to-many + actors: actors_via_MovieActor { name } + } +} + +# Filter by related data +query MoviesByDirector($director: String!) @auth(level: PUBLIC) { + movies(where: { + movieMetadata_on_movie: { director: { eq: $director }} + }) { id title } +} +``` + +### Aliases + +```graphql +query CompareRatings($genre: String!) @auth(level: PUBLIC) { + highRated: movies(where: { genre: { eq: $genre }, rating: { ge: 8 }}) { + title rating + } + lowRated: movies(where: { genre: { eq: $genre }, rating: { lt: 5 }}) { + title rating + } +} +``` + +--- + +## Mutations + +### Create + +```graphql +mutation CreateMovie($title: String!, $genre: String) @auth(level: USER) { + movie_insert(data: { + title: $title, + genre: $genre + }) +} +``` + +### Create with Server Values + +```graphql +mutation CreatePost($title: String!, $content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", # Current user + id_expr: "uuidV4()", # Auto-generate UUID + createdAt_expr: "request.time", # Server timestamp + title: $title, + content: $content + }) +} +``` + +### Update + +```graphql +mutation UpdateMovie($id: UUID!, $title: String, $genre: String) @auth(level: USER) { + movie_update( + id: $id, + data: { + title: $title, + genre: $genre, + updatedAt_expr: "request.time" + } + ) +} +``` + +### Update Operators + +```graphql +mutation IncrementViews($id: UUID!) @auth(level: PUBLIC) { + movie_update(id: $id, data: { + viewCount_update: { inc: 1 } + }) +} + +mutation AddTag($id: UUID!, $tag: String!) @auth(level: USER) { + movie_update(id: $id, data: { + tags_update: { add: [$tag] } # add, remove, append, prepend + }) +} +``` + +| Operator | Types | Description | +|----------|-------|-------------| +| `inc` | Int, Float, Date, Timestamp | Increment value | +| `dec` | Int, Float, Date, Timestamp | Decrement value | +| `add` | Lists | Add items if not present | +| `remove` | Lists | Remove all matching items | +| `append` | Lists | Append to end | +| `prepend` | Lists | Prepend to start | + +### Upsert + +```graphql +mutation UpsertUser($email: String!, $name: String!) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + name: $name + }) +} +``` + +### Delete + +```graphql +mutation DeleteMovie($id: UUID!) @auth(level: USER) { + movie_delete(id: $id) +} + +mutation DeleteOldDrafts @auth(level: USER) { + post_deleteMany(where: { + status: { eq: "draft" }, + createdAt: { lt_time: { now: true, sub: { days: 30 }}} + }) +} +``` + +### Filtered Updates/Deletes (User-Owned) + +```graphql +mutation UpdateMyPost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } # Only own posts + }}, + data: { content: $content } + ) +} +``` + +--- + +## Key Scalars + +Key scalars (`Movie_Key`, `User_Key`) are auto-generated types representing primary keys: + +```graphql +# Using key scalar +query GetMovie($key: Movie_Key!) @auth(level: PUBLIC) { + movie(key: $key) { title } +} + +# Variable format +# { "key": { "id": "uuid-here" } } + +# Composite key +# { "key": { "movieId": "...", "userId": "..." } } +``` + +Key scalars are returned by mutations: + +```graphql +mutation CreateAndFetch($title: String!) @auth(level: USER) { + key: movie_insert(data: { title: $title }) + # Returns: { "key": { "id": "generated-uuid" } } +} +``` + +--- + +## Multi-Step Operations + +### @transaction + +Ensures atomicity - all steps succeed or all rollback: + +```graphql +mutation CreateUserWithProfile($name: String!, $bio: String!) + @auth(level: USER) + @transaction { + # Step 1: Create user + user_insert(data: { + uid_expr: "auth.uid", + name: $name + }) + # Step 2: Create profile (uses response from step 1) + userProfile_insert(data: { + userId_expr: "response.user_insert.uid", + bio: $bio + }) +} +``` + +### Using response Binding + +Access results from previous steps: + +```graphql +mutation CreateTodoWithItem($listName: String!, $itemText: String!) + @auth(level: USER) + @transaction { + todoList_insert(data: { + id_expr: "uuidV4()", + name: $listName + }) + todoItem_insert(data: { + listId_expr: "response.todoList_insert.id", # From previous step + text: $itemText + }) +} +``` + +### Embedded Queries + +Run queries within mutations for validation: + +```graphql +mutation AddToPublicList($listId: UUID!, $item: String!) + @auth(level: USER) + @transaction { + # Step 1: Verify list exists and is public + query @redact { + todoList(id: $listId) @check(expr: "this != null", message: "List not found") { + isPublic @check(expr: "this == true", message: "List is not public") + } + } + # Step 2: Add item + todoItem_insert(data: { listId: $listId, text: $item }) +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/schema.md b/.agents/skills/firebase-data-connect/reference/schema.md new file mode 100644 index 0000000..21d34ec --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/schema.md @@ -0,0 +1,278 @@ +# Schema Reference + +## Contents +- [Defining Types](#defining-types) +- [Core Directives](#core-directives) +- [Relationships](#relationships) +- [Data Types](#data-types) +- [Enumerations](#enumerations) + +--- + +## Defining Types + +Types with `@table` map to PostgreSQL tables. Data Connect auto-generates an implicit `id: UUID!` primary key. + +```graphql +type Movie @table { + # id: UUID! is auto-added + title: String! + releaseYear: Int + genre: String +} +``` + +### Customizing Tables + +```graphql +type Movie @table(name: "movies", key: "id", singular: "movie", plural: "movies") { + id: UUID! @col(name: "movie_id") @default(expr: "uuidV4()") + title: String! + releaseYear: Int @col(name: "release_year") + genre: String @col(dataType: "varchar(20)") +} +``` + +### User Table with Auth + +```graphql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String @col(dataType: "varchar(100)") + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +--- + +## Core Directives + +### @table +Defines a database table. + +| Argument | Description | +|----------|-------------| +| `name` | PostgreSQL table name (snake_case default) | +| `key` | Primary key field(s), default `["id"]` | +| `singular` | Singular name for generated fields | +| `plural` | Plural name for generated fields | + +### @col +Customizes column mapping. + +| Argument | Description | +|----------|-------------| +| `name` | Column name in PostgreSQL | +| `dataType` | PostgreSQL type: `serial`, `varchar(n)`, `text`, etc. | +| `size` | Required for `Vector` type | + +### @default +Sets default value for inserts. + +| Argument | Description | +|----------|-------------| +| `value` | Literal value: `@default(value: "draft")` | +| `expr` | CEL expression: `@default(expr: "uuidV4()")`, `@default(expr: "auth.uid")`, `@default(expr: "request.time")` | +| `sql` | Raw SQL: `@default(sql: "now()")` | + +**Common expressions:** +- `uuidV4()` - Generate UUID +- `auth.uid` - Current user's Firebase Auth UID +- `request.time` - Server timestamp + +### @unique +Adds unique constraint. + +```graphql +type User @table { + email: String! @unique +} + +# Composite unique +type Review @table @unique(fields: ["movie", "user"]) { + movie: Movie! + user: User! + rating: Int +} +``` + +### @index +Creates database index for query performance. + +```graphql +type Movie @table @index(fields: ["genre", "releaseYear"], order: [ASC, DESC]) { + title: String! @index + genre: String + releaseYear: Int +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Fields for composite index (on @table) | +| `order` | `[ASC]` or `[DESC]` for each field | +| `type` | `BTREE` (default), `GIN` (arrays), `HNSW`/`IVFFLAT` (vectors) | + +### @searchable +Enables full-text search on String fields. + +```graphql +type Post @table { + title: String! @searchable + body: String! @searchable(language: "english") +} + +# Usage +query SearchPosts($q: String!) @auth(level: PUBLIC) { + posts_search(query: $q) { id title body } +} +``` + +--- + +## Relationships + +### One-to-Many (Implicit Foreign Key) + +```graphql +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! # Creates authorId foreign key + title: String! +} + +type User @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + # Auto-generated: posts_on_author: [Post!]! +} +``` + +### @ref Directive +Customizes foreign key reference. + +```graphql +type Post @table { + author: User! @ref(fields: "authorId", references: "id") + authorId: UUID! # Explicit FK field +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Local FK field name(s) | +| `references` | Target field(s) in referenced table | +| `constraintName` | PostgreSQL constraint name | + +**Cascade behavior:** +- Required reference (`User!`): CASCADE DELETE (post deleted when user deleted) +- Optional reference (`User`): SET NULL (authorId set to null when user deleted) + +### One-to-One + +Use `@unique` on the reference field: + +```graphql +type User @table { id: UUID! name: String! } + +type UserProfile @table { + user: User! @unique # One profile per user + bio: String + avatarUrl: String +} + +# Query: user.userProfile_on_user +``` + +### Many-to-Many + +Use a join table with composite primary key: + +```graphql +type Movie @table { id: UUID! title: String! } +type Actor @table { id: UUID! name: String! } + +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # Extra data on relationship +} + +# Generated fields: +# - movie.actors_via_MovieActor: [Actor!]! +# - actor.movies_via_MovieActor: [Movie!]! +# - movie.movieActors_on_movie: [MovieActor!]! +``` + +--- + +## Data Types + +| GraphQL Type | PostgreSQL Default | Other PostgreSQL Types | +|--------------|-------------------|----------------------| +| `String` | `text` | `varchar(n)`, `char(n)` | +| `Int` | `int4` | `int2`, `serial` | +| `Int64` | `bigint` | `bigserial`, `numeric` | +| `Float` | `float8` | `float4`, `numeric` | +| `Boolean` | `boolean` | | +| `UUID` | `uuid` | | +| `Date` | `date` | | +| `Timestamp` | `timestamptz` | Stored as UTC | +| `Any` | `jsonb` | | +| `Vector` | `vector` | Requires `@col(size: N)` | +| `[Type]` | Array | e.g., `[String]` → `text[]` | + +--- + +## Enumerations + +```graphql +enum Status { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + status: Status! @default(value: DRAFT) + allowedStatuses: [Status!] +} +``` + +**Rules:** +- Enum names: PascalCase, no underscores +- Enum values: UPPER_SNAKE_CASE +- Values are ordered (for comparison operations) +- Changing order or removing values is a breaking change + +--- + +## Views (Advanced) + +Map custom SQL queries to GraphQL types: + +```graphql +type MovieStats @view(sql: """ + SELECT + movie_id, + COUNT(*) as review_count, + AVG(rating) as avg_rating + FROM review + GROUP BY movie_id +""") { + movie: Movie @unique + reviewCount: Int + avgRating: Float +} + +# Query movies with stats +query TopMovies @auth(level: PUBLIC) { + movies(orderBy: [{ rating: DESC }]) { + title + stats: movieStats_on_movie { + reviewCount avgRating + } + } +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/sdks.md b/.agents/skills/firebase-data-connect/reference/sdks.md new file mode 100644 index 0000000..9885056 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/sdks.md @@ -0,0 +1,287 @@ +# SDK Reference + +## Contents +- [SDK Generation](#sdk-generation) +- [Web SDK](#web-sdk) +- [Android SDK](#android-sdk) +- [iOS SDK](#ios-sdk) +- [Admin SDK](#admin-sdk) + +--- + +## SDK Generation + +Configure SDK generation in `connector.yaml`: + +```yaml +connectorId: my-connector +generate: + javascriptSdk: + outputDir: "../web-app/src/lib/dataconnect" + package: "@movie-app/dataconnect" + kotlinSdk: + outputDir: "../android-app/app/src/main/kotlin/com/example/dataconnect" + package: "com.example.dataconnect" + swiftSdk: + outputDir: "../ios-app/DataConnect" +``` + +Generate SDKs: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` + +--- + +## Web SDK + +### Installation + +```bash +npm install firebase +``` + +### Initialization + +```typescript +import { initializeApp } from 'firebase/app'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@movie-app/dataconnect'; + +const app = initializeApp(firebaseConfig); +const dc = getDataConnect(app, connectorConfig); + +// For local development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dc, 'localhost', 9399); +} +``` + +### Calling Operations + +```typescript +// Generated SDK provides typed functions +import { listMovies, createMovie, getMovie } from '@movie-app/dataconnect'; + +// Accessing Nested Fields +const movie = await getMovie({ id: '...' }); +// Relations are just properties on the object +const director = movie.data.movie.metadata.director; +const firstActor = movie.data.movie.actors[0].name; + +// Query +const result = await listMovies(); +console.log(result.data.movies); + +// Query with variables +const movie = await getMovie({ id: 'uuid-here' }); + +// Mutation +const newMovie = await createMovie({ + title: 'New Movie', + genre: 'Action' +}); +console.log(newMovie.data.movie_insert); // Returns key +``` + +### Subscriptions + +```typescript +import { listMoviesRef, subscribe } from '@movie-app/dataconnect'; + +const unsubscribe = subscribe(listMoviesRef(), { + onNext: (result) => { + console.log('Movies updated:', result.data.movies); + }, + onError: (error) => { + console.error('Subscription error:', error); + } +}); + +// Later: unsubscribe(); +``` + +### With Authentication + +```typescript +import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; + +const auth = getAuth(app); +await signInWithEmailAndPassword(auth, email, password); + +// SDK automatically includes auth token in requests +const myReviews = await myReviews(); // @auth(level: USER) query from examples.md +``` + +--- + +## Android SDK + +### Dependencies (build.gradle.kts) + +```kotlin +dependencies { + implementation(platform("com.google.firebase:firebase-bom:33.0.0")) + implementation("com.google.firebase:firebase-dataconnect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.0") +} +``` + +### Initialization + +```kotlin +import com.google.firebase.Firebase +import com.google.firebase.dataconnect.dataConnect +import com.example.dataconnect.MyConnector + +val connector = MyConnector.instance + +// For emulator +connector.dataConnect.useEmulator("10.0.2.2", 9399) +``` + +### Calling Operations + +```kotlin +// Query +val result = connector.listMovies.execute() +result.data.movies.forEach { movie -> + println(movie.title) + // Access nested fields directly + println(movie.metadata?.director) + println(movie.actors.firstOrNull()?.name) +} + +// Query with variables +val movie = connector.getMovie.execute(id = "uuid-here") + +// Mutation +val newMovie = connector.createMovie.execute( + title = "New Movie", + genre = "Action" +) +``` + +### Flow Subscription + +```kotlin +connector.listMovies.flow().collect { result -> + when (result) { + is DataConnectResult.Success -> updateUI(result.data.movies) + is DataConnectResult.Error -> showError(result.exception) + } +} +``` + +--- + +## iOS SDK + +### Dependencies (Package.swift or SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "11.0.0") +] +// Add FirebaseDataConnect to target dependencies +``` + +### Initialization + +```swift +import FirebaseCore +import FirebaseDataConnect + +FirebaseApp.configure() +let connector = MyConnector.shared + +// For emulator +connector.useEmulator(host: "localhost", port: 9399) +``` + +### Calling Operations + +```swift +// Query +let result = try await connector.listMovies.execute() +for movie in result.data.movies { + print(movie.title) + // Access nested fields directly + print(movie.metadata?.director ?? "Unknown") + print(movie.actors.first?.name ?? "No actors") +} + +// Query with variables +let movie = try await connector.getMovie.execute(id: "uuid-here") + +// Mutation +let newMovie = try await connector.createMovie.execute( + title: "New Movie", + genre: "Action" +) +``` + +### Combine Publisher + +```swift +connector.listMovies.publisher + .sink( + receiveCompletion: { completion in + if case .failure(let error) = completion { + print("Error: \(error)") + } + }, + receiveValue: { result in + self.movies = result.data.movies + } + ) + .store(in: &cancellables) +``` + +--- + + + +## Admin SDK + +Server-side operations with elevated privileges (bypasses @auth): + +### Node.js + +```typescript +import { initializeApp, cert } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +initializeApp({ + credential: cert(serviceAccount) +}); + +const dc = getDataConnect(); + +// Execute operations (bypasses @auth) +const result = await dc.executeGraphql({ + query: `query { users { id email } }`, + operationName: 'ListAllUsers' +}); + +// Or use generated Admin SDK +import { listAllUsers } from './admin-connector'; +const users = await listAllUsers(); +``` + +### Generate Admin SDK + +In `connector.yaml`: + +```yaml +generate: + nodeAdminSdk: + outputDir: "./admin-sdk" + package: "@app/admin-dataconnect" +``` + +Generate: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` diff --git a/.agents/skills/firebase-data-connect/reference/security.md b/.agents/skills/firebase-data-connect/reference/security.md new file mode 100644 index 0000000..5eacee8 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/security.md @@ -0,0 +1,289 @@ +# Security Reference + +## Contents +- [@auth Directive](#auth-directive) +- [Access Levels](#access-levels) +- [CEL Expressions](#cel-expressions) +- [@check and @redact](#check-and-redact) +- [Authorization Patterns](#authorization-patterns) +- [Anti-Patterns](#anti-patterns) + +--- + +## @auth Directive + +Every deployable query/mutation must have `@auth`. Without it, operations default to `NO_ACCESS`. + +```graphql +query PublicData @auth(level: PUBLIC) { ... } +query UserData @auth(level: USER) { ... } +query AdminOnly @auth(expr: "auth.token.admin == true") { ... } +``` + +| Argument | Description | +|----------|-------------| +| `level` | Preset access level | +| `expr` | CEL expression (alternative to level) | +| `insecureReason` | Suppress deploy warning for PUBLIC/unfiltered USER | + +--- + +## Access Levels + +| Level | Who Can Access | CEL Equivalent | +|-------|----------------|----------------| +| `PUBLIC` | Anyone, authenticated or not | `true` | +| `USER_ANON` | Any authenticated user (including anonymous) | `auth.uid != nil` | +| `USER` | Authenticated users (excludes anonymous) | `auth.uid != nil && auth.token.firebase.sign_in_provider != 'anonymous'` | +| `USER_EMAIL_VERIFIED` | Users with verified email | `auth.uid != nil && auth.token.email_verified` | +| `NO_ACCESS` | Admin SDK only | `false` | + +> **Important:** Levels like `USER` are starting points. Always add filters or expressions to verify the user can access specific data. + +--- + +## CEL Expressions + +### Available Bindings + +| Binding | Description | +|---------|-------------| +| `auth.uid` | Current user's Firebase UID | +| `auth.token` | Auth token claims (see below) | +| `vars` | Operation variables (e.g., `vars.movieId`) | +| `request.time` | Server timestamp | +| `request.operationName` | "query" or "mutation" | + +### auth.token Fields + +| Field | Description | +|-------|-------------| +| `email` | User's email address | +| `email_verified` | Boolean: email verified | +| `phone_number` | User's phone | +| `name` | Display name | +| `sub` | Firebase UID (same as auth.uid) | +| `firebase.sign_in_provider` | `password`, `google.com`, `anonymous`, etc. | +| `` | Custom claims set via Admin SDK | + +### Expression Examples + +```graphql +# Check custom claim +@auth(expr: "auth.token.role == 'admin'") + +# Check verified email domain +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") + +# Check multiple conditions +@auth(expr: "auth.uid != nil && (auth.token.role == 'editor' || auth.token.role == 'admin')") + +# Check variable +@auth(expr: "has(vars.status) && vars.status in ['draft', 'published']") +``` + +### Using eq_expr in Filters + +Compare database fields with auth values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +mutation UpdateMyPost($id: UUID!, $title: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } + }}, + data: { title: $title } + ) +} +``` + +--- + +## @check and @redact + +Use `@check` to validate data and `@redact` to hide results from client: + +### @check +Validates a field value; aborts if check fails. + +```graphql +@check(expr: "this != null", message: "Not found") +@check(expr: "this == 'editor'", message: "Must be editor") +@check(expr: "this.exists(p, p.role == 'admin')", message: "No admin found") +``` + +| Argument | Description | +|----------|-------------| +| `expr` | CEL expression; `this` = current field value | +| `message` | Error message if check fails | +| `optional` | If `true`, pass when field not present | + +### @redact +Hides field from response (still evaluated for @check): + +```graphql +query @redact { ... } # Query result hidden but @check still runs +``` + +### Authorization Data Lookup + +Check database permissions before allowing mutation: + +```graphql +mutation UpdateMovie($id: UUID!, $title: String!) + @auth(level: USER) + @transaction { + # Step 1: Check user has permission + query @redact { + moviePermission( + key: { movieId: $id, userId_expr: "auth.uid" } + ) @check(expr: "this != null", message: "No access to movie") { + role @check(expr: "this == 'editor'", message: "Must be editor") + } + } + # Step 2: Update if authorized + movie_update(id: $id, data: { title: $title }) +} +``` + +### Validate Key Exists + +```graphql +mutation MustDeleteMovie($id: UUID!) @auth(level: USER) @transaction { + movie_delete(id: $id) + @check(expr: "this != null", message: "Movie not found") +} +``` + +--- + +## Authorization Patterns + +### User-Owned Resources + +```graphql +# Create with owner +mutation CreatePost($content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", + content: $content + }) +} + +# Read own data only +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id content + } +} + +# Update own data only +mutation UpdatePost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}}, + data: { content: $content } + ) +} + +# Delete own data only +mutation DeletePost($id: UUID!) @auth(level: USER) { + post_delete( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}} + ) +} +``` + +### Role-Based Access + +```graphql +# Admin-only query +query AllUsers @auth(expr: "auth.token.admin == true") { + users { id email name } +} + +# Role from database +mutation AdminAction($id: UUID!) @auth(level: USER) @transaction { + query @redact { + user(key: { uid_expr: "auth.uid" }) { + role @check(expr: "this == 'admin'", message: "Admin required") + } + } + # ... admin action +} +``` + +### Public Data with Filters + +```graphql +query PublicPosts @auth(level: PUBLIC) { + posts(where: { + visibility: { eq: "public" }, + publishedAt: { lt_expr: "request.time" } + }) { + id title content + } +} +``` + +### Tiered Access (Pro Content) + +```graphql +query ProContent @auth(expr: "auth.token.plan == 'pro'") { + posts(where: { visibility: { in: ["public", "pro"] }}) { + id title content + } +} +``` + +--- + +## Anti-Patterns + +### ❌ Don't Pass User ID as Variable + +```graphql +# BAD - any user can pass any userId +query GetUserPosts($userId: String!) @auth(level: USER) { + posts(where: { authorUid: { eq: $userId }}) { ... } +} + +# GOOD - use auth.uid +query GetMyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Use USER Without Filters + +```graphql +# BAD - any authenticated user sees all documents +query AllDocs @auth(level: USER) { + documents { id title content } +} + +# GOOD - filter to user's documents +query MyDocs @auth(level: USER) { + documents(where: { ownerId: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Trust Unverified Email + +```graphql +# BAD - email not verified +@auth(expr: "auth.token.email.endsWith('@company.com')") + +# GOOD - verify email first +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") +``` + +### ❌ Don't Use PUBLIC/USER for Prototyping + +During development, set operations to `NO_ACCESS` until you implement proper authorization. Use emulator and VS Code extension for testing. diff --git a/.agents/skills/firebase-data-connect/templates.md b/.agents/skills/firebase-data-connect/templates.md new file mode 100644 index 0000000..75d20dc --- /dev/null +++ b/.agents/skills/firebase-data-connect/templates.md @@ -0,0 +1,269 @@ +# Templates + +Ready-to-use templates for common Firebase Data Connect patterns. + +--- + +## Basic CRUD Schema + +```graphql +# schema.gql +type Item @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + description: String + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query ListItems @auth(level: PUBLIC) { + items(orderBy: [{ createdAt: DESC }]) { + id name description createdAt + } +} + +query GetItem($id: UUID!) @auth(level: PUBLIC) { + item(id: $id) { id name description createdAt updatedAt } +} +``` + +```graphql +# mutations.gql +mutation CreateItem($name: String!, $description: String) @auth(level: USER) { + item_insert(data: { name: $name, description: $description }) +} + +mutation UpdateItem($id: UUID!, $name: String, $description: String) @auth(level: USER) { + item_update(id: $id, data: { + name: $name, + description: $description, + updatedAt_expr: "request.time" + }) +} + +mutation DeleteItem($id: UUID!) @auth(level: USER) { + item_delete(id: $id) +} +``` + +--- + +## User-Owned Resources + +```graphql +# schema.gql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String +} + +type Note @table { + id: UUID! @default(expr: "uuidV4()") + owner: User! + title: String! + content: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query MyNotes @auth(level: USER) { + notes( + where: { owner: { uid: { eq_expr: "auth.uid" }}}, + orderBy: [{ createdAt: DESC }] + ) { id title content createdAt } +} + +query GetMyNote($id: UUID!) @auth(level: USER) { + note( + first: { where: { + id: { eq: $id }, + owner: { uid: { eq_expr: "auth.uid" }} + }} + ) { id title content } +} +``` + +```graphql +# mutations.gql +mutation CreateNote($title: String!, $content: String) @auth(level: USER) { + note_insert(data: { + owner: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +mutation UpdateNote($id: UUID!, $title: String, $content: String) @auth(level: USER) { + note_update( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}}, + data: { title: $title, content: $content } + ) +} + +mutation DeleteNote($id: UUID!) @auth(level: USER) { + note_delete( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}} + ) +} +``` + +--- + +## Many-to-Many Relationship + +```graphql +# schema.gql +type Tag @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @unique +} + +type Article @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + content: String! +} + +type ArticleTag @table(key: ["article", "tag"]) { + article: Article! + tag: Tag! +} +``` + +```graphql +# queries.gql +query ArticlesByTag($tagName: String!) @auth(level: PUBLIC) { + articles(where: { + articleTags_on_article: { tag: { name: { eq: $tagName }}} + }) { + id title + tags: tags_via_ArticleTag { name } + } +} + +query ArticleWithTags($id: UUID!) @auth(level: PUBLIC) { + article(id: $id) { + id title content + tags: tags_via_ArticleTag { id name } + } +} +``` + +```graphql +# mutations.gql +mutation AddTagToArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_insert(data: { + article: { id: $articleId }, + tag: { id: $tagId } + }) +} + +mutation RemoveTagFromArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_delete(key: { articleId: $articleId, tagId: $tagId }) +} +``` + +--- + +## dataconnect.yaml Template + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +--- + +## connector.yaml Template + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" + dartSdk: + outputDir: "../flutter/lib/dataconnect" + package: myapp_dataconnect +``` + +--- + +## Firebase Init Commands + +```bash +# Initialize Data Connect in project +npx -y firebase-tools@latest init dataconnect + +# Initialize with specific project +npx -y firebase-tools@latest use +npx -y firebase-tools@latest init dataconnect + +# Start emulator for development +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +--- + +## SDK Initialization (Web) + +```typescript +// lib/firebase.ts +import { initializeApp } from 'firebase/app'; +import { getAuth } from 'firebase/auth'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@myapp/dataconnect'; + +const firebaseConfig = { + apiKey: "...", + authDomain: "...", + projectId: "...", +}; + +export const app = initializeApp(firebaseConfig); +export const auth = getAuth(app); +export const dataConnect = getDataConnect(app, connectorConfig); + +// Connect to emulator in development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dataConnect, 'localhost', 9399); +} +``` + +```typescript +// Example usage +import { listItems, createItem } from '@myapp/dataconnect'; + +// List items +const { data } = await listItems(); +console.log(data.items); + +// Create item (requires auth) +await createItem({ name: 'New Item', description: 'Description' }); +``` diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md new file mode 100644 index 0000000..1eeb40f --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md @@ -0,0 +1,31 @@ +--- +name: firebase-firestore-enterprise-native-mode +description: Comprehensive guide for Firestore enterprise native including provisioning, data model, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore Enterprise with the Native mode, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Enterprise Native Mode + +This skill provides a complete guide for getting started with Firestore Enterprise Native Mode, including provisioning, data model, security rules, and SDK usage. + +## Provisioning + +To set up Firestore Enterprise Native Mode in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Data Model + +To learn about Firestore data model and how to organize your data, see [data_model.md](references/data_model.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Firestore Enterprise Native Mode in your application code, see: +- [Web SDK Usage](references/web_sdk_usage.md) +- [Python SDK Usage](references/python_sdk_usage.md) + +## Indexes + +Indexes help improve query performance and speed up slow queries. For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md new file mode 100644 index 0000000..0fe42c0 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md @@ -0,0 +1,54 @@ +# Firestore Data Model Reference + +Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in **documents**, which are organized into **collections**. + +## Document Data Model + +Data in Firestore is organized into documents, collections, and subcollections. + +### Documents +A **document** is a lightweight record that contains fields, which map to values. Each document is identified by a name. A document can contain complex nested objects in addition to basic data types like strings, numbers, and booleans. Documents are limited to a maximum size of 1 MiB. + +Example document (e.g., in a `users` collection): +```json +{ + "first": "Ada", + "last": "Lovelace", + "born": 1815 +} +``` + +### Collections +Documents live in **collections**, which are containers for your documents. For example, you could have a `users` collection to contain your various users, each represented by a document. +* Collections can only contain documents. They cannot directly contain raw fields with values, and they cannot contain other collections. +* Documents within a collection can contain different fields. +* You don't need to "create" or "delete" collections explicitly. After you create the first document in a collection, the collection exists. If you delete all of the documents in a collection, the collection no longer exists. + +### Subcollections +Documents can contain subcollections natively. A subcollection is a collection associated with a specific document. +For example, a user document in the `users` collection could have a `messages` subcollection containing message documents exclusively for that user. This creates a powerful hierarchical data structure. + +Data path example: `users/user1/messages/message1` + +## Collection Group Support + +A **collection group** consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection. + +### Use Cases +Collection group queries are useful when you want to query across multiple subcollections that share the same organizational structure. + +For example, imagine an app with a `landmarks` collection where each landmark has a `reviews` subcollection. If you want to find all 5-star reviews across *all* landmarks, it would involve checking many separate `reviews` subcollections. With a collection group, you can perform a single query against the `reviews` collection group. + +### Examples + +**Standard Query** (Single Collection): +Find all 5-star reviews for a specific landmark. +```javascript +db.collection('landmarks/golden_gate_bridge/reviews').where('rating', '==', 5) +``` + +**Collection Group Query**: +Find all 5-star reviews across *all* landmarks. +```javascript +db.collectionGroup('reviews').where('rating', '==', 5) +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md new file mode 100644 index 0000000..f1031bd --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md @@ -0,0 +1,111 @@ +# Firestore Indexes Reference + +Indexes helps to improve query performance. Firestore Enterprise edition does not create any indexes by default. By default, Firestore Enterprise performs a full collection scan to find documents that match a query, which can be slow and expensive for large collections. To avoid this, you can create indexes to optimize your queries. + +## Index Structure + +An index consists of the following: + +* a collection ID. +* a list of fields in the given collection. +* an order, either ascending or descending, for each field. + +### Index Ordering + +The order and sort direction of each field uniquely defines the index. For example, the following indexes are two distinct indexes and not interchangeable: + +* Field name `name` (ascending) and `population` (descending) +* Field name `name` (descending) and `population` (ascending) + +### Index Density + +Dense indexes: By default, Firestore indexes store data from all documents in a collection. An index entry will be added for a document regardless of whether the document contains any of the fields specified in the index. Non-existent fields are treated as having a NULL value when generating index entries. + +Sparse indexes: To change this behavior, you can define the index as a sparse index. A sparse index indexes only the documents in the collection that contain a value (including null) for at least one of the indexed fields. A sparse index reduces storage costs and can improve performance. + +### Unique Indexes + +You can use unique index option to enforce unique values for the indexed fields. For indexes on multiple fields, each combination of values must be unique across the index. The database rejects any update and insert operations that attempt to create index entries with duplicate values. + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Single-Field Index on field `a` | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Single-Field Index on field `a` | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Single-Field Index on field `a` and `b` | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** on field `tags` and `active` | + +If no indexes is present, Firestore Enterprise will perform a full collection scan to find documents that match a query. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +Define a dense index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "DENSE", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a sparse-any index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a unique index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "unique": true, + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx firebase-tools@latest -y deploy --only firestore:indexes +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md new file mode 100644 index 0000000..02a97e3 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md @@ -0,0 +1,101 @@ +# Provisioning Firestore Enterprise Native Mode + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create a Firestore Enterprise Database**: Create a Firestore Enterprise database using the Firebase CLI. +2. **Create `firebase.json`**: This file contains database configuration for the Firebase CLI. +3. **Create `firestore.rules`**: This file contains your security rules. +4. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create a Firestore Enterprise Database + +Use the following command to create a Firestore Enterprise database: + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" +``` + +This will create an enterprise database in `nam5` with native mode enabled. A database id is required to create an enterprise database and the database id must not be `(default)`. To enable realtime-updates feature, use `--realtime-updates` flag. + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" \ + --realtime-updates="ENABLED" +``` + +### 2. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "edition": "enterprise", + "database": "my-database-id", + "location": "nam5" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +firebase deploy --only firestore + +# To deploy just rules +firebase deploy --only firestore:rules + +# To deploy just indexes +firebase deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +firebase emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md new file mode 100644 index 0000000..8bd67a4 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md @@ -0,0 +1,126 @@ +# Python SDK Usage + +The Python Server SDK is used for backend/server environments and utilizes Google Application Default Credentials in most Google Cloud environments. + +### Writing Data + +#### Set a Document +Creates a document if it does not exist or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```python +city_ref = db.collection("cities").document("LA") + +# Create/Overwrite +city_ref.set({ + "name": "Los Angeles", + "state": "CA", + "country": "USA" +}) + +# Merge +city_ref.set({"population": 3900000}, merge=True) +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```python +update_time, city_ref = db.collection("cities").add({ + "name": "Tokyo", + "country": "Japan" +}) +print("Document written with ID: ", city_ref.id) +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```python +city_ref = db.collection("cities").document("LA") +city_ref.update({ + "capital": True +}) +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```python +from google.cloud.firestore import Transaction + +transaction = db.transaction() +city_ref = db.collection("cities").document("SF") + +@firestore.transactional +def update_in_transaction(transaction, city_ref): + snapshot = city_ref.get(transaction=transaction) + if not snapshot.exists: + raise Exception("Document does not exist!") + + new_population = snapshot.get("population") + 1 + transaction.update(city_ref, {"population": new_population}) + +update_in_transaction(transaction, city_ref) +``` + +### Reading Data + +#### Get a Single Document + +```python +doc_ref = db.collection("cities").document("SF") +doc = doc_ref.get() + +if doc.exists: + print(f"Document data: {doc.to_dict()}") +else: + print("No such document!") +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```python +docs = db.collection("cities").stream() + +for doc in docs: + print(f"{doc.id} => {doc.to_dict()}") +``` + +### Queries + +#### Simple and Compound Queries +Use `.where()` to combine filters safely. Stack `.where()` calls for compound queries. + +```python +from google.cloud.firestore import FieldFilter + +cities_ref = db.collection("cities") + +# Simple equality +query_1 = cities_ref.where(filter=FieldFilter("state", "==", "CA")) + +# Compound (AND) +query_2 = cities_ref.where( + filter=FieldFilter("state", "==", "CA") +).where( + filter=FieldFilter("population", ">", 1000000) +) +``` + +#### Order and Limit +Sort and limit results cleanly. + +```python +query = cities_ref.order_by("name").limit(3) +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```python +pipeline = client.pipeline().collection("users") +for result in pipeline.execute(): + print(f"{result.id} => {result.data()}") +``` diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md new file mode 100644 index 0000000..1eee422 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md @@ -0,0 +1,201 @@ +# Web SDK Usage + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +### Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'firebase apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); +``` + +### Writing Data + +#### Set a Document +Creates a document if it doesn't exist, or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +### Reading Data + +#### Get a Single Document + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + console.log(doc.id, " => ", doc.data()); +}); +``` + +### Realtime Updates + +#### Listen to a Document or Query + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// To stop listening: +// unsub(); +``` + +### Handle Changes + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +### Queries + +#### Simple and Compound Queries +Use `query()` and `where()` to combine filters safely. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires a composite index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +#### Order and Limit +Sort and limit results cleanly. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```javascript + +const readDataPipeline = db.pipeline() + .collection("users"); + +// Execute the pipeline and handle the result +try { + const querySnapshot = await execute(readDataPipeline); + querySnapshot.results.forEach((result) => { + console.log(`${result.id} => ${result.data()}`); + }); +} catch (error) { + console.error("Error getting documents: ", error); +} +``` diff --git a/.agents/skills/firebase-firestore-standard/SKILL.md b/.agents/skills/firebase-firestore-standard/SKILL.md new file mode 100644 index 0000000..0eb6c2e --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/SKILL.md @@ -0,0 +1,27 @@ +--- +name: firebase-firestore-standard +description: Comprehensive guide for Firestore Standard Edition, including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Standard Edition + +This skill provides a complete guide for getting started with Cloud Firestore Standard Edition, including provisioning, securing, and integrating it into your application. + +## Provisioning + +To set up Cloud Firestore in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Cloud Firestore in your application code, choose your platform: + +* **Web (Modular SDK)**: [web_sdk_usage.md](references/web_sdk_usage.md) + +## Indexes + +For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-standard/references/indexes.md b/.agents/skills/firebase-firestore-standard/references/indexes.md new file mode 100644 index 0000000..7623eb8 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/indexes.md @@ -0,0 +1,82 @@ +# Firestore Indexes Reference + +Indexes allow Firestore to ensure that query performance depends on the size of the result set, not the size of the database. + +## Index Types + +### Single-Field Indexes +In Standard Edition, Firestore **automatically creates** a single-field index for every field in a document (and subfields in maps). +* **Support**: Simple equality queries (`==`) and single-field range/sort queries (`<`, `<=`, `orderBy`). +* **Behavior**: You generally don't need to manage these unless you want to *exempt* a field. + +### Composite Indexes +A composite index stores a sorted mapping of all documents based on an ordered list of fields. +* **Support**: Complex queries that filter or sort by **multiple fields**. +* **Creation**: These are **NOT** automatically created. You must define them manually or via the console/CLI. + +## Automatic vs. Manual Management + +### What is Automatic? +* Indexes for simple queries. +* Merging of single-field indexes for multiple equality filters (e.g., `where("state", "==", "CA").where("country", "==", "USA")`). + +### When Do I Need to Act? +If you attempt a query that requires a composite index, the SDK will throw an error containing a **direct link** to the Firebase Console to create that specific index. + +**Example Error:** +> "The query requires an index. You can create it here: https://console.firebase.google.com/project/..." + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Automatic (Single-Field) | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Automatic (Single-Field) | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Automatic (Merged Single-Field) | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** (and technically limited query support) | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** | + +## Best Practices & Exemptions + +You can **exempt** fields from automatic indexing to save storage or strictly enforce write limits. + +### 1. High Write Rates (Sequential Values) +* **Problem**: Indexing fields that increase sequentially (like `timestamp`) limits the write rate to ~500 writes/second per collection. +* **Solution**: If you don't query on this field, **exempt** it from simple indexing. + +### 2. Large String/Map/Array Fields +* **Problem**: Indexing limits (40k entries per doc). Indexing large blobs wastes storage. +* **Solution**: Exempt large text blobs or huge arrays if they aren't used for filtering. + +### 3. TTL Fields +* **Problem**: TTL (Time-To-Live) deletion can cause index churn. +* **Solution**: Exempt the TTL timestamp field from indexing if you don't query it. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx -y firebase-tools@latest deploy --only firestore:indexes +``` diff --git a/.agents/skills/firebase-firestore-standard/references/provisioning.md b/.agents/skills/firebase-firestore-standard/references/provisioning.md new file mode 100644 index 0000000..5278801 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/provisioning.md @@ -0,0 +1,87 @@ +# Provisioning Cloud Firestore + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create `firebase.json`**: This file configures the Firebase CLI. +2. **Create `firestore.rules`**: This file contains your security rules. +3. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json" + } +} +``` + +This will use the default database with the Standard edition. To use a different database, specify the database ID and location. You can check the list of available databases using `npx -y firebase-tools@latest firestore:databases:list`. If the database does not exist, it will be created when you deploy: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "database": "my-database-id", + "location": "us-central1" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +npx -y firebase-tools@latest deploy --only firestore + +# To deploy just rules +npx -y firebase-tools@latest deploy --only firestore:rules + +# To deploy just indexes +npx -y firebase-tools@latest deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +npx -y firebase-tools@latest emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). diff --git a/.agents/skills/firebase-firestore-standard/references/security_rules.md b/.agents/skills/firebase-firestore-standard/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md new file mode 100644 index 0000000..3d85134 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md @@ -0,0 +1,183 @@ +# Firestore Web SDK Usage Guide + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +## Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'npx -y firebase-tools@latest apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); + +``` + +## Writing Data + +### Set a Document (`setDoc`) +Creates a document if it doesn't exist, or overwrites it if it does. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +### Add a Document with Auto-ID (`addDoc`) +Use when you don't care about the document ID. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +### Update a Document (`updateDoc`) +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +## Reading Data + +### Get a Single Document (`getDoc`) + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +### Get Multiple Documents (`getDocs`) +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + // doc.data() is never undefined for query doc snapshots + console.log(doc.id, " => ", doc.data()); +}); +``` + +## Realtime Updates + +### Listen to a Document/Query (`onSnapshot`) + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// Stop listening +// unsub(); +``` + +### Handle Changes (Added/Modified/Removed) + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +## Queries + +### Simple and Compound Queries +Use `query()` to combine filters. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires an index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +### Order and Limit +Sort and limit results. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` diff --git a/.agents/skills/firebase-hosting-basics/SKILL.md b/.agents/skills/firebase-hosting-basics/SKILL.md new file mode 100644 index 0000000..a83ac28 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/SKILL.md @@ -0,0 +1,46 @@ +--- +name: firebase-hosting-basics +description: Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting. +--- + +# hosting-basics + +This skill provides instructions and references for working with Firebase Hosting, a fast and secure hosting service for your web app, static and dynamic content, and microservices. + +## Overview + +Firebase Hosting provides production-grade web content hosting for developers. With a single command, you can deploy web apps and serve both static and dynamic content to a global CDN (content delivery network). + +**Key Features:** +- **Fast Content Delivery:** Files are cached on SSDs at CDN edges around the world. +- **Secure by Default:** Zero-configuration SSL is built-in. +- **Preview Channels:** View and test changes on temporary preview URLs before deploying live. +- **GitHub Integration:** Automate previews and deploys with GitHub Actions. +- **Dynamic Content:** Serve dynamic content and microservices using Cloud Functions or Cloud Run. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Instructions + +### 1. Configuration (`firebase.json`) +For details on configuring Hosting behavior, including public directories, redirects, rewrites, and headers, see [configuration.md](references/configuration.md). + +### 2. Deploying +For instructions on deploying your site, using preview channels, and managing releases, see [deploying.md](references/deploying.md). + +### 3. Emulation +To test your app locally: +```bash +npx -y firebase-tools@latest emulators:start --only hosting +``` +This serves your app at `http://localhost:5000` by default. diff --git a/.agents/skills/firebase-hosting-basics/references/configuration.md b/.agents/skills/firebase-hosting-basics/references/configuration.md new file mode 100644 index 0000000..adb9050 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/configuration.md @@ -0,0 +1,101 @@ +# Hosting Configuration (`firebase.json`) + +The `hosting` section of `firebase.json` configures how your site is deployed and served. + +## Key Attributes + +### `public` (Required) +Specifies the directory to deploy to Firebase Hosting. +```json +"hosting": { + "public": "public" +} +``` + +### `ignore` (Optional) +Files to ignore on deploy. Uses glob patterns (like `.gitignore`). +**Default ignores:** `firebase.json`, `**/.*`, `**/node_modules/**` + +### `redirects` (Optional) +URL redirects to prevent broken links or shorten URLs. +```json +"redirects": [ + { + "source": "/foo", + "destination": "/bar", + "type": 301 + } +] +``` + +### `rewrites` (Optional) +Serve the same content for multiple URLs, useful for SPAs or Dynamic Content. +```json +"rewrites": [ + { + "source": "**", + "destination": "/index.html" + }, + { + "source": "/api/**", + "function": "apiFunction" + }, + { + "source": "/container/**", + "run": { + "serviceId": "helloworld", + "region": "us-central1" + } + } +] +``` + +### `headers` (Optional) +Custom response headers. +```json +"headers": [ + { + "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)", + "headers": [ + { + "key": "Access-Control-Allow-Origin", + "value": "*" + } + ] + } +] +``` + +### `cleanUrls` (Optional) +If `true`, drops `.html` extension from URLs. +```json +"cleanUrls": true +``` + +### `trailingSlash` (Optional) +Controls trailing slashes in static content URLs. +- `true`: Adds trailing slash. +- `false`: Removes trailing slash. + +## Full Example + +```json +{ + "hosting": { + "public": "dist", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ], + "cleanUrls": true, + "trailingSlash": false + } +} +``` diff --git a/.agents/skills/firebase-hosting-basics/references/deploying.md b/.agents/skills/firebase-hosting-basics/references/deploying.md new file mode 100644 index 0000000..df26c5e --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/deploying.md @@ -0,0 +1,39 @@ +# Deploying to Firebase Hosting + +## Standard Deployment +To deploy your Hosting content and configuration to your live site: + +```bash +npx -y firebase-tools@latest deploy --only hosting +``` + +This deploys to your default sites (`PROJECT_ID.web.app` and `PROJECT_ID.firebaseapp.com`). + +## Preview Channels +Preview channels allow you to test changes on a temporary URL before going live. + +### Deploy to a Preview Channel +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID +``` +Replace `CHANNEL_ID` with a name (e.g., `feature-beta`). +This returns a preview URL like `PROJECT_ID--CHANNEL_ID-RANDOM_HASH.web.app`. + +### Expiration +Channels expire after 7 days by default. To set a different expiration: +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID --expires 1d +``` + +## Cloning to Live +You can promote a version from a preview channel to your live channel without rebuilding. + +```bash +npx -y firebase-tools@latest hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL_ID TARGET_SITE_ID:live +``` + +**Example:** +Clone the `feature-beta` channel on your default site to live: +```bash +npx -y firebase-tools@latest hosting:clone my-project:feature-beta my-project:live +``` diff --git a/.agents/skills/firestore-security-rules-auditor/SKILL.md b/.agents/skills/firestore-security-rules-auditor/SKILL.md new file mode 100644 index 0000000..dbc60af --- /dev/null +++ b/.agents/skills/firestore-security-rules-auditor/SKILL.md @@ -0,0 +1,45 @@ +--- +name: firestore-security-rules-auditor +description: A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust. +--- + +# Overview +This skill acts as an auditor for Firebase Security Rules, evaluating them against a rigorous set of criteria to ensure they are secure, robust, and correctly implemented. + +# Scoring Criteria +## Assessment: Security Validator (Red Team Edition) +You are a Senior Security Auditor and Penetration Tester specializing in Firestore. Your goal is to find "the hole in the wall." Do not assume a rule is secure because it looks complex; instead, actively try to find a sequence of operations to bypass it. + +### Mandatory Audit Checklist: +1. **The Update Bypass:** Compare 'create' and 'update' rules. Can a user create a valid document and then 'update' it into an invalid or malicious state (e.g., changing their role, bypassing size limits, or corrupting data types)? +2. **Authority Source:** Does the security rely on user-provided data (request.resource.data) for sensitive fields like 'role', 'isAdmin', or 'ownerId'? Carefully consider the source for that authority. +3. **Business Logic vs. Rules:** Does the rule set actually support the app's purpose? (e.g., In a collaboration app, can collaborators actually read the data? If not, the rules are "broken" or will force insecure workarounds). +4. **Storage Abuse:** Are there string length or array size limits? If not, label it as a "Resource Exhaustion/DoS" risk. +5. **Type Safety:** Are fields checked with 'is string', 'is int', or 'is timestamp'? +6. **Field-Level vs. Identity-Level Security:** Be careful with rules that use \`hasOnly()\` or \`diff()\`. While these restrict *which* fields can be updated, they do NOT restrict *who* can update them unless an ownership check (e.g., \`resource.data.uid == request.auth.uid\`) is also present. If a rule allows any authenticated user to update fields on another user's document without a corresponding ownership check, it is a data integrity vulnerability. + +### Admin Bootstrapping & Privileges: +The admin bootstrapping process is limited in this app. If the rules use a single hardcoded admin email (e.g., checking request.auth.token.email == 'admin@example.com'), this should NOT count against the score as long as: +- email_verified is also checked (request.auth.token.email_verified == true). +- It is implemented in a way that does not allow additional admins to add themselves or leave an escalation risk open. + +### Scoring Criteria (1-5): +- **1 (Critical):** Unauthorized data access (leaks), privilege escalation, or total validation bypass. +- **2 (Major):** Broken business logic, self-assigned roles, bypass of controls. +- **3 (Moderate):** PII exposure (e.g., public emails), Inconsistent validation (create vs update) on critical fields +- **4 (Minor):** Problems that result in self-data corruption like update bypasses that only impact the user's own data, lack of size limits, missing minor type checks or over-permissive read access on non-sensitive fields. +- **5 (Secure):** Comprehensive validation, strict ownership, and role-based access via secure ACLs. + +Return your assessment in JSON format using the following structure: +{ + "score": 1-5, + "summary": "overall assessment", + "findings": [ + { + "check": "checklist item", + "severity": "critical|major|moderate|minor", + "issue": "description", + "recommendation": "fix" + } + ] +} \ No newline at end of file diff --git a/.claude/skills/developing-genkit-dart/SKILL.md b/.claude/skills/developing-genkit-dart/SKILL.md new file mode 100644 index 0000000..706023b --- /dev/null +++ b/.claude/skills/developing-genkit-dart/SKILL.md @@ -0,0 +1,57 @@ +--- +name: developing-genkit-dart +description: Generates code and provides documentation for the Genkit Dart SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or integrate LLMs into Dart/Flutter applications. +metadata: + genkit-managed: true +--- + +# Genkit Dart + +Genkit Dart is an AI SDK for Dart that provides a unified interface for code generation, structured outputs, tools, flows, and AI agents. + +## Core Features and Usage +If you need help with initializing Genkit (`Genkit()`), Generation (`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings (`ai.embedMany`), streaming, or calling remote flow endpoints, please load the core framework reference: +[references/genkit.md](references/genkit.md) + +## Genkit CLI (recommended) + +The Genkit CLI provides a local development UI for running Flow, tracing executions, playing with models, and evaluating outputs. + +check if the user has it installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash # Native CLI +# OR +npm install -g genkit-cli # Via npm +``` + +**Usage:** +Wrap your run command with `genkit start` to attach the Genkit developer UI and tracing: +```bash +genkit start -- dart run main.dart +``` + +## Plugin Ecosystem +Genkit relies on a large suite of plugins to perform generative AI actions, interface with external LLMs, or host web servers. + +When asked to use any given plugin, always verify usage by referring to its corresponding reference below. You should load the reference when you need to know the specific initialization arguments, tools, models, and usage patterns for the plugin: + +| Plugin Name | Reference Link | Description | +| ---- | ---- | ---- | +| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. | +| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. | +| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. | +| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. | +| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). | +| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. | +| `genkit_shelf` | [references/genkit_shelf.md](references/genkit_shelf.md) | Load for Integrating Genkit Flow actions over HTTP using Dart Shelf. | +| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). | + +## External Dependencies +Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you must use the [schemantic](https://pub.dev/packages/schemantic) library. +To learn how to use schemantic, ensure you read [references/schemantic.md](references/schemantic.md) for how to implement type safe generated Dart code. This is particularly relevant when you encounter symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix. Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill to understand for using Genkit Dart. + +## Best Practices +- Always check that code cleanly compiles using `dart analyze` before generating the final response. +- Always use the Genkit CLI for local development and debugging. diff --git a/.claude/skills/developing-genkit-dart/references/genkit.md b/.claude/skills/developing-genkit-dart/references/genkit.md new file mode 100644 index 0000000..7dd33e5 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit.md @@ -0,0 +1,380 @@ +# Genkit Core Framework + +Genkit Dart is an AI SDK for Dart that provides a unified interface for text generation, structured output, tool calling, and agentic workflows. + +## Initialization + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; // Or any other plugin + +void main() async { + // Pass plugins to use into the Genkit constructor + final ai = Genkit(plugins: [googleAI()]); +} +``` + +## Generate Text + +```dart +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), // Needs a model reference from a plugin + prompt: 'Explain quantum computing in simple terms.', +); + +print(response.text); +``` + +## Stream Responses +```dart +final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a short story about a robot learning to paint.', +); + +await for (final chunk in stream) { + print(chunk.text); +} +``` + +## Embed Text +```dart +final embeddings = await ai.embedMany( + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], + embedder: googleAI.textEmbedding('text-embedding-004'), +); + +print(embeddings.first.embedding); +``` + +## Define Tools +Models can use define actions and access external data via custom defined tools. +Requires the `schemantic` library for schema definitions. + +```dart +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $WeatherInput { + String get location; +} + +final weatherTool = ai.defineTool( + name: 'getWeather', + description: 'Gets the current weather for a location', + inputSchema: WeatherInput.$schema, + fn: (input, _) async { + // Call your weather API here + return 'Weather in ${input.location}: 72°F and sunny'; + }, +); + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'What\'s the weather like in San Francisco?', + toolNames: ['getWeather'], // Use the tools +); +``` + +## Structured Output + +You can ensure the generative model returns a typed JSON object by providing an `outputSchema`. + +```dart +@Schema() +abstract class $Person { + String get name; + int get age; +} + +// ... inside main ... + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Generate a person named John Doe, age 30', + outputSchema: Person.$schema, // Force the model to return this schema +); + +final person = response.output; // Typed Person object +print('Name: ${person.name}, Age: ${person.age}'); +``` + +## Define Flows +Wrap your AI logic in flows for better observability, testing, and deployment: + +```dart +final jokeFlow = ai.defineFlow( + name: 'tellJoke', + inputSchema: .string(), + outputSchema: .string(), + fn: (topic, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about $topic', + ); + return response.text; // Value return + }, +); + +final joke = await jokeFlow('programming'); +print(joke); +``` + +### Streaming Flows +Stream data from your flows using `context.sendChunk(...)` and returning the final value: + +```dart +final streamStory = ai.defineFlow( + name: 'streamStory', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), + fn: (topic, context) async { + final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a story about $topic', + ); + + await for (final chunk in stream) { + context.sendChunk(chunk.text); // Stream the chunks + } + return 'Story complete'; // Value return + }, +); +``` + +## Calling remote Flows from a dart client +The `genkit` package provides `package:genkit/client.dart` representing remote Genkit actions that can be invoked or streamed using type-safe definitions. + +1. Defines a remote action +```dart +import 'package:genkit/client.dart'; + +final stringAction = defineRemoteAction( + url: 'http://localhost:3400/my-flow', + inputSchema: .string(), + outputSchema: .string(), +); +``` + +2. Call the Remote Action (Non-streaming) +```dart +final response = await stringAction(input: 'Hello from Dart!'); +print('Flow Response: $response'); +``` + +3. Call the Remote Action (Streaming) +Use the `.stream()` method on the action flow, and access `stream.onResult` to wait on the async return value. +```dart +final streamAction = defineRemoteAction( + url: 'http://localhost:3400/stream-story', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), +); + +final stream = streamAction.stream( + input: 'Tell me a short story about a Dart developer.', +); + +await for (final chunk in stream) { + print('Chunk: $chunk'); +} + +final finalResult = await stream.onResult; +print('\nFinal Response: $finalResult'); +``` + +## Calling remote Flows from a Javascript client + +Install `genkit` npm package: + +```bash +npm install genkit +``` + +1. Call a remote flow (non-streaming) + +```ts +import { runFlow } from 'genkit/beta/client'; + +async function callHelloFlow() { + try { + const result = await runFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Genkit User' }, + }); + console.log('Non-streaming result:', result.greeting); + } catch (error) { + console.error('Error calling helloFlow:', error); + } +} + +callHelloFlow(); +``` + +2. Call a remote flow (streaming) + +```ts +import { streamFlow } from 'genkit/beta/client'; + +async function streamHelloFlow() { + try { + const result = streamFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Streaming User' }, + }); + + // Process the stream chunks as they arrive + for await (const chunk of result.stream) { + console.log('Stream chunk:', chunk); + } + + // Get the final complete response + const finalOutput = await result.output; + console.log('Final streaming output:', finalOutput.greeting); + } catch (error) { + console.error('Error streaming helloFlow:', error); + } +} + +streamHelloFlow(); +``` + +## Data Models + +Genkit uses standard data models for representing prompts (messages & parts) and responses. These classes are implemented using schemantic library. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $MyDataModel { + // uses Genkit's Message schema (not schemantic's Message) + List<$Message> get messages; + List<$Part> get parts; +} + +void example() { + // --- Parts --- + // A Text part + final textPart = TextPart(text: 'some text', metadata: {'foo': 'bar'}); + + // A Media/Image part + final mediaPart = MediaPart( + media: Media(url: 'https://...', contentType: 'image/png'), + metadata: {'foo': 'bar'}, + ); + + // A Tool Request initiated by the model + final toolRequestPart = ToolRequestPart( + toolRequest: ToolRequest( + name: 'get_weather', + ref: 'abc', + input: {'location': 'Paris, France'}, + ), + metadata: {'foo': 'bar'}, + ); + + // The resulting data from a Tool execution + final toolResponsePart = ToolResponsePart( + toolResponse: ToolResponse( + name: 'get_weather', + ref: 'abc', + output: {'temperature': '20C'}, + ), + metadata: {'foo': 'bar'}, + ); + + // Model reasoning (e.g. for Claude's "thinking" models) + final reasoningPart = ReasoningPart( + reasoning: 'thinking...', + metadata: {'foo': 'bar'}, + ); + + // A custom fallback part + final customPart = CustomPart( + custom: {'provider': {'specific': 'data'}}, + metadata: {'foo': 'bar'}, + ); + + // --- Messages --- + final systemMessage = Message( + role: Role.system, + content: [textPart, mediaPart], + metadata: {'foo': 'bar'}, + ); + + final userMessage = Message( + role: Role.user, + content: [textPart, mediaPart], // Can contain media (multimodal) + ); + + final modelMessage = Message( + role: Role.model, + // Models can emit text, tool requests, reasoning, or custom parts + content: [textPart, toolRequestPart, reasoningPart, customPart], + ); + + // --- Ergonomic Data Access (schema_extensions.dart) --- + // The Genkit SDK provides extensions on `Message` and `Part` to easily access fields + // without needing to cast them manually. + + // Get concatenated text from all TextParts in a Message + print(modelMessage.text); + + // Get the first Media object from a Message + print(modelMessage.media?.url); + + // Iterate over tool requests in a Message + for (final toolReq in modelMessage.toolRequests) { + print(toolReq.name); + } + + // Inspect individual parts + for (final part in modelMessage.content) { + if (part.isText) print(part.text); + if (part.isMedia) print(part.media?.url); + if (part.isToolRequest) print(part.toolRequest?.name); + if (part.isToolResponse) print(part.toolResponse?.name); + if (part.isReasoning) print(part.reasoning); + if (part.isCustom) print(part.custom); + } + + // --- Streaming Chunks --- + // Data emitted by ai.generateStream() calls + final generateResponseChunk = ModelResponseChunk( + content: [textPart], + index: 0, // Index of the message this chunk belongs to + aggregated: false, + ); + + // Chunks also have text and media accessors + print(generateResponseChunk.text); + + // --- Advanced: Schemas --- + // Use Genkit type schemas directly in Schemantic validations + final messageSchema = Message.$schema; + final partSchema = Part.$schema; + + final mySchema = SchemanticType.map( + .string(), + .list(Message.$schema), // Requires a list of Messages + ); + + // --- Generate Response --- + // ai.generate() returns a GenerateResponseHelper which provides ergonomic getters + // over the underlying ModelResponse: + final response = await ai.generate(...); + + print(response.text); // Concatenated text + print(response.media?.url); // First media part + print(response.toolRequests); // All tool requests + print(response.interrupts); // Tool requests that triggered an interrupt + print(response.messages); // Full history of the conversation, including the request and response + print(response.output); // Structured typed output (if outputSchema was used) +} +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_anthropic.md b/.claude/skills/developing-genkit-dart/references/genkit_anthropic.md new file mode 100644 index 0000000..2e420a3 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_anthropic.md @@ -0,0 +1,41 @@ +# Genkit Anthropic Plugin (`genkit_anthropic`) + +The Anthropic plugin for Genkit Dart, used for interacting with the Claude models. + +## Usage + +Requires `ANTHROPIC_API_KEY` to be passed to the init block. + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_anthropic/genkit_anthropic.dart'; + +void main() async { + final ai = Genkit( + plugins: [anthropic(apiKey: Platform.environment['ANTHROPIC_API_KEY']!)], + ); + + final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Claude Thinking Configurations + +Provides specific configurations for utilizing Claude 3.7+ "thinking" model capabilities. + +```dart +final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Solve this 24 game: 2, 3, 10, 10', + config: AnthropicOptions(thinking: ThinkingConfig(budgetTokens: 2048)), +); + +// The thinking content is available in the message parts +print(response.message?.content); +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_chrome.md b/.claude/skills/developing-genkit-dart/references/genkit_chrome.md new file mode 100644 index 0000000..8152369 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_chrome.md @@ -0,0 +1,23 @@ +# Genkit Chrome AI Plugin (`genkit_chrome`) + +Chrome Built-in AI (Gemini Nano) plugin for Genkit Dart, allowing local offline execution within a Chrome application. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_chrome/genkit_chrome.dart'; + +void main() async { + final ai = Genkit(plugins: [ChromeAIPlugin()]); + + final stream = ai.generateStream( + model: modelRef('chrome/gemini-nano'), + prompt: 'Write a story about a robot.', + ); + + await for (final chunk in stream) { + print(chunk.text); + } +} +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_firebase_ai.md b/.claude/skills/developing-genkit-dart/references/genkit_firebase_ai.md new file mode 100644 index 0000000..7ec462d --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_firebase_ai.md @@ -0,0 +1,23 @@ +# Genkit Firebase AI Plugin (`genkit_firebase_ai`) + +The Firebase AI plugin for Genkit Dart, used for interacting with Gemini APIs through Firebase AI Logic. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_firebase_ai/genkit_firebase_ai.dart'; + +void main() async { + // Initialize Genkit with the Firebase AI plugin + final ai = Genkit(plugins: [firebaseAI()]); + + // Generate text + final response = await ai.generate( + model: firebaseAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_google_genai.md b/.claude/skills/developing-genkit-dart/references/genkit_google_genai.md new file mode 100644 index 0000000..92d3ec4 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_google_genai.md @@ -0,0 +1,95 @@ +# Genkit Google GenAI Plugin (`genkit_google_genai`) + +The Google AI plugin provides an interface against the official Google AI Gemini API. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; + +void main() async { + // Initialize Genkit with the Google AI plugin + final ai = Genkit(plugins: [googleAI()]); + + // Generate text + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Embeddings + +```dart +final embeddings = await ai.embedMany( + embedder: googleAI.textEmbedding('text-embedding-004'), + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], +); +``` + +## Image Generation + +The plugin also supports image generation models such as `gemini-2.5-flash-image`. + +### Example (Nano Banana) + +```dart +// Define an image generation flow +ai.defineFlow( + name: 'imageGenerator', + inputSchema: .string(defaultValue: 'A banana riding a bike'), + outputSchema: Media.$schema, + fn: (input, context) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-image'), + prompt: input, + ); + if (response.media == null) { + throw Exception('No media generated'); + } + return response.media!; + }, +); +``` + +The media (url field) contain base64 encoded data uri. You can decode it and save it as a file. + +## Text-to-Speech (TTS) + +You can use text-to-speech models to generate audio from text. The generated `Media` object will contain base64 encoded PCM audio in its data URI. + +```dart +// Define a TTS flow +ai.defineFlow( + name: 'textToSpeech', + inputSchema: .string(defaultValue: 'Genkit is an amazing AI framework!'), + outputSchema: Media.$schema, + fn: (prompt, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-preview-tts'), + prompt: prompt, + config: GeminiTtsOptions( + responseModalities: ['AUDIO'], + speechConfig: SpeechConfig( + voiceConfig: VoiceConfig( + prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Puck'), + ), + ), + ), + ); + + if (response.media != null) { + return response.media!; + } + throw Exception('No audio generated'); + }, +); +``` + +Google AI also supports multi-speaker TTS by configuring a `MultiSpeakerVoiceConfig` inside `SpeechConfig`. diff --git a/.claude/skills/developing-genkit-dart/references/genkit_mcp.md b/.claude/skills/developing-genkit-dart/references/genkit_mcp.md new file mode 100644 index 0000000..ce8ddb0 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_mcp.md @@ -0,0 +1,115 @@ +# Genkit MCP (`genkit_mcp`) + +MCP (Model Context Protocol) integration for Genkit Dart. + +## MCP Host (Recommended) +Connect to one or more MCP servers and aggregate their capabilities into the Genkit registry automatically. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final host = defineMcpHost( + ai, + McpHostOptionsWithCache( + name: 'my-host', + mcpServers: { + 'fs': McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + }, + ), + ); + + // Tools can be discovered and executed dynamically using a wildcard... + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Summarize the contents of README.md', + toolNames: ['my-host:tool/fs/*'], + ); + + // ...or by specifying the exact tool name + final exactResponse = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read README.md', + toolNames: ['my-host:tool/fs/read_file'], + ); +} +``` + +## MCP Client (Advanced / Single Server) +Connecting to a single MCP server with a client object is an advanced usecase for when you need manual control over the client lifecycle. Standalone clients do not automatically register tools into the registry, so they must be passed into `generate` or `defineDynamicActionProvider` manually. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final client = createMcpClient( + McpClientOptions( + name: 'my-client', + mcpServer: McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + ), + ); + + await client.ready(); + + // Retrieve the tools from the connected client + final tools = await client.getActiveTools(ai); + + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read the contents of README.md', + tools: tools, + ); +} +``` + +## MCP Server +Expose Genkit actions (tools, prompts, resources) over MCP. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + ai.defineTool( + name: 'add', + description: 'Add two numbers together', + inputSchema: .map(.string(), .dynamicSChema()), + fn: (input, _) async => (input['a'] + input['b']).toString(), + ); + + ai.defineResource( + name: 'my-resource', + uri: 'my://resource', + fn: (_, _) async => ResourceOutput(content: [TextPart(text: 'my resource')]), + ); + + // Stdio transport by default + final server = createMcpServer(ai, McpServerOptions(name: 'my-server')); + await server.start(); +} +``` + +### Streamable HTTP Transport +```dart +import 'dart:io'; + +final transport = await StreamableHttpServerTransport.bind( + address: InternetAddress.loopbackIPv4, + port: 3000, +); +await server.start(transport); +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_middleware.md b/.claude/skills/developing-genkit-dart/references/genkit_middleware.md new file mode 100644 index 0000000..24cff79 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_middleware.md @@ -0,0 +1,84 @@ +# Genkit Middleware (`genkit_middleware`) + +A collection of useful middleware for Genkit Dart to enhance your agent's capabilities. Register plugins when initializing Genkit: + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_middleware/genkit_middleware.dart'; + +void main() { + final ai = Genkit( + plugins: [ + FilesystemPlugin(), + SkillsPlugin(), + ToolApprovalPlugin(), + ], + ); +} +``` + +## Filesystem Middleware +Allows the agent to list, read, write, and search/replace files within a restricted root directory. + +```dart +final response = await ai.generate( + prompt: 'Check the logs in the current directory.', + use: [ + filesystem(rootDirectory: '/path/to/secure/workspace'), + ], +); +``` + +**Tools Provided:** +- `list_files`, `read_file`, `write_file`, `search_and_replace` + +## Skills Middleware +Injects specialized instructions (skills) into the system prompt from `SKILL.md` files located in specified directories. + +```dart +final response = await ai.generate( + prompt: 'Help me debug this issue.', + use: [ + skills(skillPaths: ['/path/to/skills']), + ], +); +``` + +**Tools Provided:** +- `use_skill`: Retrieve the full content of a skill by name. + +## Tool Approval Middleware +Intercepts tool execution for specified tools and requires explicit approval. Returns `FinishReason.interrupted`. + +```dart +final response = await ai.generate( + prompt: 'Delete the database.', + use: [ + // Require approval for all tools EXCEPT those below + toolApproval(approved: ['read_file', 'list_files']), + ], +); + +if (response.finishReason == FinishReason.interrupted) { + final interrupt = response.interrupts.first; + + // Ask user for approval + final isApproved = await askUser(); + + if (isApproved) { + final resumeResponse = await ai.generate( + messages: response.messages, // Pass history + toolChoice: ToolChoice.none, // Prevent immediate re-call + interruptRestart: [ + ToolRequestPart( + toolRequest: interrupt.toolRequest, + metadata: { + ...?interrupt.metadata, + 'tool-approved': true + }, + ), + ], + ); + } +} +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_openai.md b/.claude/skills/developing-genkit-dart/references/genkit_openai.md new file mode 100644 index 0000000..42344db --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_openai.md @@ -0,0 +1,54 @@ +# Genkit OpenAI Plugin (`genkit_openai`) + +OpenAI-compatible API plugin for Genkit Dart. Supports OpenAI models and other compatible APIs (xAI, DeepSeek, Together AI, Groq, etc.). + +## Basic Usage + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_openai/genkit_openai.dart'; + +void main() async { + final ai = Genkit(plugins: [ + openAI(apiKey: Platform.environment['OPENAI_API_KEY']), + ]); + + final response = await ai.generate( + model: openAI.model('gpt-4o'), + prompt: 'Tell me a joke.', + ); +} +``` + +## Options + +`OpenAIOptions` allows configuring sampling temperature, nucleus sampling, token generation, seed, etc: +`config: OpenAIOptions(temperature: 0.7, maxTokens: 100)` + +## Groq API override + +Specify custom `baseUrl` and custom models to integrate with third-party providers. + +```dart +final ai = Genkit(plugins: [ + openAI( + apiKey: Platform.environment['GROQ_API_KEY'], + baseUrl: 'https://api.groq.com/openai/v1', + models: [ + CustomModelDefinition( + name: 'llama-3.3-70b-versatile', + info: ModelInfo( + label: 'Llama 3.3 70B', + supports: {'multiturn': true, 'tools': true, 'systemRole': true}, + ), + ), + ], + ), +]); + +final response = await ai.generate( + model: openAI.model('llama-3.3-70b-versatile'), + prompt: 'Hello!', +); +``` diff --git a/.claude/skills/developing-genkit-dart/references/genkit_shelf.md b/.claude/skills/developing-genkit-dart/references/genkit_shelf.md new file mode 100644 index 0000000..1887f80 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/genkit_shelf.md @@ -0,0 +1,59 @@ +# Genkit Shelf Plugin (`genkit_shelf`) + +Shelf integration for Genkit Dart, used to serve Genkit Flows. + +## Standalone Server +Serve Genkit Flows easily on an isolated HTTP server using `startFlowServer`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + await startFlowServer( + flows: [flow], + port: 8080, + ); +} +``` + +## Existing Shelf Application +Mount Genkit Flow endpoints directly to an existing Shelf `Router` using `shelfHandler`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as io; +import 'package:shelf_router/shelf_router.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + final router = Router(); + + // Mount the flow handler at a specific path + router.post('/myFlow', shelfHandler(flow)); + + // Start the server + await io.serve(router.call, 'localhost', 8080); +} +``` + +Access deployed flows using genkit client libraries (from Dart or JS). diff --git a/.claude/skills/developing-genkit-dart/references/schemantic.md b/.claude/skills/developing-genkit-dart/references/schemantic.md new file mode 100644 index 0000000..45939b2 --- /dev/null +++ b/.claude/skills/developing-genkit-dart/references/schemantic.md @@ -0,0 +1,137 @@ +# Schemantic + +Schemantic is a general-purpose Dart library used for defining strongly typed data classes that automatically bind to reusable runtime JSON schemas. It is standard for the `genkit-dart` framework but works independently as well. + +## Core Concepts + +Always use `schemantic` when strongly typed JSON parsing or programmatic schema validation is required. + +- Annotate your abstract classes with `@Schema()`. +- Use the `$` prefix for abstract schema class names (e.g., `abstract class $User`). +- Always run `dart run build_runner build` to generate the `.g.dart` schema files. + +## Installation + +Add dependencies: + +```bash +dart pub add schemantic +``` + +## Basic Usage + +1. **Defining a schema:** + +```dart +import 'package:schemantic/schemantic.dart'; + +part 'my_file.g.dart'; // Must match the filename + +@Schema() +abstract class $MyObj { + String get name; + $MySubObj get subObj; +} + +@Schema() +abstract class $MySubObj { + String get foo; +} +``` + +2. **Using the Generated Class:** + +The builder creates a concrete class `MyObj` (no `$`) with a factory constructor (`MyObj.fromJson`) and a regular constructor. + +```dart +// Creating an instance +final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar')); + +// Serializing to JSON +print(obj.toJson()); + +// Parsing from JSON +final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}}); +``` + +3. **Accessing Schemas at Runtime:** + +The generated data classes have a static `$schema` field (of type `SchemanticType`) which can be used to pass the definition into functions or to extract the raw JSON schema. + +```dart +// Access JSON schema +final schema = MyObj.$schema.jsonSchema; +print(schema.toJson()); + +// Validate arbitrary JSON at runtime +final validationErrors = await schema.validate({'invalid': 'data'}); +``` + +## Primitive Schemas + +When a full data class is not required, Schemantic provides functions to create schemas dynamically. + +```dart +final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0); +final nameSchema = SchemanticType.string(minLength: 2); +final nothingSchema = SchemanticType.voidSchema(); +final anySchema = SchemanticType.dynamicSchema(); + +final userSchema = SchemanticType.map(.string(), .integer()); // Map +final tagsSchema = SchemanticType.list(.string()); // List +``` + +## Union Types (AnyOf) + +To allow a field to accept multiple types, use `@AnyOf`. + +```dart +@Schema() +abstract class $Poly { + @AnyOf([int, String, $MyObj]) + Object? get id; +} +``` + +Schemantic generates a specific helper class (e.g., `PolyId`) to handle the values: + +```dart +final poly1 = Poly(id: PolyId.int(123)); +final poly2 = Poly(id: PolyId.string('abc')); +``` + +## Field Annotations + +You can use specialized annotations for more validation boundaries: + +```dart +@Schema() +abstract class $User { + @IntegerField( + name: 'years_old', // Change JSON key + description: 'Age of the user', + minimum: 0, + defaultValue: 18, + ) + int? get age; + + @StringField( + minLength: 2, + enumValues: ['user', 'admin'], + ) + String get role; +} +``` + +## Recursive Schemas + +For recursive structures (like trees), must use `useRefs: true` inside the generated jsonSchema property. You define it normally: + +```dart +@Schema() +abstract class $Node { + String get id; + List<$Node>? get children; +} +``` +*Note*: `Node.$schema.jsonSchema(useRefs: true)` generates schemas with JSON Schema `$ref`. \ No newline at end of file diff --git a/.claude/skills/developing-genkit-go/SKILL.md b/.claude/skills/developing-genkit-go/SKILL.md new file mode 100644 index 0000000..5e49c35 --- /dev/null +++ b/.claude/skills/developing-genkit-go/SKILL.md @@ -0,0 +1,97 @@ +--- +name: developing-genkit-go +description: Develop AI-powered applications using Genkit in Go. Use when the user asks to build AI features, agents, flows, or tools in Go using Genkit, or when working with Genkit Go code involving generation, prompts, streaming, tool calling, or model providers. +metadata: + genkit-managed: true +--- + +# Genkit Go + +Genkit Go is an AI SDK for Go that provides generation, structured output, streaming, tool calling, prompts, and flows with a unified interface across model providers. + +## Hello World + +```go +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/genkit-ai/genkit/go/ai" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" + "github.com/genkit-ai/genkit/go/plugins/server" +) + +func main() { + ctx := context.Background() + g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) + + genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }) + + mux := http.NewServeMux() + for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) + } + log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +} +``` + +## Core Features + +Load the appropriate reference based on what you need: + +| Feature | Reference | When to load | +| --- | --- | --- | +| Initialization | [references/getting-started.md](references/getting-started.md) | Setting up `genkit.Init`, plugins, the `*Genkit` instance pattern | +| Generation | [references/generation.md](references/generation.md) | `Generate`, `GenerateText`, `GenerateData`, streaming, output formats | +| Prompts | [references/prompts.md](references/prompts.md) | `DefinePrompt`, `DefineDataPrompt`, `.prompt` files, schemas | +| Tools | [references/tools.md](references/tools.md) | `DefineTool`, tool interrupts, `RestartWith`/`RespondWith` | +| Flows & HTTP | [references/flows-and-http.md](references/flows-and-http.md) | `DefineFlow`, `DefineStreamingFlow`, `genkit.Handler`, HTTP serving | +| Model Providers | [references/providers.md](references/providers.md) | Google AI, Vertex AI, Anthropic, OpenAI-compatible, Ollama setup | + +## Genkit CLI + +Check if installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Key commands:** + +```bash +# Start app with Developer UI (tracing, flow testing) at http://localhost:4000 +genkit start -- go run . +genkit start -o -- go run . # also opens browser + +# Run a flow directly from the CLI +genkit flow:run myFlow '{"data": "input"}' +genkit flow:run myFlow '{"data": "input"}' --stream # with streaming +genkit flow:run myFlow '{"data": "input"}' --wait # wait for completion + +# Look up Genkit documentation +genkit docs:search "streaming" go +genkit docs:list go +genkit docs:read go/flows.md +``` + +See [references/getting-started.md](references/getting-started.md) for full CLI and Developer UI details. + +## Key Guidance + +- **Pass `g` explicitly.** The `*Genkit` instance returned by `genkit.Init` is the central registry. Pass it to all Genkit functions rather than storing it as a global. This is a core pattern throughout the SDK. +- **Wrap AI logic in flows.** Flows give you tracing, observability, HTTP deployment via `genkit.Handler`, and the ability to test from the Developer UI and CLI. Any generation call worth keeping should live in a flow. +- **Use `jsonschema:"description=..."` struct tags on output types.** The model uses these descriptions to understand what each field should contain. Without them, structured output quality drops significantly. +- **Write good tool descriptions.** The model decides which tools to call based on their description string. Vague descriptions lead to missed or incorrect tool calls. +- **Use `.prompt` files for complex prompts.** They separate prompt content from Go code, support Handlebars templating, and can be iterated on without recompilation. Code-defined prompts are better for simple, single-line cases. +- **Look up the latest model IDs.** Model names change frequently. Check provider documentation for current model IDs rather than relying on hardcoded names. See [references/providers.md](references/providers.md). diff --git a/.claude/skills/developing-genkit-go/references/flows-and-http.md b/.claude/skills/developing-genkit-go/references/flows-and-http.md new file mode 100644 index 0000000..92f99a2 --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/flows-and-http.md @@ -0,0 +1,183 @@ +# Flows & HTTP + +## DefineFlow + +Wrap AI logic in a flow for observability, tracing, and HTTP deployment. + +```go +jokeFlow := genkit.DefineFlow(g, "jokeFlow", + func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }, +) +``` + +### Running a Flow Directly + +```go +result, err := jokeFlow.Run(ctx, "cats") +``` + +## DefineStreamingFlow + +Flows that stream chunks back to the caller. Two common patterns: + +### Pattern 1: Passthrough Streaming + +Pass the stream callback directly through to `WithStreaming`. The callback type is `ai.ModelStreamCallback` = `func(context.Context, *ai.ModelResponseChunk) error`: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk ai.ModelStreamCallback) (string, error) { + resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ai.WithStreaming(sendChunk), // passthrough + ) + if err != nil { + return "", err + } + return resp.Text(), nil + }, +) +``` + +### Pattern 2: Manual String Streaming + +Use `core.StreamCallback[string]` to stream extracted text: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk core.StreamCallback[string]) (string, error) { + stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ) + for result, err := range stream { + if err != nil { + return "", err + } + if result.Done { + return result.Response.Text(), nil + } + sendChunk(ctx, result.Chunk.Text()) + } + return "", nil + }, +) +``` + +### Typed Streaming Flows + +Use `core.StreamCallback[T]` with `GenerateDataStream` for typed chunks: + +```go +genkit.DefineStreamingFlow(g, "structuredStream", + func(ctx context.Context, input JokeRequest, sendChunk core.StreamCallback[*Joke]) (*Joke, error) { + stream := genkit.GenerateDataStream[*Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", input.Topic), + ) + for result, err := range stream { + if err != nil { return nil, err } + if result.Done { return result.Output, nil } + sendChunk(ctx, result.Chunk) + } + return nil, nil + }, +) +``` + +## Named Sub-Steps + +Use `core.Run` inside a flow for traced sub-steps: + +```go +genkit.DefineFlow(g, "pipeline", + func(ctx context.Context, input string) (string, error) { + subject, err := core.Run(ctx, "extract-subject", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Extract the subject from: %s", input), + ) + }) + if err != nil { return "", err } + + joke, err := core.Run(ctx, "generate-joke", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Tell me a joke about %s", subject), + ) + }) + return joke, err + }, +) +``` + +## HTTP Handlers + +### genkit.Handler + +Convert any flow into an `http.HandlerFunc`: + +```go +mux := http.NewServeMux() +for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) +} +log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +``` + +### Request/Response Format + +**Non-streaming request:** +```bash +curl -X POST http://localhost:8080/jokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Response: `{"result": "Why did the banana go to the doctor?..."}` + +**Streaming request:** +```bash +curl -N -X POST http://localhost:8080/streamingJokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Streaming responses use Server-Sent Events (SSE) format. + +### genkit.HandlerFunc + +For frameworks that expect error-returning handlers: + +```go +handler := genkit.HandlerFunc(myFlow) +// handler is func(http.ResponseWriter, *http.Request) error +``` + +### Context Providers + +Inject request context (e.g., auth headers) into flow execution: + +```go +mux.HandleFunc("POST /myFlow", genkit.Handler(myFlow, + genkit.WithContextProviders(func(ctx context.Context, rd core.RequestData) (api.ActionContext, error) { + // rd.Headers contains HTTP headers + return api.ActionContext{"userId": rd.Headers.Get("X-User-Id")}, nil + }), +)) +``` + +### ListFlows + +Get all registered flows for dynamic route setup: + +```go +flows := genkit.ListFlows(g) // []api.Action +for _, f := range flows { + fmt.Println(f.Name()) +} +``` diff --git a/.claude/skills/developing-genkit-go/references/generation.md b/.claude/skills/developing-genkit-go/references/generation.md new file mode 100644 index 0000000..5934575 --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/generation.md @@ -0,0 +1,176 @@ +# Generation + +## GenerateText + +Simplest form. Returns a string. + +```go +text, err := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +``` + +## Generate + +Returns a full `*ModelResponse` with metadata, usage stats, and history. + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithSystem("You are a helpful assistant."), + ai.WithPrompt("Explain %s", topic), +) +fmt.Println(resp.Text()) // concatenated text +fmt.Println(resp.FinishReason) // ai.FinishReasonStop, etc. +fmt.Println(resp.Usage) // token counts +``` + +## GenerateData (Structured Output) + +Returns a typed Go value parsed from the model's JSON output. + +```go +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup of the joke"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +joke, resp, err := genkit.GenerateData[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +// joke is *Joke, resp is *ModelResponse +``` + +## Streaming + +### GenerateStream + +Returns an iterator. Each value has `.Done`, `.Chunk`, and `.Response`. + +```go +stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long story about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalText := result.Response.Text() + break + } + fmt.Print(result.Chunk.Text()) // incremental text +} +``` + +### GenerateDataStream (Structured Streaming) + +Streams typed partial objects as they arrive. + +```go +stream := genkit.GenerateDataStream[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalJoke := result.Output // *Joke + break + } + partialJoke := result.Chunk // *Joke (partial) +} +``` + +### Callback-Based Streaming + +Use `ai.WithStreaming` with `Generate` for callback-style streaming. The callback receives `*ai.ModelResponseChunk`: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a story"), + ai.WithStreaming(func(ctx context.Context, chunk *ai.ModelResponseChunk) error { + fmt.Print(chunk.Text()) // extract text from chunk + return nil + }), +) +// resp contains the final complete response +``` + +## Common Options + +```go +// Model selection +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)) // model reference +ai.WithModelName("googleai/gemini-flash-latest") // by name string + +// Content +ai.WithPrompt("Tell me about %s", topic) // user message (supports fmt verbs) +ai.WithSystem("You are a pirate.") // system instructions +ai.WithMessages(msg1, msg2) // conversation history +ai.WithDocs(doc1, doc2) // context documents +ai.WithTextDocs("context 1", "context 2") // context as strings + +// Model config (provider-specific) +ai.WithConfig(map[string]any{"temperature": 0.7}) +``` + +## Output Formats + +Control how the model structures its output. + +### By Go Type + +```go +// Automatically uses JSON format and instructs model to match the type +ai.WithOutputType(MyStruct{}) +``` + +### By Format String + +```go +ai.WithOutputFormat(ai.OutputFormatJSON) // single JSON object +ai.WithOutputFormat(ai.OutputFormatJSONL) // JSON Lines (one object per line) +ai.WithOutputFormat(ai.OutputFormatArray) // JSON array +ai.WithOutputFormat(ai.OutputFormatEnum) // constrained enum value +ai.WithOutputFormat(ai.OutputFormatText) // plain text (default) +``` + +### Enum Output + +```go +type Color string +const ( + Red Color = "red" + Green Color = "green" + Blue Color = "blue" +) + +text, err := genkit.GenerateText(ctx, g, + ai.WithPrompt("What color is the sky?"), + ai.WithOutputEnums(Red, Green, Blue), +) +``` + +### Custom Output Instructions + +```go +ai.WithOutputInstructions("Return a JSON object with fields: name (string), age (number)") +``` + +### Combining Format + Schema + +```go +// JSONL with a typed schema (useful for streaming lists) +genkit.DefinePrompt(g, "characters", + ai.WithPrompt("Generate 5 story characters"), + ai.WithOutputType([]StoryCharacter{}), + ai.WithOutputFormat(ai.OutputFormatJSONL), +) +``` diff --git a/.claude/skills/developing-genkit-go/references/getting-started.md b/.claude/skills/developing-genkit-go/references/getting-started.md new file mode 100644 index 0000000..950b616 --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/getting-started.md @@ -0,0 +1,142 @@ +# Getting Started + +## Project Setup + +```bash +mkdir my-genkit-app && cd my-genkit-app +go mod init my-genkit-app +go get github.com/genkit-ai/genkit/go@latest +``` + +Add provider plugin(s) for the models you want to use: +```bash +go get github.com/genkit-ai/genkit/go/plugins/googlegenai # Google AI / Vertex AI +go get github.com/genkit-ai/genkit/go/plugins/anthropic # Anthropic Claude +go get github.com/genkit-ai/genkit/go/plugins/compat_oai # OpenAI-compatible +go get github.com/genkit-ai/genkit/go/plugins/ollama # Ollama (local) +``` + +After writing your code, run `go mod tidy` to resolve all dependencies. + +## Initialization + +Every Genkit app starts with `genkit.Init`, which returns a `*Genkit` instance: + +```go +import ( + "context" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" +) + +ctx := context.Background() +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), +) +``` + +### The `*Genkit` Instance + +The `*Genkit` value `g` is the central registry. Pass it to every Genkit function: + +```go +// Defining resources +genkit.DefineFlow(g, "myFlow", ...) +genkit.DefineTool(g, "myTool", ...) +genkit.DefinePrompt(g, "myPrompt", ...) + +// Generating content +genkit.GenerateText(ctx, g, ...) +genkit.Generate(ctx, g, ...) +``` + +Do not store `g` in a global variable. Pass it explicitly through your call chain. + +### Init Options + +```go +g := genkit.Init(ctx, + // Register one or more plugins + genkit.WithPlugins(&googlegenai.GoogleAI{}, &anthropic.Anthropic{}), + + // Set a default model (used when no model is specified) + genkit.WithDefaultModel("googleai/gemini-flash-latest"), + + // Set directory for .prompt files (default: "prompts") + genkit.WithPromptDir("my-prompts"), + + // Or embed prompts using Go's embed package + // genkit.WithPromptFS(promptsFS), +) +``` + +### Embedding Prompts + +Use `go:embed` to bundle `.prompt` files into the binary: + +```go +//go:embed prompts +var promptsFS embed.FS + +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), + genkit.WithPromptFS(promptsFS), +) +``` + +## Genkit CLI + +The Genkit CLI provides a local Developer UI for running flows, tracing executions, and inspecting model interactions. + +**Install:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Verify:** +```bash +genkit --version +``` + +### Developer UI + +Start your app with the Developer UI attached: + +```bash +genkit start -- go run . +``` + +This launches: +- Your app (with tracing enabled) +- The Developer UI at `http://localhost:4000` +- A telemetry API at `http://localhost:4033` + +Add `-o` to auto-open the UI in your browser: +```bash +genkit start -o -- go run . +``` + +The Developer UI lets you: +- Run and test flows interactively +- View traces for each generation call (inputs, outputs, latency, token usage) +- Inspect prompt rendering and tool calls +- Debug multi-step flows with per-step trace data + +### Without the CLI + +Set `GENKIT_ENV=dev` to enable the reflection API without the CLI: + +```bash +GENKIT_ENV=dev go run . +``` + +## Import Paths + +```go +import ( + "github.com/genkit-ai/genkit/go/genkit" // Core: Init, Generate*, DefineFlow, etc. + "github.com/genkit-ai/genkit/go/ai" // Types: WithModel, WithPrompt, Message, Part, etc. + "github.com/genkit-ai/genkit/go/core" // Low-level: Run (sub-steps), Flow types + "github.com/genkit-ai/genkit/go/plugins/server" // server.Start for HTTP +) +``` diff --git a/.claude/skills/developing-genkit-go/references/prompts.md b/.claude/skills/developing-genkit-go/references/prompts.md new file mode 100644 index 0000000..610d563 --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/prompts.md @@ -0,0 +1,256 @@ +# Prompts + +## DefinePrompt + +Define a reusable prompt in code with a default model and template. + +```go +jokePrompt := genkit.DefinePrompt(g, "joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithInputType(JokeRequest{Topic: "example"}), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +fmt.Println(resp.Text()) +``` + +### ExecuteStream + +```go +stream := jokePrompt.ExecuteStream(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +for result, err := range stream { + if err != nil { return err } + if result.Done { break } + fmt.Print(result.Chunk.Text()) +} +``` + +### Override Options at Execution + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), + ai.WithModelName("googleai/gemini-pro-latest"), // override model + ai.WithConfig(map[string]any{"temperature": 0.9}), + ai.WithTools(myTool), +) +``` + +## DefineDataPrompt (Typed Input/Output) + +Strongly-typed prompts with Go generics. + +```go +type JokeRequest struct { + Topic string `json:"topic"` +} + +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +jokePrompt := genkit.DefineDataPrompt[JokeRequest, *Joke](g, "structured-joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute (typed) + +```go +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +// joke is *Joke, resp is *ModelResponse +``` + +### ExecuteStream (typed) + +```go +stream := jokePrompt.ExecuteStream(ctx, JokeRequest{Topic: "cats"}) +for result, err := range stream { + if err != nil { return err } + if result.Done { + finalJoke := result.Output // *Joke + break + } + fmt.Print(result.Chunk) // partial *Joke +} +``` + +## .prompt Files (Dotprompt) + +Define prompts in separate files with YAML frontmatter and Handlebars templates. + +### Basic .prompt File + +`prompts/joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string +--- +Tell me a joke about {{topic}}. +``` + +### Load and Use + +```go +// LookupPrompt returns Prompt (untyped: map[string]any input, string output) +jokePrompt := genkit.LookupPrompt(g, "joke") +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +``` + +### Typed .prompt File + +`prompts/structured-joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +config: + thinkingConfig: + thinkingBudget: 0 +input: + schema: JokeRequest +output: + format: json + schema: Joke +--- +Tell me a joke about {{topic}}. +``` + +Register Go types so the .prompt file can reference them by name: +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) + +jokePrompt := genkit.LookupDataPrompt[JokeRequest, *Joke](g, "structured-joke") +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +``` + +### LoadPrompt (Explicit Path) + +```go +prompt := genkit.LoadPrompt(g, "./prompts/countries.prompt", "countries") +resp, err := prompt.Execute(ctx) +``` + +### .prompt File Features + +**Multi-message prompts with roles:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + question: string +--- +{{ role "system" }} +You are a helpful assistant. + +{{ role "user" }} +{{question}} +``` + +**Media in prompts:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + videoUrl: string + contentType: string +--- +{{ role "user" }} +Summarize this video: +{{media url=videoUrl contentType=contentType}} +``` + +**Conditionals and loops:** +``` +--- +input: + schema: + topic: string + dietaryRestrictions?(array): string +--- +Write a recipe about {{topic}}. +{{#if dietaryRestrictions}} +Dietary restrictions: {{#each dietaryRestrictions}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}. +{{/if}} +``` + +**Inline schema in .prompt file:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string + style?: string +output: + format: json + schema: + title: string + body: string + tags(array): string +--- +Write an article about {{topic}}. +{{#if style}}Write in a {{style}} style.{{/if}} +``` + +## Schemas + +### DefineSchemaFor (from Go type) + +Registers a Go struct as a named schema for use in `.prompt` files. + +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) +``` + +The schema name matches the Go type name. Use `jsonschema` struct tags for metadata: + +```go +type Recipe struct { + Title string `json:"title" jsonschema:"description=The recipe title"` + Difficulty string `json:"difficulty" jsonschema:"enum=easy,enum=medium,enum=hard"` + Ingredients []Ingredient `json:"ingredients"` + Steps []string `json:"steps"` +} + +type Ingredient struct { + Name string `json:"name"` + Amount float64 `json:"amount"` + Unit string `json:"unit"` +} +``` + +### DefineSchema (manual JSON Schema) + +```go +genkit.DefineSchema(g, "Recipe", map[string]any{ + "type": "object", + "properties": map[string]any{ + "title": map[string]any{"type": "string"}, + "ingredients": map[string]any{ + "type": "array", + "items": map[string]any{"type": "object"}, + }, + }, + "required": []string{"title", "ingredients"}, +}) +``` diff --git a/.claude/skills/developing-genkit-go/references/providers.md b/.claude/skills/developing-genkit-go/references/providers.md new file mode 100644 index 0000000..dbf137c --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/providers.md @@ -0,0 +1,157 @@ +# Model Providers + +## Google AI (Gemini) + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) +``` + +**Env var:** `GEMINI_API_KEY` or `GOOGLE_API_KEY` + +Model names follow the format `googleai/`. Look up the latest model IDs at https://ai.google.dev/gemini-api/docs/models. + +```go +// By name string +ai.WithModelName("googleai/gemini-flash-latest") + +// Model ref with provider-specific config +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", &genai.GenerateContentConfig{ + ThinkingConfig: &genai.ThinkingConfig{ + ThinkingBudget: genai.Ptr[int32](0), // disable thinking + }, +})) + +// Lookup a model instance +m := googlegenai.GoogleAIModel(g, "gemini-flash-latest") +``` + +## Vertex AI + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.VertexAI{})) +``` + +**Env vars:** `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION` (or `GOOGLE_CLOUD_REGION`) + +Uses Application Default Credentials (`gcloud auth application-default login`). + +Model names follow the format `vertexai/`. Same model IDs as Google AI. + +```go +ai.WithModelName("vertexai/gemini-flash-latest") +``` + +## Anthropic (Claude) + +```go +import ( + "github.com/anthropics/anthropic-sdk-go" // Anthropic SDK types + ant "github.com/genkit-ai/genkit/go/plugins/anthropic" // Genkit plugin +) + +g := genkit.Init(ctx, genkit.WithPlugins(&ant.Anthropic{})) +``` + +**Env var:** `ANTHROPIC_API_KEY` + +Model names follow the format `anthropic/`. Look up the latest model IDs at https://docs.anthropic.com/en/docs/about-claude/models. + +```go +// By name +ai.WithModelName("anthropic/claude-sonnet-4-6") + +// With provider-specific config (uses Anthropic SDK types via ai.WithConfig) +ai.WithConfig(&anthropic.MessageNewParams{ + Temperature: anthropic.Float(1.0), + MaxTokens: *anthropic.IntPtr(2000), + Thinking: anthropic.ThinkingConfigParamUnion{ + OfEnabled: &anthropic.ThinkingConfigEnabledParam{ + BudgetTokens: *anthropic.IntPtr(1024), + }, + }, +}) +``` + +## OpenAI-Compatible (compat_oai) + +Works with any OpenAI-compatible API: OpenAI, DeepSeek, xAI, etc. + +```go +import "github.com/genkit-ai/genkit/go/plugins/compat_oai" + +openaiPlugin := &compat_oai.OpenAICompatible{ + Provider: "openai", // unique identifier + APIKey: os.Getenv("OPENAI_API_KEY"), + // BaseURL: "https://custom-endpoint/v1", // for non-OpenAI providers +} +g := genkit.Init(ctx, genkit.WithPlugins(openaiPlugin)) +``` + +Define models explicitly (not auto-discovered): + +```go +model := openaiPlugin.DefineModel("openai", "gpt-4o", compat_oai.ModelOptions{}) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Ollama (Local Models) + +```go +import "github.com/genkit-ai/genkit/go/plugins/ollama" + +ollamaPlugin := &ollama.Ollama{ + ServerAddress: "http://localhost:11434", + Timeout: 60, // seconds +} +g := genkit.Init(ctx, genkit.WithPlugins(ollamaPlugin)) +``` + +Define models explicitly: + +```go +model := ollamaPlugin.DefineModel(g, + ollama.ModelDefinition{ + Name: "llama3.1", + Type: "chat", // or "generate" + }, + nil, // optional *ModelOptions +) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Multiple Providers + +Register multiple plugins in a single Genkit instance: + +```go +g := genkit.Init(ctx, + genkit.WithPlugins( + &googlegenai.GoogleAI{}, + &ant.Anthropic{}, + ), + genkit.WithDefaultModel("googleai/gemini-flash-latest"), +) + +// Use different models per call +text1, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Hello from Gemini"), +) + +text2, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("anthropic/claude-sonnet-4-6"), + ai.WithPrompt("Hello from Claude"), +) +``` diff --git a/.claude/skills/developing-genkit-go/references/tools.md b/.claude/skills/developing-genkit-go/references/tools.md new file mode 100644 index 0000000..d4a37de --- /dev/null +++ b/.claude/skills/developing-genkit-go/references/tools.md @@ -0,0 +1,178 @@ +# Tools + +## DefineTool + +Define a tool the model can call during generation. + +```go +type WeatherInput struct { + Location string `json:"location" jsonschema:"description=City name"` +} + +type WeatherOutput struct { + Temperature float64 `json:"temperature"` + Conditions string `json:"conditions"` +} + +weatherTool := genkit.DefineTool(g, "getWeather", + "Gets the current weather for a location.", + func(ctx *ai.ToolContext, input WeatherInput) (WeatherOutput, error) { + // Call your weather API + return WeatherOutput{Temperature: 72, Conditions: "sunny"}, nil + }, +) +``` + +## Using Tools in Generation + +Pass tools to `Generate`, `GenerateText`, or prompts: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("What's the weather in San Francisco?"), + ai.WithTools(weatherTool), +) +// The model calls the tool automatically and incorporates the result +fmt.Println(resp.Text()) +``` + +### Tool Choice + +```go +ai.WithToolChoice(ai.ToolChoiceAuto) // model decides (default) +ai.WithToolChoice(ai.ToolChoiceRequired) // model must use a tool +ai.WithToolChoice(ai.ToolChoiceNone) // model cannot use tools +``` + +### Max Turns + +Limit how many tool-call round trips the model can make: + +```go +ai.WithMaxTurns(3) // default is 5 +``` + +## DefineMultipartTool + +Tools that return both structured output and media content: + +```go +screenshotTool := genkit.DefineMultipartTool(g, "screenshot", + "Takes a screenshot of the current page", + func(ctx *ai.ToolContext, input any) (*ai.MultipartToolResponse, error) { + return &ai.MultipartToolResponse{ + Output: map[string]any{"success": true}, + Content: []*ai.Part{ai.NewMediaPart("image/png", base64Data)}, + }, nil + }, +) +``` + +## Tool Interrupts + +Pause tool execution to request human input before continuing. + +### Interrupting + +```go +type TransferInput struct { + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` +} + +type TransferOutput struct { + Status string `json:"status"` + Message string `json:"message"` + Balance float64 `json:"balance"` +} + +type TransferInterrupt struct { + Reason string `json:"reason"` + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` + Balance float64 `json:"balance"` +} + +transferTool := genkit.DefineTool(g, "transferMoney", + "Transfers money to another account.", + func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if input.Amount > accountBalance { + return TransferOutput{}, ai.InterruptWith(ctx, TransferInterrupt{ + Reason: "insufficient_balance", + ToAccount: input.ToAccount, + Amount: input.Amount, + Balance: accountBalance, + }) + } + // Process transfer... + return TransferOutput{Status: "success", Balance: newBalance}, nil + }, +) +``` + +### Handling Interrupts + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithTools(transferTool), + ai.WithPrompt(userRequest), +) + +for resp.FinishReason == ai.FinishReasonInterrupted { + var restarts, responses []*ai.Part + + for _, interrupt := range resp.Interrupts() { + meta, ok := ai.InterruptAs[TransferInterrupt](interrupt) + if !ok { + continue + } + + switch meta.Reason { + case "insufficient_balance": + // RestartWith: re-execute the tool with adjusted input + part, err := transferTool.RestartWith(interrupt, + ai.WithNewInput(TransferInput{ + ToAccount: meta.ToAccount, + Amount: meta.Balance, // transfer what's available + }), + ) + if err != nil { return err } + restarts = append(restarts, part) + + case "confirm_large": + // RespondWith: provide a response directly without re-executing + part, err := transferTool.RespondWith(interrupt, + TransferOutput{Status: "cancelled", Message: "User declined"}, + ) + if err != nil { return err } + responses = append(responses, part) + } + } + + // Continue generation with the resolved interrupts + resp, err = genkit.Generate(ctx, g, + ai.WithMessages(resp.History()...), + ai.WithTools(transferTool), + ai.WithToolRestarts(restarts...), + ai.WithToolResponses(responses...), + ) + if err != nil { return err } +} +``` + +### Checking Resume State + +Inside a tool function, check if the tool is being resumed from an interrupt: + +```go +func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if ctx.IsResumed() { + // This is a resumed call after an interrupt + original, ok := ai.OriginalInputAs[TransferInput](ctx) + // original contains the input from the first call + } + // ... +} +``` diff --git a/.claude/skills/developing-genkit-js/SKILL.md b/.claude/skills/developing-genkit-js/SKILL.md new file mode 100644 index 0000000..d8e1e76 --- /dev/null +++ b/.claude/skills/developing-genkit-js/SKILL.md @@ -0,0 +1,112 @@ +--- +name: developing-genkit-js +description: Develop AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems. +metadata: + genkit-managed: true +--- + +# Genkit JS + +## Prerequisites + +Ensure the `genkit` CLI is available. +- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0** +- If not found or if an older version (1.x < 1.29.0) is present, install/upgrade it: `npm install -g genkit-cli@^1.29.0`. + +**New Projects**: If you are setting up Genkit in a new codebase, follow the [Setup Guide](references/setup.md). + +## Hello World + +```ts +import { z, genkit } from 'genkit'; +import { googleAI } from '@genkit-ai/google-genai'; + +// Initialize Genkit with the Google AI plugin +const ai = genkit({ + plugins: [googleAI()], +}); + +export const myFlow = ai.defineFlow({ + name: 'myFlow', + inputSchema: z.string().default('AI'), + outputSchema: z.string(), +}, async (subject) => { + const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: `Tell me a joke about ${subject}`, + }); + return response.text; +}); +``` + +## Critical: Do Not Trust Internal Knowledge + +Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended: + +```sh +genkit docs:read js/get-started.md +genkit docs:read js/flows.md +``` + +See [Common Errors](references/common-errors.md) for a list of deprecated APIs (e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x replacements. + +**ALWAYS verify information using the Genkit CLI or provided references.** + +## Error Troubleshooting Protocol + +**When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):** + +1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md) +2. Identify if the error matches a known pattern +3. Apply the documented solution +4. Only if not found in common-errors.md, then consult other sources (e.g. `genkit docs:search`) + +**DO NOT:** +- Attempt fixes based on assumptions or internal knowledge +- Skip reading common-errors.md "because you think you know the fix" +- Rely on patterns from pre-1.0 Genkit + +**This protocol is non-negotiable for error handling.** + +## Development Workflow + +1. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.). + - If the user does not specify a provider, default to **Google AI**. + - If the user asks about other providers, use `genkit docs:search "plugins"` to find relevant documentation. +2. **Detect Framework**: Check `package.json` to identify the runtime (Next.js, Firebase, Express). + - Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or `@genkit-ai/google-cloud`. + - Adapt implementation to the specific framework's patterns. +3. **Follow Best Practices**: + - See [Best Practices](references/best-practices.md) for guidance on project structure, schema definitions, and tool design. + - **Be Minimal**: Only specify options that differ from defaults. When unsure, check docs/source. +4. **Ensure Correctness**: + - Run type checks (e.g., `npx tsc --noEmit`) after making changes. + - If type checks fail, consult [Common Errors](references/common-errors.md) before searching source code. +5. **Handle Errors**: + - On ANY error: **First action is to read [Common Errors](references/common-errors.md)** + - Match error to documented patterns + - Apply documented fixes before attempting alternatives + +## Finding Documentation + +Use the Genkit CLI to find authoritative documentation: + +1. **Search topics**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` +2. **List all docs**: `genkit docs:list` +3. **Read a guide**: `genkit docs:read ` + - Example: `genkit docs:read js/flows.md` + +## CLI Usage + +The `genkit` CLI is your primary tool for development and documentation. +- See [CLI Reference](references/docs-and-cli.md) for common tasks, workflows, and command usage. +- Use `genkit --help` for a full list of commands. + +## References + +- [Best Practices](references/best-practices.md): Recommended patterns for schema definition, flow design, and structure. +- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search, CLI tasks, and workflows. +- [Common Errors](references/common-errors.md): Critical "gotchas", migration guide, and troubleshooting. +- [Setup Guide](references/setup.md): Manual setup instructions for new projects. +- [Examples](references/examples.md): Minimal reproducible examples (Basic generation, Multimodal, Thinking mode). diff --git a/.claude/skills/developing-genkit-js/references/best-practices.md b/.claude/skills/developing-genkit-js/references/best-practices.md new file mode 100644 index 0000000..f6e4b7b --- /dev/null +++ b/.claude/skills/developing-genkit-js/references/best-practices.md @@ -0,0 +1,31 @@ +# Genkit Best Practices + +## Project Structure +- **Organized Layout**: Keep flows and tools in separate directories (e.g., `src/flows`, `src/tools`) to maintain a clean codebase. +- **Index Exports**: Use `index.ts` files to export flows and tools, making it easier to import them into your main configuration. + +## Model Selection (Google AI) +- **Gemini Models**: If using Google AI, ALWAYS use the latest generation (`gemini-3-*` or `gemini-2.5-*`). + - **NEVER** use `gemini-2.0-*` or `gemini-1.5-*` series, as they are decommissioned and won't work. + - **Recommended**: `gemini-2.5-flash` or `gemini-3-flash-preview` for general use, `gemini-3.1-pro-preview` for complex tasks. + +## Model Selection (Other Providers) +- **Consult Documentation**: For other providers (OpenAI, Anthropic, etc.), refer to the provider's official documentation for the latest recommended model versions. + +## Schema Definition +- **Use `z` from `genkit`**: Always import `z` from the `genkit` package to ensure compatibility. + ```ts + import { z } from "genkit"; + ``` +- **Descriptive Schemas**: Use `.describe()` on Zod fields. LLMs use these descriptions to understand how to populate the fields. + +## Flow & Tool Design +- **Modularize**: Keep flows and tools in separate files/modules and import them into your main Genkit configuration. +- **Single Responsibility**: Tools should do one thing well. Complex logic should be broken down. + +## Configuration +- **Environment Variables**: Store sensitive keys (like API keys) in environment variables or `.env` files. Do not hardcode them. + +## Development +- **Use Dev Mode**: Run your app with `genkit start -- ` to enable the Developer UI. +- It is recommended to configure a watcher to auto-reload your app (e.g. `node --watch` or `tsx --watch`) diff --git a/.claude/skills/developing-genkit-js/references/common-errors.md b/.claude/skills/developing-genkit-js/references/common-errors.md new file mode 100644 index 0000000..d7162e6 --- /dev/null +++ b/.claude/skills/developing-genkit-js/references/common-errors.md @@ -0,0 +1,132 @@ +# Common Errors & Pitfalls + +## When Typecheck Fails + +**Before searching source code or docs**, check the sections below. Many type errors are caused by deprecated APIs or incorrect imports. + +## Genkit v1.x vs Pre-1.0 Migration + +Genkit v1.x introduced significant API changes. This section covers critical syntax updates. + +### Package Imports + +- **Correct (v1.x)**: Import core functionality (zod, genkit) from the main `genkit` package and plugins from their specific packages. + ```ts + import { z, genkit } from 'genkit'; + import { googleAI } from '@genkit-ai/google-genai'; + ``` + +- **Incorrect (Pre-1.0)**: Importing from `@genkit-ai/ai`, `@genkit-ai/core`, or `@genkit-ai/flow`. These packages are internal/deprecated for direct use. + ```ts + import { genkit } from "@genkit-ai/core"; // INCORRECT + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + ``` + +### Model References + +- **Correct**: Use plugin-specific model factories or string identifiers (prefaced by plugin name). + ```ts + // Using model factory (v1.x - Preferred) + await ai.generate({ model: googleAI.model('gemini-2.5-flash'), ... }); + + // Using string identifier + await ai.generate({ model: 'googleai/gemini-2.5-flash', ...}); + // Or + await ai.generate({ model: 'vertexai/gemini-2.5-flash', ...}); + ``` +- **Incorrect**: Using imported model objects directly or string identifiers without plugin name. + ```ts + await ai.generate({ model: gemini15Pro, ... }); // INCORRECT (Pre-1.0) + await ai.generate({ model: 'gemini-2.5-flash', ... }); // INCORRECT (No plugin prefix) + ``` + +### Model Selection (Gemini) + +- **Preferred**: Use `gemini-2.5-*` models for best performance and features. + ```ts + model: googleAI.model('gemini-2.5-flash') // PREFERRED + ``` +- **DEPRECATED**: `gemini-1.5-*` models are deprecated and will throw errors. + ```ts + model: googleAI.model('gemini-1.5-flash') // ERROR (Deprecated) + ``` + +### Response Access + +- **Correct (v1.x)**: Access properties directly. + ```ts + response.text; // CORRECT + response.output; // CORRECT + ``` +- **Incorrect (Pre-1.0)**: Calling as methods. + ```ts + response.text(); // INCORRECT + response.output(); // INCORRECT + ``` + +### Streaming Generation + +- **Correct (v1.x)**: Do NOT await `generateStream`. Iterate over `stream` directly. Await `response` property for final result. + ```ts + const {stream, response} = ai.generateStream(...); // NO await here + for await (const chunk of stream) { ... } // Iterate stream + const finalResponse = await response; // Await response property + ``` +- **Incorrect (Pre-1.0)**: Calling stream as a function or awaiting the generator incorrectly. + ```ts + for await (const chunk of stream()) { ... } // INCORRECT + await response(); // INCORRECT + ``` + +### Initialization + +- **Correct (v1.x)**: Instantiate `genkit`. + ```ts + const ai = genkit({ plugins: [...] }); + ``` +- **Incorrect (Pre-1.0)**: Global configuration. + ```ts + configureGenkit({ plugins: [...] }); // INCORRECT + ``` + +### Flow Definitions + +- **Correct (v1.x)**: Define flows on the `ai` instance. + ```ts + ai.defineFlow({...}, (input) => {...}); + ``` +- **Incorrect (Pre-1.0)**: Importing `defineFlow` globally. + ```ts + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + +You should never import `@genkit-ai/flow`, `@genkit-ai/ai` or `@genkit-ai/core` packages directly. + +## Zod & Schema Errors + +- **Import Source**: ALWAYS use `import { z } from "genkit"`. + - Using `zod` directly from `zod` package may cause instance mismatches or compatibility issues. +- **Supported Types**: Stick to basic types: scalar (`string`, `number`, `boolean`), `object`, and `array`. + - Avoid complex Zod features unless strictly necessary and verified. +- **Descriptions**: Always use `.describe('...')` for fields in output schemas to guide the LLM. + +## Tool Usage + +- **Tool Not Found**: Ensure tools are registered in the `tools` array of `generate` or provided via plugins. +- **MCP Tools**: Use the `ServerName:tool_name` format when referencing MCP tools. + +## Multimodal & Image Generation + +- **Missing responseModalities**: When using image generation models (like `gemini-2.5-flash-image`), you **MUST** specify the response modalities in the config. + ```ts + config: { + responseModalities: ["TEXT", "IMAGE"] + } + ``` + Failure to do so will result in errors or incorrect output format. + +## Audio & Speech Generation + +- **Raw PCM Data vs MP3**: Some providers (e.g., Google GenAI) return raw PCM data, while others (e.g., OpenAI) return MP3. + - **DO NOT assume MP3 format.** + - **DO NOT embed raw PCM in HTML audio tags.** + - **Action**: Run `genkit docs:search "speech audio"` to find provider-specific conversion steps (e.g., PCM to WAV). diff --git a/.claude/skills/developing-genkit-js/references/docs-and-cli.md b/.claude/skills/developing-genkit-js/references/docs-and-cli.md new file mode 100644 index 0000000..3561721 --- /dev/null +++ b/.claude/skills/developing-genkit-js/references/docs-and-cli.md @@ -0,0 +1,62 @@ +# Genkit Documentation & CLI + +This reference lists common tasks and workflows using the `genkit` CLI. For authoritative command details, always run `genkit --help` or `genkit --help`. + +## Prerequisites: + +Ensure that the CLI is on `genkit-cli` version >= 1.29.0. If not, or if an older version (1.x < 1.29.0) is present, update the Genkit CLI version. Alternatively, to run commands with a specific version or without global installation, prefix them with `npx -y genkit-cli@^1.29.0`. + +## Documentation + +- **Search docs**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` + - Example: `genkit docs:search "rag retrieval"` +- **Read doc**: `genkit docs:read ` + - Example: `genkit docs:read js/overview.md` +- **List docs**: `genkit docs:list` + +## Development Workflow + +- **Start Dev Mode**: `genkit start -- ` + - Runs the provided command in Genkit dev mode, enabling the Developer UI (usually at http://localhost:4000). + - **Node.js (TypeScript)**: + ```bash + genkit start -- npx tsx --watch src/index.ts + ``` + - **Next.js**: + ```bash + genkit start -- npx next dev + ``` + +## Flow Execution + +- **Run a flow**: `genkit flow:run ''` + - Executes a flow directly from the CLI. Useful for testing. + - **Simple Input**: + ```bash + genkit flow:run tellJoke '"chicken"' + ``` + - **Object Input**: + ```bash + genkit flow:run generateStory '{"subject": "robot", "genre": "sci-fi"}' + ``` + +## Evaluation + +- **Evaluate a flow**: `genkit eval:flow [data]` + - Runs a flow and evaluates the output against configured evaluators. + - **Example (Single Input)**: + ```bash + genkit eval:flow answerQuestion '[{"testCaseId": "1", "input": {"question": "What is Genkit?"}}]' + ``` + - **Example (Batch Input)**: + ```bash + genkit eval:flow answerQuestion --input inputs.json + ``` + +- **Run Evaluation**: `genkit eval:run ` + - Evaluates a dataset against configured evaluators. + - **Example**: + ```bash + genkit eval:run dataset.json --output results.json + ``` \ No newline at end of file diff --git a/.claude/skills/developing-genkit-js/references/examples.md b/.claude/skills/developing-genkit-js/references/examples.md new file mode 100644 index 0000000..2279b4e --- /dev/null +++ b/.claude/skills/developing-genkit-js/references/examples.md @@ -0,0 +1,157 @@ +# Genkit Examples + +This reference contains minimal, reproducible examples (MREs) for common Genkit patterns. + +> **Disclaimer**: These examples use **Google AI** models (`googleAI`, `gemini-*`) for demonstration. The patterns apply to **any provider**. To use a different provider: +> 1. Search the docs for the correct plugin: `genkit docs:search "plugins"`. +> 2. Install and configure the plugin. +> 3. Swap the model reference in the code. + +## Basic Text Generation + +```ts +import { genkit } from "genkit"; +import { googleAI } from "@genkit-ai/google-genai"; + +const ai = genkit({ + plugins: [googleAI()], +}); + +const { text } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a story in a pirate accent', +}); +``` + +## Structured Output + +```ts +import { z } from 'genkit'; + +const JokeSchema = z.object({ + setup: z.string().describe('The setup of the joke'), + punchline: z.string().describe('The punchline'), +}); + +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a joke about developers.', + output: { schema: JokeSchema }, +}); + +// response.output is strongly typed +const joke = response.output; +if (joke) { + console.log(`${joke.setup} ... ${joke.punchline}`); +} +``` + +## Streaming + +```ts +const { stream, response } = ai.generateStream({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell a long story about a developer using Genkit.', +}); + +for await (const chunk of stream) { + console.log(chunk.text); +} + +// Await the final response +const finalResponse = await response; +console.log('Complete:', finalResponse.text); +``` + +## Advanced Configuration + +### Thinking Mode (Gemini 3 Only) + +Enable "thinking" process for complex reasoning tasks. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-3.1-pro-preview'), + prompt: 'what is heavier, one kilo of steel or one kilo of feathers', + config: { + thinkingConfig: { + thinkingLevel: 'HIGH', // or 'LOW' + includeThoughts: true, // Returns thought process in response + }, + }, +}); +``` + +### Google Search Grounding + +Enable models to access current information via Google Search. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'What are the top tech news stories this week?', + config: { + googleSearchRetrieval: true, + }, +}); + +// Access grounding metadata (sources) +const groundingMetadata = (response.custom as any)?.candidates?.[0]?.groundingMetadata; +if (groundingMetadata) { + console.log('Sources:', groundingMetadata.groundingChunks); +} +``` + +## Multimodal Generation + +### Image Generation / Editing + +**Critical**: You MUST set `responseModalities: ['TEXT', 'IMAGE']` when using image generation models. + +```ts +// Generate an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: "generate a picture of a unicorn wearing a space suit on the moon", +}); +// media.url contains the data URI +``` + +```ts +// Edit an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: [ + { text: "change the person's outfit to a banana costume" }, + { media: { url: "https://example.com/photo.jpg" } }, + ], +}); +``` + +### Speech Generation (TTS) + +Generate audio from text. + +```ts +import { writeFile } from 'node:fs/promises'; + +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-preview-tts'), + config: { + responseModalities: ['AUDIO'], + speechConfig: { + voiceConfig: { + prebuiltVoiceConfig: { voiceName: 'Algenib' }, // Options: 'Puck', 'Charon', 'Fenrir', etc. + }, + }, + }, + prompt: 'Genkit is an amazing library', +}); + +// The response contains raw PCM data in media.url (base64 encoded). +// CAUTION: This is NOT an MP3/WAV file. It requires conversion (e.g., PCM to WAV). +// DO NOT GUESS. Run `genkit docs:search "speech audio"` to find the correct +// conversion code for your provider. +``` diff --git a/.claude/skills/developing-genkit-js/references/setup.md b/.claude/skills/developing-genkit-js/references/setup.md new file mode 100644 index 0000000..dcbc8bd --- /dev/null +++ b/.claude/skills/developing-genkit-js/references/setup.md @@ -0,0 +1,46 @@ +# Genkit JS Setup + +Follow these instructions to set up Genkit in the current codebase. These instructions are general-purpose and have not been written with specific codebase knowledge, so use your best judgement when following them. + +0. Tell the user "I'm going to check out your workspace and set you up to use Genkit for GenAI workflows." +1. If the current workspace is empty or is a starter template, your goal will be to create a simple image generation flow that allows someone to generate an image based on a prompt and selectable style. If the current workspace is not empty, you will create a simple example flow to help get the user started. +2. Check to see if any Genkit provider plugin (such as `@genkit-ai/google-genai` or `@genkit-ai/oai-compat` or others, may start with `genkitx-*`) is installed. + - If not, ask the user which provider they want to use. + - **For non-Google providers**: Use `genkit docs:search "plugins"` to find the correct package and installation instructions. + - If they have no preference, default to `@genkit-ai/google-genai` for a quick start. + - If this is a Next.js app, install `@genkit-ai/next` as well. +3. Search the codebase for the exact string `genkit(` (remember to escape regexes properly) which would indicate that the user has already set up Genkit in the codebase. If found, no need to set it up again, tell the user "Genkit is already configured in this app." and exit this workflow. +4. Create an `ai` directory in the primary source directory of the project (this may be e.g. `src` but is project-dependent). Adapt this path if your project uses a different structure. +5. Create `{sourceDir}/ai/genkit.ts` and populate it using the example below. DO NOT add a `next` plugin to the file, ONLY add a model provider plugin to the plugins array: + +```ts +import { genkit, z } from 'genkit'; +// Import your chosen provider plugin here. Example: +import { googleAI } from '@genkit-ai/google-genai'; + +export const ai = genkit({ + plugins: [ + googleAI(), // Add your provider plugin here + ], + model: googleAI.model('gemini-2.5-flash'), // Set your provider's model here +}); + +export { z }; +``` + +6. Create `{sourceDir}/ai/tools` and `{sourceDir}/ai/flows` directories, but leave them empty for now. +7. Create `{sourceDir}/ai/index.ts` and populate it with the following (change the import to match import aliases in `tsconfig.json` as needed): + +```ts +import './genkit.js'; +// import each created flow, tool, etc. here for use in the Genkit Dev UI +``` + +8. Add a `genkit:ui` script to `package.json` that runs `genkit start -- npx tsx --watch {sourceDir}/ai/index.ts` (or `npx genkit-cli` or `pnpm dlx` or `yarn dlx` for those package managers, if CLI is not locally installed). DO NOT try to run the script now. +9. Tell the user "Genkit is now configured and ready for use." as setup is now complete. Also remind them to set appropriate env variables (e.g. `GEMINI_API_KEY` for Google providers). Wait for the user to prompt further before creating any specific flows. + +## Next Steps & Troubleshooting + +- **Documentation**: Use the [CLI](docs-and-cli.md) to access documentation (e.g., `genkit docs:search`). +- **Building Flows**: See [examples.md](examples.md) for patterns on creating flows, adding tools, and advanced configuration. +- **Troubleshooting**: If you encounter issues during setup or initialization, check [common-errors.md](common-errors.md) for solutions. diff --git a/.claude/skills/firebase-ai-logic/SKILL.md b/.claude/skills/firebase-ai-logic/SKILL.md new file mode 100644 index 0000000..f7ec367 --- /dev/null +++ b/.claude/skills/firebase-ai-logic/SKILL.md @@ -0,0 +1,109 @@ +--- +name: firebase-ai-logic +description: Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security. +version: 1.0.0 +--- + +# Firebase AI Logic Basics + +## Overview + +Firebase AI Logic is a product of Firebase that allows developers to add gen AI to their mobile and web apps using client-side SDKs. You can call Gemini models directly from your app without managing a dedicated backend. Firebase AI Logic, which was previously known as "Vertex AI for Firebase", represents the evolution of Google's AI integration platform for mobile and web developers. + +It supports the two Gemini API providers: +- **Gemini Developer API**: It has a free tier ideal for prototyping, and pay-as-you-go for production +- **Vertex AI Gemini API**: Ideal for scale with enterprise-grade production readiness, requires Blaze plan + +Use the Gemini Developer API as a default, and only Vertex AI Gemini API if the application requires it. + +## Setup & Initialization + +### Prerequisites + +- Before starting, ensure you have **Node.js 16+** and npm installed. Install them if they aren’t already available. +- Identify the platform the user is interested in building on prior to starting: Android, iOS, Flutter or Web. +- If their platform is unsupported, Direct the user to Firebase Docs to learn how to set up AI Logic for their application (share this link with the user https://firebase.google.com/docs/ai-logic/get-started) + +### Installation + +The library is part of the standard Firebase Web SDK. + +`npm install -g firebase@latest` + +If you're in a firebase directory (with a firebase.json) the currently selected project will be marked with "current" using this command: + +`npx -y firebase-tools@latest projects:list` + +Ensure there's at least one app associated with the current project + +`npx -y firebase-tools@latest apps:list` + +Initialize AI logic SDK with the init command + +`npx -y firebase-tools@latest init # Choose AI logic` + +This will automatically enable the Gemini Developer API in the Firebase console. + +More info in [Firebase AI Logic Getting Started](https://firebase.google.com/docs/ai-logic/get-started.md.txt) + +## Core Capabilities + +### Text-Only Generation + +### Multimodal (Text + Images/Audio/Video/PDF input) + +Firebase AI Logic allows Gemini models to analyze image files directly from your app. This enables features like creating captions, answering questions about images, detecting objects, and categorizing images. Beyond images, Gemini can analyze other media types like audio, video, and PDFs by passing them as inline data with their MIME type. For files larger than 20 megabytes (which can cause HTTP 413 errors as inline data), store them in Cloud Storage for Firebase and pass their URLs to the Gemini Developer API. + +### Chat Session (Multi-turn) + +Maintain history automatically using `startChat`. + +### Streaming Responses + +To improve the user experience by showing partial results as they arrive (like a typing effect), use `generateContentStream` instead of `generateContent` for faster display of results. + +### Generate Images with Nano Banana + +- Start with Gemini for most use cases, and choose Imagen for specialized tasks where image quality and specific styles are critical. (Example: gemini-2.5-flash-image) +- Requires an upgraded Blaze pay-as-you-go billing plan. + +### Search Grounding with the built in googleSearch tool + +## Supported Platforms and Frameworks + +Supported Platforms and Frameworks include Kotlin and Java for Android, Swift for iOS, JavaScript for web apps, Dart for Flutter, and C Sharp for Unity. + +## Advanced Features + +### Structured Output (JSON) + +Enforce a specific JSON schema for the response. + +### On-Device AI (Hybrid) + +Hybrid on-device inference for web apps, where the Firebase Javascript SDK automatically checks for Gemini Nano's availability (after installation) and switches between on-device or cloud-hosted prompt execution. This requires specific steps to enable model usage in the Chrome browser, more info in the [hybrid-on-device-inference documentation](https://firebase.google.com/docs/ai-logic/hybrid-on-device-inference.md.txt). + +## Security & Production + +### App Check + +Recommended: The developer must enable Firebase App Check to prevent unauthorized clients from using their API quota. see [App-check recaptcha enterprise](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider.md.txt). + +### Remote Config + +Consider that you do not need to hardcode model names (e.g., `gemini-flash-lite-latest`). Use Firebase Remote Config to update model versions dynamically without deploying new client code. See [Changing model names remotely](https://firebase.google.com/docs/ai-logic/change-model-name-remotely.md.txt) + +## Initialization Code References + +| Language, Framework, Platform | Gemini API provider | Context URL | +| :---- | :---- | :---- | +| Web Modular API | Gemini Developer API (Developer API) | firebase://docs/ai-logic/get-started | + +**Always use the most recent version of Gemini (gemini-flash-latest) unless another model is requested by the docs or the user. DO NOT USE gemini-1.5-flash** + +## References + +[Web SDK code examples and usage patterns](references/usage_patterns_web.md) + + + diff --git a/.claude/skills/firebase-ai-logic/references/usage_patterns_web.md b/.claude/skills/firebase-ai-logic/references/usage_patterns_web.md new file mode 100644 index 0000000..e6435bb --- /dev/null +++ b/.claude/skills/firebase-ai-logic/references/usage_patterns_web.md @@ -0,0 +1,174 @@ +# Firebase AI Logic Basics + +## Initialization Pattern +You must initialize the ai-logic service after the main Firebase App. +```JavaScript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; + + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // ... your firebase config +}; + +const app = initializeApp(firebaseConfig); + +// Initialize the AI Logic service (defaults to Gemini Developer API) +// To set the AI provider, set the backend as the second parameter +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +const generationConfig = { + candidate_count: 1, + maxOutputTokens: 2048, + stopSequences: [], + temperature: 0.7, // Balanced: creative but focused + topP: 0.95, // Standard: allows a wide range of probable tokens + topK: 40, // Standard: considers the top 40 tokens +}; + +// Specify the config as part of creating the `GenerativeModel` instance +const model = getGenerativeModel(ai, { model: "gemini-2.5-flash-lite", generationConfig }); +``` + +## Core Capabilities +Text-Only Generation +```JavaScript +async function generateText(prompt) { + const result = await model.generateContent(prompt); + const response = await result.response; + return response.text(); +} +``` + +## Multimodal (Text + Images/Audio/Video/PDF input) +Firebase AI Logic accepts Base64 encoded data or specific file references. +```JavaScript +// Helper to convert file to base64 generic object +async function fileToGenerativePart(file) { + const base64EncodedDataPromise = new Promise((resolve) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result.split(',')[1]); + reader.readAsDataURL(file); + }); + + return { + inlineData: { + data: await base64EncodedDataPromise, + mimeType: file.type, + }, + }; +} + +async function analyzeImage(prompt, imageFile) { + const imagePart = await fileToGenerativePart(imageFile); + const result = await model.generateContent([prompt, imagePart]); + return result.response.text(); +} +``` + +## Chat Session (Multi-turn) +Maintain history automatically using startChat. +```JavaScript +const chat = model.startChat({ + history: [ + { + role: "user", + parts: [{ text: "Hello, I am a developer." }], + }, + { + role: "model", + parts: [{ text: "Great to meet you. How can I help with code?" }], + }, + ], +}); + +async function sendMessage(msg) { + const result = await chat.sendMessage(msg); + return result.response.text(); +} +``` + +## Streaming Responses +For real-time UI updates (like a typing effect). +```JavaScript +async function streamResponse(prompt) { + const result = await model.generateContentStream(prompt); + for await (const chunk of result.stream) { + const chunkText = chunk.text(); + console.log("Stream chunk:", chunkText); + // Update UI here + } +} +``` + +Generate Images with Nano Banana + +```Javascript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai"; + + +// Initialize FirebaseApp +const firebaseApp = initializeApp(firebaseConfig); + +// Initialize the Gemini Developer API backend service +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +// Create a `GenerativeModel` instance with a model that supports your use case +const model = getGenerativeModel(ai, { + model: "gemini-2.5-flash-image", + // Configure the model to respond with text and images (required) + generationConfig: { + responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE], + }, +}); + +// Provide a text prompt instructing the model to generate an image +const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.'; + +// To generate an image, call `generateContent` with the text input +const result = model.generateContent(prompt); + +// Handle the generated image +try { + const inlineDataParts = result.response.inlineDataParts(); + if (inlineDataParts?.[0]) { + const image = inlineDataParts[0].inlineData; + console.log(image.mimeType, image.data); + } +} catch (err) { + console.error('Prompt or candidate was blocked:', err); +} +``` + +## Advanced Features +Structured Output (JSON) +Enforce a specific JSON schema for the response. +```JavaScript +import { getGenerativeModel, Schema } from "firebase/ai"; +const jsonModel = getGenerativeModel(ai, { + model: "gemini-2.5-flash-lite", + generationConfig: { + responseMimeType: "application/json", + // Optional: Define a schema + schema = Schema.object({ ... }); + } +}); + +async function getJsonData(prompt) { + const result = await jsonModel.generateContent(prompt); + return JSON.parse(result.response.text()); +} +``` + +On-Device AI (Hybrid) +Automatically switch between local Gemini Nano and cloud models based on device capability. +```JavaScript +import {getGenerativeModel, InferenceMode } from "firebase/ai"; + +const hybridModel = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE }); +``` + diff --git a/.claude/skills/firebase-app-hosting-basics/SKILL.md b/.claude/skills/firebase-app-hosting-basics/SKILL.md new file mode 100644 index 0000000..4aa23b7 --- /dev/null +++ b/.claude/skills/firebase-app-hosting-basics/SKILL.md @@ -0,0 +1,58 @@ +--- +name: firebase-app-hosting-basics +description: Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends. +--- + +# App Hosting Basics + +## Description +This skill enables the agent to deploy and manage modern, full-stack web applications (Next.js, Angular, etc.) using Firebase App Hosting. + +**Important**: In order to use App Hosting, your Firebase project must be on the Blaze pricing plan. Direct the user to https://console.firebase.google.com/project/_/overview?purchaseBillingPlan=metered to upgrade their plan. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Deploying to App Hosting + +### Deploy from Source + +This is the recommended flow for most users. +1. Configure `firebase.json` with an `apphosting` block. + ```json + { + "apphosting": { + "backendId": "my-app-id", + "rootDir": "/", + "ignore": [ + "node_modules", + ".git", + "firebase-debug.log", + "firebase-debug.*.log", + "functions" + ] + } + } + ``` +2. Create or edit `apphosting.yaml`- see [Configuration](references/configuration.md) for more information on how to do so. +3. If the app needs safe access to sensitive keys, use `npx -y firebase-tools@latest apphosting:secrets` commands to set and grant access to secrets. +4. Run `npx -y firebase-tools@latest deploy` when you are ready to deploy. + +### Automated deployment via GitHub (CI/CD) + +Alternatively, set up a backend connected to a GitHub repository for automated deployments "git push" deployments. +This is only recommended for more advanced users, and is not required to use App Hosting. +See [CLI Commands](references/cli_commands.md) for more information on how to set this up using CLI commands. + +## Emulation + +See [Emulation](references/emulation.md) for more information on how to test your app locally using the Firebase Local Emulator Suite. diff --git a/.claude/skills/firebase-app-hosting-basics/references/cli_commands.md b/.claude/skills/firebase-app-hosting-basics/references/cli_commands.md new file mode 100644 index 0000000..c758c9d --- /dev/null +++ b/.claude/skills/firebase-app-hosting-basics/references/cli_commands.md @@ -0,0 +1,71 @@ +# App Hosting CLI Commands + +The Firebase CLI provides a comprehensive suite of commands to manage App Hosting resources. These commands are often faster and more scriptable than using the Firebase Console. + +## Initialization + +### `npx -y firebase-tools@latest init apphosting` + +- **Purpose**: Interactive command that sets up App Hosting in your local project. +Use this command only if you are able to handle interactive CLI inputs well. +Alternatively, you can manually edit `firebase.json` and `apphosting.yml`. + +- **Effect**: + - Detects your web framework. + - Creates/updates `apphosting.yaml`. + - Can optionally create a backend if one doesn't exist. + +## Backend Management + +### `npx -y firebase-tools@latest apphosting:backends:list` + +- **Purpose**: Lists all backends in the current project. + +### `npx -y firebase-tools@latest apphosting:backends:get ` + +- **Purpose**: Shows details for a specific backend. + +### `npx -y firebase-tools@latest apphosting:backends:delete ` + +- **Purpose**: Deletes a backend and its associated resources. + +### `npx -y firebase-tools@latest apphosting:rollouts:list ` + +- **Purpose**: Lists the history of rollouts for a backend. + +## Secrets Management + +App Hosting uses Cloud Secret Manager to securely handle sensitive environment variables (like API keys). + +### `npx -y firebase-tools@latest apphosting:secrets:set ` + +- **Purpose**: Creates or updates a secret in Cloud Secret Manager and makes it available to App Hosting. +- **Behavior**: Prompts for the secret value (hidden input). + +### `npx -y firebase-tools@latest apphosting:secrets:grantaccess ` + +- **Purpose**: Grants the App Hosting service account permission to access the secret. +- **Note**: Often handled automatically by `secrets:set`, but useful for debugging permission issues or granting access to existing secrets. + +## Automated deployment via GitHub (CI/CD) + +**IMPORTANT** Only use these commands if you are setting up automated deployments via GitHub. If you are managing deployments using `npx -y firebase-tools@latest deploy`, DO NOT use these commands. + +### `npx -y firebase-tools@latest apphosting:rollouts:create ` + +- **Purpose**: Manually triggers a new rollout (deployment). +- **Options**: + - `--git-branch `: Deploy the latest commit from a specific branch. + - `--git-commit `: Deploy a specific commit. +- **Use Case**: Useful for redeploying without code changes, or rolling back to a specific commit. + +### `npx -y firebase-tools@latest apphosting:backends:create` + +- **Purpose**: Creates a new App Hosting backend. Use this when setting up automated deployments via GitHub. +- **Options**: + - `--app `: The ID of an existing Firebase web app to associate with the backend. + - `--backend `: The ID of the new backend. + - `--primary-region `: The primary region for the backend. + - `--root-dir `: The root directory for the backend. If omitted, defaults to the root directory of the project. + - `--service-account `: The service account used to run the server. If omitted, defaults to the default service account. + \ No newline at end of file diff --git a/.claude/skills/firebase-app-hosting-basics/references/configuration.md b/.claude/skills/firebase-app-hosting-basics/references/configuration.md new file mode 100644 index 0000000..da10766 --- /dev/null +++ b/.claude/skills/firebase-app-hosting-basics/references/configuration.md @@ -0,0 +1,51 @@ +# App Hosting Configuration (`apphosting.yaml`) + +The `apphosting.yaml` file is the source of truth for your backend's configuration. It must be located in the root of your app's directory (or the specific root directory if using a monorepo). + +## File Structure + +```yaml +# apphosting.yaml + +# Cloud Run service configuration +runConfig: + cpu: 1 + memoryMiB: 512 + minInstances: 0 + maxInstances: 100 + concurrency: 80 + +# Environment variables +env: + - variable: STORAGE_BUCKET + value: mybucket.app + availability: + - BUILD + - RUNTIME + - variable: API_KEY + secret: myApiKeySecret +``` + +## `runConfig` +Controls the resources allocated to the Cloud Run service that serves your app. +- `cpu`: Number of vCPUs. Note: If `< 1`, concurrency MUST be set to `1`. +- `memoryMiB`: RAM in MiB (128 to 32768). +- `minInstances`: Minimum containers to keep warm (default 0). Set to >= 1 to avoid cold starts. +- `maxInstances`: Maximum scaling limit (default 100). +- `concurrency`: Max concurrent requests per instance (default 80). + +### Resource Constraints +- **CPU vs Memory**: Higher memory often requires higher CPU. + - > 4GiB RAM -> Needs >= 2 vCPU + - > 8GiB RAM -> Needs >= 4 vCPU + +## `env` (Environment Variables) +Defines environment variables available during build and/or runtime. + +- `variable`: The name of the env var (e.g., `NEXT_PUBLIC_API_URL`). +- `value`: A literal string value. +- `secret`: The name of a secret in Cloud Secret Manager. use `npx -y firebase-tools@latest apphosting:secrets:set` to create these. +- `availability`: Where the variable is needed. + - `BUILD`: Available during the `npm run build` process. + - `RUNTIME`: Available when the app is serving requests. + - Defaults to both if not specified. diff --git a/.claude/skills/firebase-app-hosting-basics/references/emulation.md b/.claude/skills/firebase-app-hosting-basics/references/emulation.md new file mode 100644 index 0000000..299dcde --- /dev/null +++ b/.claude/skills/firebase-app-hosting-basics/references/emulation.md @@ -0,0 +1,47 @@ +# App Hosting Emulation + +You can test your App Hosting setup locally using the Firebase Local Emulator Suite. This allows you to verify your app's behavior with environment variables and secrets before deploying. + +## Configuration: `apphosting.emulator.yaml` +This optional file overrides `apphosting.yaml` settings specifically for the local emulator. Use it to provide local secret values or override resource configs. If it contains sensitive values such as API keys, do not commit it to source control. + +```yaml +# apphosting.emulator.yaml (gitignored usually) +runConfig: + cpu: 1 + memoryMiB: 512 + +env: + - variable: API_KEY + value: "local-dev-api-key" # Override secret with local value +``` + +## Running the Emulator +To start the App Hosting emulator: + +```bash +npx -y firebase-tools@latest emulators:start --only apphosting +``` + +Or, if you are also using other emulators (Auth, Firestore, etc.): + +```bash +npx -y firebase-tools@latest emulators:start +``` + +## Capabilities +- **Builds your app**: Runs the build command defined in your `package.json` to generate the serving artifact. +- **Serves locally**: Runs the app on `localhost:5004` (default). +Configurable by setting `host` and `port` in the `emulators` block of `firebase.json`, like so: + +```json +{ + "emulators": { + "apphosting": { + "host": "localhost", + "port": 5004 + } + } +} +``` +- **Env Var Injection**: Injects variables defined in `apphosting.yaml` and `apphosting.emulator.yaml` into the process. diff --git a/.claude/skills/firebase-auth-basics/SKILL.md b/.claude/skills/firebase-auth-basics/SKILL.md new file mode 100644 index 0000000..bac12ad --- /dev/null +++ b/.claude/skills/firebase-auth-basics/SKILL.md @@ -0,0 +1,86 @@ +--- +name: firebase-auth-basics +description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +## Prerequisites + +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). + +## Core Concepts + +Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. + +### Users + +A user is an entity that can sign in to your app. Each user is identified by a unique ID (`uid`) which is guaranteed to be unique across all providers. +User properties include: +- `uid`: Unique identifier. +- `email`: User's email address (if available). +- `displayName`: User's display name (if available). +- `photoURL`: URL to user's photo (if available). +- `emailVerified`: Boolean indicating if the email is verified. + +### Identity Providers + +Firebase Auth supports multiple ways to sign in: +- **Email/Password**: Basic email and password authentication. +- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub, Microsoft, Apple, etc. +- **Phone Number**: SMS-based authentication. +- **Anonymous**: Temporary guest accounts that can be linked to permanent accounts later. +- **Custom Auth**: Integrate with your existing auth system. + +Google Sign In is recommended as a good and secure default provider. + +### Tokens + +When a user signs in, they receive an ID Token (JWT). This token is used to identify the user when making requests to Firebase services (Realtime Database, Cloud Storage, Firestore) or your own backend. +- **ID Token**: Short-lived (1 hour), verifies identity. +- **Refresh Token**: Long-lived, used to get new ID tokens. + +## Workflow + +### 1. Provisioning + +#### Option 1. Enabling Authentication via CLI + +Only Google Sign In, anonymous auth, and email/password auth can be enabled via CLI. For other providers, use the Firebase Console. + +Configure Firebase Authentication in `firebase.json` by adding an 'auth' block: + +``` +{ + "auth": { + "providers": { + "anonymous": true, + "emailPassword": true, + "googleSignIn": { + "oAuthBrandDisplayName": "Your Brand Name", + "supportEmail": "support@example.com", + "authorizedRedirectUris": ["https://example.com"] + } + } + } +} +``` + +#### Option 2. Enabling Authentication in Console + +Enable other providers in the Firebase Console. + +1. Go to the https://console.firebase.google.com/project/_/authentication/providers +2. Select your project. +3. Enable the desired Sign-in providers (e.g., Email/Password, Google). + +### 2. Client Setup & Usage + +**Web** +See [references/client_sdk_web.md](references/client_sdk_web.md). + +### 3. Security Rules + +Secure your data using `request.auth` in Firestore/Storage rules. + +See [references/security_rules.md](references/security_rules.md). diff --git a/.claude/skills/firebase-auth-basics/references/client_sdk_web.md b/.claude/skills/firebase-auth-basics/references/client_sdk_web.md new file mode 100644 index 0000000..493a66a --- /dev/null +++ b/.claude/skills/firebase-auth-basics/references/client_sdk_web.md @@ -0,0 +1,287 @@ +# Firebase Authentication Web SDK + +## Initialization + +First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize the Auth service: + +```javascript +import { getAuth } from "firebase/auth"; +import { app } from "./firebase"; // Your initialized Firebase App + +const auth = getAuth(app); +export { auth }; +``` + +## Connect to Emulator + +If you are running the Authentication emulator (usually on port 9099), connect to it immediately after initialization. + +```javascript +import { getAuth, connectAuthEmulator } from "firebase/auth"; + +const auth = getAuth(); +// Connect to emulator if running locally +if (location.hostname === "localhost") { + connectAuthEmulator(auth, "http://localhost:9099"); +} +``` + +## Sign Up with Email/Password + +```javascript +import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; + +const auth = getAuth(); +createUserWithEmailAndPassword(auth, email, password) + .then((userCredential) => { + const user = userCredential.user; + // ... + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + // .. + }); +``` + +## Sign In with Google (Popup) + +```javascript +import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GoogleAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // This gives you a Google Access Token. You can use it to access the Google API. + const credential = GoogleAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + // The signed-in user info. + const user = result.user; + // ... + }) + .catch((error) => { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // ... + }); +``` + +## Sign In with Facebook (Popup) + +```javascript +import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new FacebookAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // The signed-in user info. + const user = result.user; + // This gives you a Facebook Access Token. You can use it to access the Facebook API. + const credential = FacebookAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Apple (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('apple.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Apple credential + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Twitter (Popup) + +```javascript +import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new TwitterAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Twitter credential + const credential = TwitterAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + const secret = credential.secret; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with GitHub (Popup) + +```javascript +import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GithubAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = GithubAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Microsoft (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('microsoft.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Yahoo (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('yahoo.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In Anonymously + +```javascript +import { getAuth, signInAnonymously } from "firebase/auth"; + +const auth = getAuth(); +signInAnonymously(auth) + .then(() => { + // Signed in.. + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + }); +``` + +## Email Link Authentication + +**1. Send Auth Link** + +```javascript +import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; + +const auth = getAuth(); +const actionCodeSettings = { + // URL you want to redirect back to. The domain must be in the authorized domains list in Firebase Console. + url: 'https://www.example.com/finishSignUp?cartId=1234', + handleCodeInApp: true, +}; + +sendSignInLinkToEmail(auth, email, actionCodeSettings) + .then(() => { + // Save the email locally so you don't need to ask the user for it again + window.localStorage.setItem('emailForSignIn', email); + }) + .catch((error) => { + // Error + }); +``` + +**2. Complete Sign In (on landing page)** + +```javascript +import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth"; + +const auth = getAuth(); + +if (isSignInWithEmailLink(auth, window.location.href)) { + let email = window.localStorage.getItem('emailForSignIn'); + if (!email) { + email = window.prompt('Please provide your email for confirmation'); + } + + signInWithEmailLink(auth, email, window.location.href) + .then((result) => { + window.localStorage.removeItem('emailForSignIn'); + // You can check result.user + }) + .catch((error) => { + // Error + }); +} +``` + +## Observe Auth State + +Recommended way to get the current user. This listener triggers whenever the user signs in or out. + +```javascript +import { getAuth, onAuthStateChanged } from "firebase/auth"; + +const auth = getAuth(); +onAuthStateChanged(auth, (user) => { + if (user) { + // User is signed in, see docs for a list of available properties + // https://firebase.google.com/docs/reference/js/firebase.User + const uid = user.uid; + // ... + } else { + // User is signed out + // ... + } +}); +``` + +## Sign Out + +```javascript +import { getAuth, signOut } from "firebase/auth"; + +const auth = getAuth(); +signOut(auth).then(() => { + // Sign-out successful. +}).catch((error) => { + // An error happened. +}); +``` diff --git a/.claude/skills/firebase-auth-basics/references/security_rules.md b/.claude/skills/firebase-auth-basics/references/security_rules.md new file mode 100644 index 0000000..5de862a --- /dev/null +++ b/.claude/skills/firebase-auth-basics/references/security_rules.md @@ -0,0 +1,38 @@ +# Authentication in Security Rules + +Firebase Security Rules work with Firebase Authentication to provide rule-based access control. For better advice on writing safe security rules, +enable the `firebase-firestore-basics` or `firebase-storage-basics` skills. + +The `request.auth` variable contains authentication information for the user requesting data. + +## Basic Checks + +### Check if user is signed in +``` +allow read, write: if request.auth != null; +``` + +### Check if user owns the data +Access data only if the document ID matches the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == userId; +``` +(Where `userId` is a path variable, e.g., `match /users/{userId}`) + +### Check if user owns the document (field-based) +Access data only if the document has a `owner_uid` field matching the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == resource.data.owner_uid; +``` + +## Token Properties +`request.auth.token` contains standard JWT claims and custom claims. + +- `request.auth.token.email`: The user's email address. +- `request.auth.token.email_verified`: If the email is verified. +- `request.auth.token.name`: The user's display name. + +### Example: Email Verification Check +``` +allow create: if request.auth.token.email_verified == true; +``` diff --git a/.claude/skills/firebase-basics/SKILL.md b/.claude/skills/firebase-basics/SKILL.md new file mode 100644 index 0000000..25909bb --- /dev/null +++ b/.claude/skills/firebase-basics/SKILL.md @@ -0,0 +1,52 @@ +--- +name: firebase-basics +description: The definitive, foundational skill for ANY Firebase task. Make sure to ALWAYS use this skill whenever the user mentions or interacts with Firebase, even if they do not explicitly ask for it. This skill covers everything from the bare minimum INITIAL setup (Node.js setup, Firebase CLI installation, first-time login) to ongoing operations (core principles, workflows, building, service setup, executing Firebase CLI commands, troubleshooting, refreshing, or updating an existing environment). +--- +# Prerequisites + +Please complete these setup steps before proceeding, and remember your progress to avoid repeating them in future interactions. + +1. **Local Environment Setup:** Verify the environment is properly set up so we can use Firebase tools: + - Run `npx -y firebase-tools@latest --version` to check if the Firebase CLI is installed. + - Verify if the Firebase MCP server is installed using your existing tools. + - If either of these checks fails, please review [references/local-env-setup.md](references/local-env-setup.md) to get the environment ready. + +2. **Authentication:** + Ensure you are logged in to Firebase so that commands have the correct permissions. Run `npx -y firebase-tools@latest login`. For environments without a browser (e.g., remote shells), use `npx -y firebase-tools@latest login --no-localhost`. + - The command should output the current user. + - If you are not logged in, follow the interactive instructions from this command to authenticate. + +3. **Active Project:** + Most Firebase tasks require an active project context. Check the current project by running `npx -y firebase-tools@latest use`. + - If the command outputs `Active Project: `, you can proceed with your task. + - If not, ask the user if they have an existing Firebase Project ID. + - If yes: Set it as the active project and add a default alias by running: + ```bash + npx -y firebase-tools@latest use --add + ``` + - If no: Follow the project creation instructions in [references/firebase-project-create.md](references/firebase-project-create.md). + +# Firebase Usage Principles + +Please adhere to these principles when working with Firebase, as they ensure reliability and up-to-date project tools: + +1. **Use npx for CLI commands:** To ensure you always use the latest version of the Firebase CLI, always prepend commands with `npx -y firebase-tools@latest` instead of just `firebase`. (e.g., use `npx -y firebase-tools@latest --version` instead of `firebase --version`). +2. **Prioritize official knowledge:** For any Firebase-related knowledge, consult the `developerknowledge_search_documents` MCP tool before falling back to Google Search or your internal knowledge base. Including "Firebase" in your search query significantly improves relevance. +3. **Follow Agent Skills for implementation guidance:** Skills provide opinionated workflows (CUJs), security rules, and best practices. Always consult them to understand *how* to implement Firebase features correctly instead of relying on general knowledge. +4. **Use Firebase MCP Server tools instead of direct API calls:** Whenever you need to interact with remote Firebase APIs (such as fetching Crashlytics logs or executing Data Connect queries), use the tools provided by the Firebase MCP Server instead of attempting manual API calls. +5. **Keep Plugin / Agent Skills updated:** Since Firebase best practices evolve quickly, remind the user to regularly check for and install updates to their Firebase plugin or Agent Skills, ensuring you both operate with the latest workflows. Similarly, if you encounter issues with outdated tools or commands, follow the steps below based on your agent environment: + - **Antigravity**: Follow [references/refresh-antigravity.md](references/refresh-antigravity.md) + - **Gemini CLI**: Follow [references/refresh-gemini-cli.md](references/refresh-gemini-cli.md) + - **Claude Code**: Follow [references/refresh-claude.md](references/refresh-claude.md) + - **Cursor**: Follow [references/refresh-cursor.md](references/refresh-cursor.md) + - **Others**: Follow [references/refresh-other.md](references/refresh-other-agents.md) + +# References + +- **Initialize Firebase:** See [references/firebase-service-init.md](references/firebase-service-init.md) when you need to initialize new Firebase services using the CLI. +- **Exploring Commands:** See [references/firebase-cli-guide.md](references/firebase-cli-guide.md) to discover and understand CLI functionality. +- **SDK Setup:** For detailed guides on adding Firebase to a web app, see [references/web_setup.md](references/web_setup.md). + +# Common Issues + +- **Login Issues:** If the browser fails to open during the login step, use `npx -y firebase-tools@latest login --no-localhost` instead. diff --git a/.claude/skills/firebase-basics/references/firebase-cli-guide.md b/.claude/skills/firebase-basics/references/firebase-cli-guide.md new file mode 100644 index 0000000..36a4480 --- /dev/null +++ b/.claude/skills/firebase-basics/references/firebase-cli-guide.md @@ -0,0 +1,16 @@ +# Exploring Commands + +The Firebase CLI documents itself. Use help commands to discover functionality. + +- **Global Help**: List all available commands and categories. + ```bash + npx -y firebase-tools@latest --help + ``` + +- **Command Help**: Get detailed usage for a specific command. + ```bash + npx -y firebase-tools@latest [command] --help + # Example: + npx -y firebase-tools@latest deploy --help + npx -y firebase-tools@latest firestore:indexes --help + ``` diff --git a/.claude/skills/firebase-basics/references/firebase-project-create.md b/.claude/skills/firebase-basics/references/firebase-project-create.md new file mode 100644 index 0000000..02b0566 --- /dev/null +++ b/.claude/skills/firebase-basics/references/firebase-project-create.md @@ -0,0 +1,11 @@ +# Creating a Project + +To create a new Firebase project from the CLI: + +```bash +npx -y firebase-tools@latest projects:create +``` + +You will be prompted to: +1. Enter a **Project ID** (must be 6-30 chars, lowercase, digits, and hyphens; must be unique globally). +2. Enter a **display name**. diff --git a/.claude/skills/firebase-basics/references/firebase-service-init.md b/.claude/skills/firebase-basics/references/firebase-service-init.md new file mode 100644 index 0000000..13800aa --- /dev/null +++ b/.claude/skills/firebase-basics/references/firebase-service-init.md @@ -0,0 +1,18 @@ +# Initialization + +Before initializing, check if you are already in a Firebase project directory by looking for `firebase.json`. + +1. **Project Directory:** + Navigate to the root directory of the codebase. + *(Only if starting a completely new project from scratch without an existing codebase, create a directory first: `mkdir my-project && cd my-project`)* + +2. **Initialize Services:** + Run the initialization command: + ```bash + npx -y firebase-tools@latest init + ``` + +The CLI will guide you through: +- Selecting features (Firestore, Functions, Hosting, etc.). +- Associating with an existing project or creating a new one. +- Configuring files (e.g. `firebase.json`, `.firebaserc`). diff --git a/.claude/skills/firebase-basics/references/local-env-setup.md b/.claude/skills/firebase-basics/references/local-env-setup.md new file mode 100644 index 0000000..99e6019 --- /dev/null +++ b/.claude/skills/firebase-basics/references/local-env-setup.md @@ -0,0 +1,65 @@ +# Firebase Local Environment Setup + +This skill documents the bare minimum setup required for a full Firebase experience for the agent. Before starting to use any Firebase features, you MUST verify that each of the following steps has been completed. + +## 1. Verify Node.js +- **Action**: Run `node --version`. +- **Handling**: Ensure Node.js is installed and the version is `>= 20`. If Node.js is missing or `< v20`, install it based on the operating system: + + **Recommended: Use a Node Version Manager** + This avoids permission issues when installing global packages. + + **For macOS or Linux:** + 1. Guide the user to the [official nvm repository](https://github.com/nvm-sh/nvm#installing-and-updating). + 2. Request the user to manually install `nvm` and reply when finished. **Stop and wait** for the user's confirmation. + 3. Make `nvm` available in the current terminal session by sourcing the appropriate profile: + ```bash + # For Bash + source ~/.bash_profile + source ~/.bashrc + + # For Zsh + source ~/.zprofile + source ~/.zshrc + ``` + 4. Install Node.js: + ```bash + nvm install 24 + nvm use 24 + ``` + + **For Windows:** + 1. Guide the user to download and install [nvm-windows](https://github.com/coreybutler/nvm-windows/releases). + 2. Request the user to manually install `nvm-windows` and Node.js, and reply when finished. **Stop and wait** for the user's confirmation. + 3. After the user confirms, verify Node.js is available: + ```bash + node --version + ``` + + **Alternative: Official Installer** + 1. Guide the user to download and install the LTS version from [nodejs.org](https://nodejs.org/en/download). + 2. Request the user to manually install Node.js and reply when finished. **Stop and wait** for the user's confirmation. + +## 2. Verify Firebase CLI +The Firebase CLI is the primary tool for interacting with Firebase services. +- **Action**: Run `npx -y firebase-tools@latest --version`. +- **Handling**: Ensure this command runs successfully and outputs a version number. + +## 3. Verify Firebase Authentication +You must be authenticated to manage Firebase projects. +- **Action**: Run `npx -y firebase-tools@latest login`. +- **Handling**: If the environment is remote or restricted (no browser access), run `npx -y firebase-tools@latest login --no-localhost` instead. + +## 4. Install Agent Skills and MCP Server +To fully manage Firebase, the agent needs specific skills and the Firebase MCP server installed. Identify the agent environment you are currently running in and follow the corresponding setup document strictly. + +**Read the setup document for your current agent:** +- **Gemini CLI**: Review [setup-gemini_cli.md](setup-gemini_cli.md) +- **Antigravity**: Review [setup-antigravity.md](setup-antigravity.md) +- **Claude Code**: Review [setup-claude_code.md](setup-claude_code.md) +- **Cursor**: Review [setup-cursor.md](setup-cursor.md) +- **GitHub Copilot**: Review [setup-github_copilot.md](setup-github_copilot.md) +- **Other Agents** (Windsurf, Cline, etc.): Review [setup-other_agents.md](setup-other_agents.md) + +--- +**CRITICAL AGENT RULE:** Do NOT proceed with any other Firebase tasks until EVERY step above has been successfully verified and completed. diff --git a/.claude/skills/firebase-basics/references/refresh-antigravity.md b/.claude/skills/firebase-basics/references/refresh-antigravity.md new file mode 100644 index 0000000..6f5ee32 --- /dev/null +++ b/.claude/skills/firebase-basics/references/refresh-antigravity.md @@ -0,0 +1,46 @@ +# Refresh Antigravity Local Environment + +Follow these steps to refresh Antigravity's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Antigravity relies on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent antigravity + + # Check global-level skills + npx -y skills list --agent antigravity --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to Antigravity.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent antigravity --yes + + # Update global-level skills + npx -y skills update --agent antigravity --global --yes + ``` diff --git a/.claude/skills/firebase-basics/references/refresh-claude.md b/.claude/skills/firebase-basics/references/refresh-claude.md new file mode 100644 index 0000000..772314e --- /dev/null +++ b/.claude/skills/firebase-basics/references/refresh-claude.md @@ -0,0 +1,10 @@ +# Refresh Claude Code Local Environment + +Follow these steps to refresh Claude Code's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use Claude Code's native plugin manager instead of `npx`. + +1. **Update the Plugin:** Run the specific CLI command to update the Firebase plugin: + ```bash + claude plugin update firebase@firebase + ``` \ No newline at end of file diff --git a/.claude/skills/firebase-basics/references/refresh-gemini-cli.md b/.claude/skills/firebase-basics/references/refresh-gemini-cli.md new file mode 100644 index 0000000..6cc1467 --- /dev/null +++ b/.claude/skills/firebase-basics/references/refresh-gemini-cli.md @@ -0,0 +1,11 @@ +# Refresh Gemini CLI Local Environment + +Follow these steps to refresh Gemini CLI's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use the native Gemini CLI extension manager instead of `npx`. + +1. **Update the Extension:** Run the specific CLI command to update: + ```bash + gemini extensions update firebase + ``` + *Note: If the extension is named differently, replace `firebase` with the correct name from `gemini extensions list`.* diff --git a/.claude/skills/firebase-basics/references/refresh-other-agents.md b/.claude/skills/firebase-basics/references/refresh-other-agents.md new file mode 100644 index 0000000..f624c96 --- /dev/null +++ b/.claude/skills/firebase-basics/references/refresh-other-agents.md @@ -0,0 +1,48 @@ +# Refresh Other Local Environment + +Follow these steps to refresh the local environment of other agents, ensuring that their agent skills and plugins are fully up-to-date. + +Other agents rely on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +Replace `` with the actual agent name, which can be found in the [skills repository README](https://github.com/vercel-labs/skills/blob/main/README.md). + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked for the agent at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent + + # Check global-level skills + npx -y skills list --agent --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to the agent.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent --yes + + # Update global-level skills + npx -y skills update --agent --global --yes + ``` diff --git a/.claude/skills/firebase-basics/references/setup-antigravity.md b/.claude/skills/firebase-basics/references/setup-antigravity.md new file mode 100644 index 0000000..7817673 --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-antigravity.md @@ -0,0 +1,63 @@ +# Antigravity Setup + +To get the most out of Firebase in Antigravity, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `ls -d .agent/skills/firebase-basics` or `ls -d .agents/skills/firebase-basics`. If the directory exists, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent antigravity + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent antigravity --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Antigravity to interact directly with Firebase projects. + +1. **Locate `mcp_config.json`**: Find the configuration file for your operating system: + - macOS / Linux: `~/.gemini/antigravity/mcp_config.json` + - Windows: `%USERPROFILE%\\.gemini\\antigravity\\mcp_config.json` + + *Note: If the `.gemini/antigravity/` directory or `mcp_config.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp_config.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp_config.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Antigravity**: Instruct the user to restart the Antigravity application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Antigravity UI to confirm that the Firebase MCP server is connected. diff --git a/.claude/skills/firebase-basics/references/setup-claude_code.md b/.claude/skills/firebase-basics/references/setup-claude_code.md new file mode 100644 index 0000000..fe8eba6 --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-claude_code.md @@ -0,0 +1,30 @@ +# Claude Code Setup + +To get the most out of Firebase in Claude Code, follow these steps to install the agent skills and the MCP server. + +## Recommended Method: Using Plugins + +The recommended method is using the plugin marketplace to install both the agent skills and the MCP functionality. + +### 1. Install and Verify Plugins + +Check if the plugins are already installed before proceeding: + +1. **Check Existing Skills**: Run `npx skills list --agent claude-code` to check for local skills. Run `npx skills list --global --agent claude-code` to check for global skills. Note whether the output includes `firebase-basics`. +2. **Check Existing MCP Configuration**: Run `claude mcp list -s user` and `claude mcp list -s project`. Note whether the output of either command includes `firebase`. +3. **Determine Installation Path**: + - If **both** skills and MCP configuration are found, the plugin is fully installed. **Stop here and skip all remaining setup steps in this document.** + - If **neither** are found, proceed to step 4. + - If **only one** is found (e.g., skills are installed but MCP is missing, or vice versa), **stop and prompt the user**. Explain the mixed state and ask if they want to proceed with installing the Firebase plugin before continuing to step 4. +4. **Add Marketplace**: Run the following command to add the marketplace (this uses the default User scope): + ```bash + claude plugin marketplace add firebase/agent-skills + ``` +5. **Install Plugins**: Run the following command to install the plugin: + ```bash + claude plugin install firebase@firebase + ``` +6. **Verify Installation**: Re-run the checks in steps 1 and 2 to confirm the skills and the MCP server are now available. + +### 2. Restart and Verify Connection +1. **Restart Claude Code**: Instruct the user to restart Claude Code. **Stop and wait** for their confirmation before proceeding. diff --git a/.claude/skills/firebase-basics/references/setup-cursor.md b/.claude/skills/firebase-basics/references/setup-cursor.md new file mode 100644 index 0000000..c74360e --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-cursor.md @@ -0,0 +1,63 @@ +# Cursor Setup + +To get the most out of Firebase in Cursor, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent cursor`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent cursor + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent cursor --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Cursor to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your operating system: + - Global: `~/.cursor/mcp.json` + - Project: `.cursor/mcp.json` + + *Note: If the directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Cursor**: Instruct the user to restart the Cursor application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Cursor UI to confirm that the Firebase MCP server is connected. diff --git a/.claude/skills/firebase-basics/references/setup-gemini_cli.md b/.claude/skills/firebase-basics/references/setup-gemini_cli.md new file mode 100644 index 0000000..ebadeaa --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-gemini_cli.md @@ -0,0 +1,39 @@ +# Gemini CLI Setup + +To get the most out of Firebase in the Gemini CLI, follow these steps to install the agent extension and the MCP server. + +## Recommended: Installing Extensions + +The best way to get both the agent skills and the MCP server is via the Gemini extension. + +### 1. Install and Verify Firebase Extension +Check if the extension is already installed before proceeding: + +1. **Check Existing Extensions**: Run `gemini extensions list`. If the output includes `firebase`, the extension is already installed. +2. **Install Extension**: If not found, run the following command to install the Firebase agent skills and MCP server: + ```bash + gemini extensions install https://github.com/firebase/agent-skills + ``` +3. **Verify Installation**: Run the following checks to confirm installation: + - `gemini mcp list` -> Output should include `firebase-tools`. + - `gemini skills list` -> Output should include `firebase-basic`. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI if any new installation occurred. **Stop and wait** for their confirmation before proceeding. + +--- + +## Alternative: Manual MCP Configuration (Project Scope) + +If the user only wants to use the MCP server for the current project: + +### 1. Configure and Verify Firebase MCP Server +1. **Check Existing Configuration**: Run `gemini mcp list`. If the output includes `firebase-tools`, the MCP server is already configured. +2. **Add the MCP Server**: If not found, run the following command to configure the Firebase MCP Server: + ```bash + gemini mcp add -e IS_GEMINI_CLI_EXTENSION=true firebase npx -y firebase-tools@latest mcp + ``` +3. **Verify Configuration**: Re-run `gemini mcp list` to confirm `firebase-tools` is connected. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI. **Stop and wait** for their confirmation before proceeding. diff --git a/.claude/skills/firebase-basics/references/setup-github_copilot.md b/.claude/skills/firebase-basics/references/setup-github_copilot.md new file mode 100644 index 0000000..1704cb5 --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-github_copilot.md @@ -0,0 +1,70 @@ +# GitHub Copilot Setup + +To get the most out of Firebase with GitHub Copilot in VS Code, follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent github-copilot`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent github-copilot + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent github-copilot --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows GitHub Copilot to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your environment: + - Workspace: `.vscode/mcp.json` + - Global: User Settings `mcp.json` file. + + *Note: If the `.vscode/` directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcp": { "servers": {} } }` before proceeding.* +2. **Check Existing Configuration**: Open the `mcp.json` file and check the `mcp.servers` object for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "type": "stdio", + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcp.servers` object: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file under the `mcp.servers` object. You MUST preserve any other existing servers inside `mcp.servers`.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart VS Code**: Instruct the user to restart VS Code. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the VS Code Copilot UI to confirm that the Firebase MCP server is connected. diff --git a/.claude/skills/firebase-basics/references/setup-other_agents.md b/.claude/skills/firebase-basics/references/setup-other_agents.md new file mode 100644 index 0000000..d45a608 --- /dev/null +++ b/.claude/skills/firebase-basics/references/setup-other_agents.md @@ -0,0 +1,65 @@ +# Other Agents Setup + +If you use another agent (like Windsurf, Cline, or Claude Desktop), follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent `. If the output includes `firebase-basics`, the skills are already installed locally. Replace `` with the actual agent name, which can be found [here](https://github.com/vercel-labs/skills/blob/main/README.md). +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows the agent to interact directly with Firebase projects. + +1. **Locate MCP Configuration**: Find the configuration file for your agent (e.g., `~/.codeium/windsurf/mcp_config.json`, `cline_mcp_settings.json`, or `claude_desktop_config.json`). + + *Note: If the document or its containing directory does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open the configuration file and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Agent**: Instruct the user to restart the agent application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the agent's UI to confirm that the Firebase MCP server is connected. diff --git a/.claude/skills/firebase-basics/references/web_setup.md b/.claude/skills/firebase-basics/references/web_setup.md new file mode 100644 index 0000000..b696118 --- /dev/null +++ b/.claude/skills/firebase-basics/references/web_setup.md @@ -0,0 +1,69 @@ +# Firebase Web Setup Guide + +## 1. Create a Firebase Project and App +If you haven't already created a project: + +```bash +npx -y firebase-tools@latest projects:create +``` + +Register your web app: +```bash +npx -y firebase-tools@latest apps:create web my-web-app +``` +(Note the **App ID** returned by this command). + +## 2. Installation +Install the Firebase SDK via npm: + +```bash +npm install firebase +``` + +## 3. Initialization +Create a `firebase.js` (or `firebase.ts`) file. You can fetch your config object using the CLI: + +```bash +npx -y firebase-tools@latest apps:sdkconfig +``` + +Copy the output config object into your initialization file: + +```javascript +import { initializeApp } from "firebase/app"; +import { getAuth } from "firebase/auth"; + +// Your web app's Firebase configuration +const firebaseConfig = { + apiKey: "API_KEY", + authDomain: "PROJECT_ID.firebaseapp.com", + projectId: "PROJECT_ID", + storageBucket: "PROJECT_ID.firebasestorage.app", + messagingSenderId: "SENDER_ID", + appId: "APP_ID", + measurementId: "G-MEASUREMENT_ID" +}; + +// Initialize Firebase +const app = initializeApp(firebaseConfig); +const auth = getAuth(app); + +export { app }; +``` + +## 4. Using Services +Import specific services as needed (Modular API): + +```javascript +import { getFirestore, collection, getDocs } from "firebase/firestore"; +import { app } from "./firebase"; // Import the initialized app + +const db = getFirestore(app); + +async function getUsers() { + const querySnapshot = await getDocs(collection(db, "users")); + querySnapshot.forEach((doc) => { + console.log(`${doc.id} => ${doc.data()}`); + }); +} +``` diff --git a/.claude/skills/firebase-data-connect/SKILL.md b/.claude/skills/firebase-data-connect/SKILL.md new file mode 100644 index 0000000..e87a3c1 --- /dev/null +++ b/.claude/skills/firebase-data-connect/SKILL.md @@ -0,0 +1,95 @@ +--- +name: firebase-data-connect +description: Build and deploy Firebase Data Connect backends with PostgreSQL. Use for schema design, GraphQL queries/mutations, authorization, and SDK generation for web, Android, iOS, and Flutter apps. +--- + +# Firebase Data Connect + +Firebase Data Connect is a relational database service using Cloud SQL for PostgreSQL with GraphQL schema, auto-generated queries/mutations, and type-safe SDKs. + +## Project Structure + +``` +dataconnect/ +├── dataconnect.yaml # Service configuration +├── schema/ +│ └── schema.gql # Data model (types with @table) +└── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Queries + └── mutations.gql # Mutations +``` + +## Development Workflow + +Follow this strict workflow to build your application. You **must** read the linked reference files for each step to understand the syntax and available features. + +### 1. Define Data Model (`schema/schema.gql`) +Define your GraphQL types, tables, and relationships. +> **Read [reference/schema.md](reference/schema.md)** for: +> * `@table`, `@col`, `@default` +> * Relationships (`@ref`, one-to-many, many-to-many) +> * Data types (UUID, Vector, JSON, etc.) + +### 2. Define Operations (`connector/queries.gql`, `connector/mutations.gql`) +Write the queries and mutations your client will use. Data Connect generates the underlying SQL. +> **Read [reference/operations.md](reference/operations.md)** for: +> * **Queries**: Filtering (`where`), Ordering (`orderBy`), Pagination (`limit`/`offset`). +> * **Mutations**: Create (`_insert`), Update (`_update`), Delete (`_delete`). +> * **Upserts**: Use `_upsert` to "insert or update" records (CRITICAL for user profiles). +> * **Transactions**: use `@transaction` for multi-step atomic operations. + +### 3. Secure Your App (`connector/` files) +Add authorization logic closely with your operations. +> **Read [reference/security.md](reference/security.md)** for: +> * `@auth(level: ...)` for PUBLIC, USER, or NO_ACCESS. +> * `@check` and `@redact` for row-level security and validation. + +### 4. Generate & Use SDKs +Generate type-safe code for your client platform. +> **Read [reference/sdks.md](reference/sdks.md)** for: +> * Android (Kotlin), iOS (Swift), Web (TypeScript), Flutter (Dart). +> * How to initialize and call your queries/mutations. +> * **Nested Data**: See how to access related fields (e.g., `movie.reviews`). + +--- + +## Feature Capability Map + +If you need to implement a specific feature, consult the mapped reference file: + +| Feature | Reference File | Key Concepts | +| :--- | :--- | :--- | +| **Data Modeling** | [reference/schema.md](reference/schema.md) | `@table`, `@unique`, `@index`, Relations | +| **Vector Search** | [reference/advanced.md](reference/advanced.md) | `Vector`, `@col(dataType: "vector")` | +| **Full-Text Search** | [reference/advanced.md](reference/advanced.md) | `@searchable` | +| **Upserting Data** | [reference/operations.md](reference/operations.md) | `_upsert` mutations | +| **Complex Filters** | [reference/operations.md](reference/operations.md) | `_or`, `_and`, `_not`, `eq`, `contains` | +| **Transactions** | [reference/operations.md](reference/operations.md) | `@transaction`, `response` binding | +| **Environment Config** | [reference/config.md](reference/config.md) | `dataconnect.yaml`, `connector.yaml` | + +--- + +## Deployment & CLI + +> **Read [reference/config.md](reference/config.md)** for deep dive on configuration. + +Common commands (run from project root): + +```bash +# Initialize Data Connect +npx -y firebase-tools@latest init dataconnect + +# Start local emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDK code +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +## Examples + +For complete, working code examples of schemas and operations, see **[examples.md](examples.md)**. diff --git a/.claude/skills/firebase-data-connect/examples.md b/.claude/skills/firebase-data-connect/examples.md new file mode 100644 index 0000000..87a6e3d --- /dev/null +++ b/.claude/skills/firebase-data-connect/examples.md @@ -0,0 +1,377 @@ +# Examples + +Complete, working examples for common Data Connect use cases. + +--- + +## Movie Review App + +A complete schema for a movie database with reviews, actors, and user authentication. + +### Schema + +```graphql +# schema.gql + +# Users +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movies +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + releaseYear: Int + genre: String @index + rating: Float + description: String + posterUrl: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movie metadata (one-to-one) +type MovieMetadata @table { + movie: Movie! @unique + director: String + runtime: Int + budget: Int64 +} + +# Actors +type Actor @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + birthDate: Date +} + +# Movie-Actor relationship (many-to-many) +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # "lead" or "supporting" + character: String +} + +# Reviews (user-owned) +type Review @table @unique(fields: ["movie", "user"]) { + id: UUID! @default(expr: "uuidV4()") + movie: Movie! + user: User! + rating: Int! + text: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Queries + +```graphql +# queries.gql + +# Public: List movies with filtering +query ListMovies($genre: String, $minRating: Float, $limit: Int) + @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ rating: DESC }], + limit: $limit + ) { + id title genre rating releaseYear posterUrl + } +} + +# Public: Get movie with full details +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre rating releaseYear description + metadata: movieMetadata_on_movie { director runtime } + actors: actors_via_MovieActor { name } + reviews: reviews_on_movie(orderBy: [{ createdAt: DESC }], limit: 10) { + rating text createdAt + user { displayName } + } + } +} + +# User: Get my reviews +query MyReviews @auth(level: USER) { + reviews(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + id rating text createdAt + movie { id title posterUrl } + } +} +``` + +### Mutations + +```graphql +# mutations.gql + +# User: Create/update profile on first login +mutation UpsertUser($email: String!, $displayName: String) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + displayName: $displayName + }) +} + +# User: Add review (one per movie per user) +mutation AddReview($movieId: UUID!, $rating: Int!, $text: String) + @auth(level: USER) { + review_upsert(data: { + movie: { id: $movieId }, + user: { uid_expr: "auth.uid" }, + rating: $rating, + text: $text + }) +} + +# User: Delete my review +mutation DeleteReview($id: UUID!) @auth(level: USER) { + review_delete( + first: { where: { + id: { eq: $id }, + user: { uid: { eq_expr: "auth.uid" }} + }} + ) +} +``` + +--- + +## E-Commerce Store + +Products, orders, and cart management with user authentication. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String + shippingAddress: String +} + +type Product @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @index + description: String + price: Float! + stock: Int! @default(value: 0) + category: String @index + imageUrl: String +} + +type CartItem @table(key: ["user", "product"]) { + user: User! + product: Product! + quantity: Int! +} + +enum OrderStatus { + PENDING + PAID + SHIPPED + DELIVERED + CANCELLED +} + +type Order @table { + id: UUID! @default(expr: "uuidV4()") + user: User! + status: OrderStatus! @default(value: PENDING) + total: Float! + shippingAddress: String! + createdAt: Timestamp! @default(expr: "request.time") +} + +type OrderItem @table { + id: UUID! @default(expr: "uuidV4()") + order: Order! + product: Product! + quantity: Int! + priceAtPurchase: Float! +} +``` + +### Operations + +```graphql +# Public: Browse products +query ListProducts($category: String, $search: String) @auth(level: PUBLIC) { + products(where: { + category: { eq: $category }, + name: { contains: $search }, + stock: { gt: 0 } + }) { + id name price stock imageUrl + } +} + +# User: View cart +query MyCart @auth(level: USER) { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + quantity + product { id name price imageUrl stock } + } +} + +# User: Add to cart +mutation AddToCart($productId: UUID!, $quantity: Int!) @auth(level: USER) { + cartItem_upsert(data: { + user: { uid_expr: "auth.uid" }, + product: { id: $productId }, + quantity: $quantity + }) +} + +# User: Checkout (transactional) +mutation Checkout($shippingAddress: String!) + @auth(level: USER) + @transaction { + # Query cart items + query @redact { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) + @check(expr: "this.size() > 0", message: "Cart is empty") { + quantity + product { id price } + } + } + # Create order (in real app, calculate total from cart) + order_insert(data: { + user: { uid_expr: "auth.uid" }, + shippingAddress: $shippingAddress, + total: 0 # Calculate in app logic + }) +} +``` + +--- + +## Blog with Permissions + +Multi-author blog with role-based permissions. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String! + bio: String +} + +enum UserRole { + VIEWER + AUTHOR + EDITOR + ADMIN +} + +type BlogPermission @table(key: ["user"]) { + user: User! + role: UserRole! @default(value: VIEWER) +} + +enum PostStatus { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! + title: String! @searchable + content: String! @searchable + status: PostStatus! @default(value: DRAFT) + publishedAt: Timestamp + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} + +type Comment @table { + id: UUID! @default(expr: "uuidV4()") + post: Post! + author: User! + content: String! + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Operations with Role Checks + +```graphql +# Public: Read published posts +query PublishedPosts @auth(level: PUBLIC) { + posts( + where: { status: { eq: PUBLISHED }}, + orderBy: [{ publishedAt: DESC }] + ) { + id title content publishedAt + author { name } + } +} + +# Author+: Create post +mutation CreatePost($title: String!, $content: String!) + @auth(level: USER) + @transaction { + # Check user is at least AUTHOR + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) + @check(expr: "this != null", message: "No permission record") { + role @check(expr: "this in ['AUTHOR', 'EDITOR', 'ADMIN']", message: "Must be author+") + } + } + post_insert(data: { + author: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +# Editor+: Publish any post +mutation PublishPost($id: UUID!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this in ['EDITOR', 'ADMIN']", message: "Must be editor+") + } + } + post_update(id: $id, data: { + status: PUBLISHED, + publishedAt_expr: "request.time" + }) +} + +# Admin: Grant role +mutation GrantRole($userUid: String!, $role: UserRole!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this == 'ADMIN'", message: "Must be admin") + } + } + blogPermission_upsert(data: { + user: { uid: $userUid }, + role: $role + }) +} +``` diff --git a/.claude/skills/firebase-data-connect/reference/advanced.md b/.claude/skills/firebase-data-connect/reference/advanced.md new file mode 100644 index 0000000..bdffe7c --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/advanced.md @@ -0,0 +1,303 @@ +# Advanced Features Reference + +## Contents +- [Vector Similarity Search](#vector-similarity-search) +- [Full-Text Search](#full-text-search) +- [Cloud Functions Integration](#cloud-functions-integration) +- [Data Seeding & Bulk Operations](#data-seeding--bulk-operations) + +--- + +## Vector Similarity Search + +Semantic search using Vertex AI embeddings and PostgreSQL's `pgvector`. + +### Schema Setup + +```graphql +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + description: String + # Vector field for embeddings - size must match model output (768 for gecko) + descriptionEmbedding: Vector! @col(size: 768) +} +``` + +### Generate Embeddings in Mutations + +Use `_embed` server value to auto-generate embeddings via Vertex AI: + +```graphql +mutation CreateMovieWithEmbedding($title: String!, $description: String!) + @auth(level: USER) { + movie_insert(data: { + title: $title, + description: $description, + descriptionEmbedding_embed: { + model: "textembedding-gecko@003", + text: $description + } + }) +} +``` + +### Similarity Search Query + +Data Connect generates `_similarity` fields for Vector columns: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare_embed: { model: "textembedding-gecko@003", text: $query }, + method: L2, # L2, COSINE, or INNER_PRODUCT + within: 2.0, # Max distance threshold + limit: 5 + ) { + id + title + description + _metadata { distance } # See how close each result is + } +} +``` + +### Similarity Parameters + +| Parameter | Description | +|-----------|-------------| +| `compare` | Raw Vector to compare against | +| `compare_embed` | Generate embedding from text via Vertex AI | +| `method` | Distance function: `L2`, `COSINE`, `INNER_PRODUCT` | +| `within` | Max distance (results further are excluded) | +| `where` | Additional filters | +| `limit` | Max results to return | + +### Custom Embeddings + +Pass pre-computed vectors directly: + +```graphql +mutation StoreCustomEmbedding($id: UUID!, $embedding: Vector!) @auth(level: USER) { + movie_update(id: $id, data: { descriptionEmbedding: $embedding }) +} + +query SearchWithCustomVector($vector: Vector!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare: $vector, + method: COSINE, + limit: 10 + ) { id title } +} +``` + +--- + +## Full-Text Search + +Fast keyword/phrase search using PostgreSQL's full-text capabilities. + +### Enable with @searchable + +```graphql +type Movie @table { + title: String! @searchable + description: String @searchable(language: "english") + genre: String @searchable +} +``` + +### Search Query + +Data Connect generates `_search` fields: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + queryFormat: QUERY, # QUERY, PLAIN, PHRASE, or ADVANCED + limit: 20 + ) { + id title description + _metadata { relevance } # Relevance score + } +} +``` + +### Query Formats + +| Format | Description | +|--------|-------------| +| `QUERY` | Web-style (default): quotes, AND, OR supported | +| `PLAIN` | Match all words, any order | +| `PHRASE` | Match exact phrase | +| `ADVANCED` | Full tsquery syntax | + +### Tuning Results + +```graphql +query SearchWithThreshold($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + relevanceThreshold: 0.05, # Min relevance score + where: { genre: { eq: "Action" }}, + orderBy: [{ releaseYear: DESC }] + ) { id title } +} +``` + +### Supported Languages + +`english` (default), `french`, `german`, `spanish`, `italian`, `portuguese`, `dutch`, `danish`, `finnish`, `norwegian`, `swedish`, `russian`, `arabic`, `hindi`, `simple` + +--- + +## Cloud Functions Integration + +Trigger Cloud Functions when mutations execute. + +### Basic Trigger (Node.js) + +```typescript +import { onMutationExecuted } from "firebase-functions/dataconnect"; +import { logger } from "firebase-functions"; + +export const onUserCreate = onMutationExecuted( + { + service: "myService", + connector: "default", + operation: "CreateUser", + region: "us-central1" // Must match Data Connect location + }, + (event) => { + const variables = event.data.payload.variables; + const returnedData = event.data.payload.data; + + logger.info("User created:", returnedData); + // Send welcome email, sync to analytics, etc. + } +); +``` + +### Basic Trigger (Python) + +```python +from firebase_functions import dataconnect_fn, logger + +@dataconnect_fn.on_mutation_executed( + service="myService", + connector="default", + operation="CreateUser" +) +def on_user_create(event: dataconnect_fn.Event): + variables = event.data.payload.variables + returned_data = event.data.payload.data + logger.info("User created:", returned_data) +``` + +### Event Data + +```typescript +// event.authType: "app_user" | "unauthenticated" | "admin" +// event.authId: Firebase Auth UID (for app_user) +// event.data.payload.variables: mutation input variables +// event.data.payload.data: mutation response data +// event.data.payload.errors: any errors that occurred +``` + +### Filtering with Wildcards + +```typescript +// Trigger on all User* mutations +export const onUserMutation = onMutationExecuted( + { operation: "User*" }, + (event) => { /* ... */ } +); + +// Capture operation name +export const onAnyMutation = onMutationExecuted( + { service: "myService", operation: "{operationName}" }, + (event) => { + console.log("Operation:", event.params.operationName); + } +); +``` + +### Use Cases + +- **Data sync**: Replicate to Firestore, BigQuery, external APIs +- **Notifications**: Send emails, push notifications on events +- **Async workflows**: Image processing, data aggregation +- **Audit logging**: Track all data changes + +> ⚠️ **Avoid infinite loops**: Don't trigger mutations that would fire the same trigger. Use filters to exclude self-triggered events. + +--- + +## Data Seeding & Bulk Operations + +### Local Prototyping with _insertMany + +```graphql +mutation SeedMovies @transaction { + movie_insertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" }, + { id: "uuid-3", title: "Movie 3", genre: "Comedy" } + ]) +} +``` + +### Reset Data with _upsertMany + +```graphql +mutation ResetData { + movie_upsertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } + ]) +} +``` + +### Clear All Data + +```graphql +mutation ClearMovies { + movie_deleteMany(all: true) +} +``` + +### Production: Admin SDK Bulk Operations + +```typescript +import { initializeApp } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +const app = initializeApp(); +const dc = getDataConnect({ location: "us-central1", serviceId: "my-service" }); + +const movies = [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } +]; + +// Bulk insert +await dc.insertMany("movie", movies); + +// Bulk upsert +await dc.upsertMany("movie", movies); + +// Single operations +await dc.insert("movie", movies[0]); +await dc.upsert("movie", movies[0]); +``` + +### Emulator Data Persistence + +```bash +# Export emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with saved data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` diff --git a/.claude/skills/firebase-data-connect/reference/config.md b/.claude/skills/firebase-data-connect/reference/config.md new file mode 100644 index 0000000..c7e5c52 --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/config.md @@ -0,0 +1,267 @@ +# Configuration Reference + +## Contents +- [Project Structure](#project-structure) +- [dataconnect.yaml](#dataconnectyaml) +- [connector.yaml](#connectoryaml) +- [Firebase CLI Commands](#firebase-cli-commands) +- [Emulator](#emulator) +- [Deployment](#deployment) + +--- + +## Project Structure + +``` +project-root/ +├── firebase.json # Firebase project config +└── dataconnect/ + ├── dataconnect.yaml # Service configuration + ├── schema/ + │ └── schema.gql # Data model (types, relationships) + └── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Query operations + └── mutations.gql # Mutation operations (optional separate file) +``` + +--- + +## dataconnect.yaml + +Main Data Connect service configuration: + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schemaValidation: "STRICT" # or "COMPATIBLE" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +| Field | Description | +|-------|-------------| +| `specVersion` | Always `"v1"` | +| `serviceId` | Unique identifier for the service | +| `location` | GCP region (us-central1, us-east4, europe-west1, etc.) | +| `schemaValidation` | Deployment mode: `"STRICT"` (must match exactly) or `"COMPATIBLE"` (backward compatible) | +| `schema.source` | Path to schema directory | +| `schema.datasource` | PostgreSQL connection config | +| `connectorDirs` | List of connector directories | + +### Cloud SQL Configuration + +```yaml +schema: + datasource: + postgresql: + database: "my-database" # Database name + cloudSql: + instanceId: "my-instance" # Cloud SQL instance ID +``` + +--- + +## connector.yaml + +Connector configuration and SDK generation: + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" +``` + +### SDK Generation Options + +| SDK | Fields | +|-----|--------| +| `javascriptSdk` | `outputDir`, `package` | +| `kotlinSdk` | `outputDir`, `package` | +| `swiftSdk` | `outputDir` | +| `nodeAdminSdk` | `outputDir`, `package` (for Admin SDK) | + +--- + +## Firebase CLI Commands + +### Initialize Data Connect + +```bash +# Interactive setup +npx -y firebase-tools@latest init dataconnect + +# Set project +npx -y firebase-tools@latest use +``` + +### Local Development + +```bash +# Start emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Start with database seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Watch for schema changes (auto-regenerate) +npx -y firebase-tools@latest dataconnect:sdk:generate --watch +``` + +### Schema Management + +```bash +# Compare local schema to production +npx -y firebase-tools@latest dataconnect:sql:diff + + +# Apply migration +npx -y firebase-tools@latest dataconnect:sql:migrate +``` + +### Deployment + +```bash +# Deploy Data Connect service +npx -y firebase-tools@latest deploy --only dataconnect + +# Deploy specific connector +npx -y firebase-tools@latest deploy --only dataconnect:connector-id + +# Deploy with schema migration +npx -y firebase-tools@latest deploy --only dataconnect --force +``` + +--- + +## Emulator + +### Start Emulator + +```bash +npx -y firebase-tools@latest emulators:start --only dataconnect +``` + +Default ports: +- Data Connect: `9399` +- PostgreSQL: `9939` (local PostgreSQL instance) + +### Emulator Configuration (firebase.json) + +```json +{ + "emulators": { + "dataconnect": { + "port": 9399 + } + } +} +``` + +### Connect from SDK + +```typescript +// Web +import { connectDataConnectEmulator } from 'firebase/data-connect'; +connectDataConnectEmulator(dc, 'localhost', 9399); + +// Android +connector.dataConnect.useEmulator("10.0.2.2", 9399) + +// iOS +connector.useEmulator(host: "localhost", port: 9399) + + +``` + +### Seed Data + +Create seed data files and import: + +```bash +# Export current emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` + +--- + +## Deployment + +### Deploy Workflow + +1. **Test locally** with emulator +2. **Generate SQL diff**: `npx -y firebase-tools@latest dataconnect:sql:diff` +3. **Review migration**: Check breaking changes +4. **Deploy**: `npx -y firebase-tools@latest deploy --only dataconnect` + +### Schema Migrations + +Data Connect auto-generates PostgreSQL migrations: + +```bash +# Preview migration +npx -y firebase-tools@latest dataconnect:sql:diff + +# Apply migration (interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate + +# Force migration (non-interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate --force +``` + +### Breaking Changes + +Some schema changes require special handling: +- Removing required fields +- Changing field types +- Removing tables + +Use `--force` flag to acknowledge breaking changes during deploy. + +### CI/CD Integration + +```yaml +# GitHub Actions example +- name: Deploy Data Connect + run: | + npx -y firebase-tools@latest deploy --only dataconnect --token ${{ secrets.FIREBASE_TOKEN }} --force +``` + +--- + +## VS Code Extension + +Install "Firebase Data Connect" extension for: +- Schema intellisense and validation +- GraphQL operation testing +- Emulator integration +- SDK generation on save + +### Extension Settings + +```json +{ + "firebase.dataConnect.autoGenerateSdk": true, + "firebase.dataConnect.emulator.port": 9399 +} +``` diff --git a/.claude/skills/firebase-data-connect/reference/operations.md b/.claude/skills/firebase-data-connect/reference/operations.md new file mode 100644 index 0000000..6fe7e73 --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/operations.md @@ -0,0 +1,357 @@ +# Operations Reference + +## Contents +- [Generated Fields](#generated-fields) +- [Queries](#queries) +- [Mutations](#mutations) +- [Key Scalars](#key-scalars) +- [Multi-Step Operations](#multi-step-operations) + +--- + +## Generated Fields + +Data Connect auto-generates fields for each `@table` type: + +| Generated Field | Purpose | Example | +|-----------------|---------|---------| +| `movie(id: UUID, key: Key, first: Row)` | Get single record | `movie(id: $id)` or `movie(first: {where: ...})` | +| `movies(where: ..., orderBy: ..., limit: ..., offset: ..., distinct: ..., having: ...)` | List/filter records | `movies(where: {...})` | +| `movie_insert(data: ...)` | Create record | Returns key | +| `movie_insertMany(data: [...])` | Bulk create | Returns keys | +| `movie_update(id: ..., data: ...)` | Update by ID | Returns key or null | +| `movie_updateMany(where: ..., data: ...)` | Bulk update | Returns count | +| `movie_upsert(data: ...)` | Insert or update | Returns key | +| `movie_delete(id: ...)` | Delete by ID | Returns key or null | +| `movie_deleteMany(where: ...)` | Bulk delete | Returns count | + +### Relation Fields +For a `Post` with `author: User!`: +- `post.author` - Navigate to related User +- `user.posts_on_author` - Reverse: all Posts by User + +For many-to-many via `MovieActor`: +- `movie.actors_via_MovieActor` - Get all actors +- `actor.movies_via_MovieActor` - Get all movies + +--- + +## Queries + +### Basic Query + +```graphql +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre releaseYear + } +} +``` + +### List with Filtering + +```graphql +query ListMovies($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ releaseYear: DESC }, { title: ASC }], + limit: 20, + offset: 0 + ) { + id title genre rating + } +} +``` + +### Filter Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `eq` | Equals | `{ title: { eq: "Matrix" }}` | +| `ne` | Not equals | `{ status: { ne: "deleted" }}` | +| `gt`, `ge` | Greater than (or equal) | `{ rating: { ge: 4 }}` | +| `lt`, `le` | Less than (or equal) | `{ releaseYear: { lt: 2000 }}` | +| `in` | In list | `{ genre: { in: ["Action", "Drama"] }}` | +| `nin` | Not in list | `{ status: { nin: ["deleted", "hidden"] }}` | +| `isNull` | Is null check | `{ description: { isNull: true }}` | +| `contains` | String contains | `{ title: { contains: "war" }}` | +| `startsWith` | String starts with | `{ title: { startsWith: "The" }}` | +| `endsWith` | String ends with | `{ email: { endsWith: "@gmail.com" }}` | +| `includes` | Array includes | `{ tags: { includes: "sci-fi" }}` | + +### Expression Operators (Compare with Server Values) + +Use `_expr` suffix to compare with server-side values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +query RecentPosts @auth(level: PUBLIC) { + posts(where: { publishedAt: { lt_expr: "request.time" }}) { + id title + } +} +``` + +### Logical Operators + +```graphql +query ComplexFilter($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies(where: { + _or: [ + { genre: { eq: $genre }}, + { rating: { ge: $minRating }} + ], + _and: [ + { releaseYear: { ge: 2000 }}, + { status: { ne: "hidden" }} + ], + _not: { genre: { eq: "Horror" }} + }) { id title } +} +``` + +### Relational Queries + +```graphql +# Navigate relationships +query MovieWithDetails($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + title + # One-to-one + metadata: movieMetadata_on_movie { director } + # One-to-many + reviews: reviews_on_movie { rating user { name }} + # Many-to-many + actors: actors_via_MovieActor { name } + } +} + +# Filter by related data +query MoviesByDirector($director: String!) @auth(level: PUBLIC) { + movies(where: { + movieMetadata_on_movie: { director: { eq: $director }} + }) { id title } +} +``` + +### Aliases + +```graphql +query CompareRatings($genre: String!) @auth(level: PUBLIC) { + highRated: movies(where: { genre: { eq: $genre }, rating: { ge: 8 }}) { + title rating + } + lowRated: movies(where: { genre: { eq: $genre }, rating: { lt: 5 }}) { + title rating + } +} +``` + +--- + +## Mutations + +### Create + +```graphql +mutation CreateMovie($title: String!, $genre: String) @auth(level: USER) { + movie_insert(data: { + title: $title, + genre: $genre + }) +} +``` + +### Create with Server Values + +```graphql +mutation CreatePost($title: String!, $content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", # Current user + id_expr: "uuidV4()", # Auto-generate UUID + createdAt_expr: "request.time", # Server timestamp + title: $title, + content: $content + }) +} +``` + +### Update + +```graphql +mutation UpdateMovie($id: UUID!, $title: String, $genre: String) @auth(level: USER) { + movie_update( + id: $id, + data: { + title: $title, + genre: $genre, + updatedAt_expr: "request.time" + } + ) +} +``` + +### Update Operators + +```graphql +mutation IncrementViews($id: UUID!) @auth(level: PUBLIC) { + movie_update(id: $id, data: { + viewCount_update: { inc: 1 } + }) +} + +mutation AddTag($id: UUID!, $tag: String!) @auth(level: USER) { + movie_update(id: $id, data: { + tags_update: { add: [$tag] } # add, remove, append, prepend + }) +} +``` + +| Operator | Types | Description | +|----------|-------|-------------| +| `inc` | Int, Float, Date, Timestamp | Increment value | +| `dec` | Int, Float, Date, Timestamp | Decrement value | +| `add` | Lists | Add items if not present | +| `remove` | Lists | Remove all matching items | +| `append` | Lists | Append to end | +| `prepend` | Lists | Prepend to start | + +### Upsert + +```graphql +mutation UpsertUser($email: String!, $name: String!) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + name: $name + }) +} +``` + +### Delete + +```graphql +mutation DeleteMovie($id: UUID!) @auth(level: USER) { + movie_delete(id: $id) +} + +mutation DeleteOldDrafts @auth(level: USER) { + post_deleteMany(where: { + status: { eq: "draft" }, + createdAt: { lt_time: { now: true, sub: { days: 30 }}} + }) +} +``` + +### Filtered Updates/Deletes (User-Owned) + +```graphql +mutation UpdateMyPost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } # Only own posts + }}, + data: { content: $content } + ) +} +``` + +--- + +## Key Scalars + +Key scalars (`Movie_Key`, `User_Key`) are auto-generated types representing primary keys: + +```graphql +# Using key scalar +query GetMovie($key: Movie_Key!) @auth(level: PUBLIC) { + movie(key: $key) { title } +} + +# Variable format +# { "key": { "id": "uuid-here" } } + +# Composite key +# { "key": { "movieId": "...", "userId": "..." } } +``` + +Key scalars are returned by mutations: + +```graphql +mutation CreateAndFetch($title: String!) @auth(level: USER) { + key: movie_insert(data: { title: $title }) + # Returns: { "key": { "id": "generated-uuid" } } +} +``` + +--- + +## Multi-Step Operations + +### @transaction + +Ensures atomicity - all steps succeed or all rollback: + +```graphql +mutation CreateUserWithProfile($name: String!, $bio: String!) + @auth(level: USER) + @transaction { + # Step 1: Create user + user_insert(data: { + uid_expr: "auth.uid", + name: $name + }) + # Step 2: Create profile (uses response from step 1) + userProfile_insert(data: { + userId_expr: "response.user_insert.uid", + bio: $bio + }) +} +``` + +### Using response Binding + +Access results from previous steps: + +```graphql +mutation CreateTodoWithItem($listName: String!, $itemText: String!) + @auth(level: USER) + @transaction { + todoList_insert(data: { + id_expr: "uuidV4()", + name: $listName + }) + todoItem_insert(data: { + listId_expr: "response.todoList_insert.id", # From previous step + text: $itemText + }) +} +``` + +### Embedded Queries + +Run queries within mutations for validation: + +```graphql +mutation AddToPublicList($listId: UUID!, $item: String!) + @auth(level: USER) + @transaction { + # Step 1: Verify list exists and is public + query @redact { + todoList(id: $listId) @check(expr: "this != null", message: "List not found") { + isPublic @check(expr: "this == true", message: "List is not public") + } + } + # Step 2: Add item + todoItem_insert(data: { listId: $listId, text: $item }) +} +``` diff --git a/.claude/skills/firebase-data-connect/reference/schema.md b/.claude/skills/firebase-data-connect/reference/schema.md new file mode 100644 index 0000000..21d34ec --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/schema.md @@ -0,0 +1,278 @@ +# Schema Reference + +## Contents +- [Defining Types](#defining-types) +- [Core Directives](#core-directives) +- [Relationships](#relationships) +- [Data Types](#data-types) +- [Enumerations](#enumerations) + +--- + +## Defining Types + +Types with `@table` map to PostgreSQL tables. Data Connect auto-generates an implicit `id: UUID!` primary key. + +```graphql +type Movie @table { + # id: UUID! is auto-added + title: String! + releaseYear: Int + genre: String +} +``` + +### Customizing Tables + +```graphql +type Movie @table(name: "movies", key: "id", singular: "movie", plural: "movies") { + id: UUID! @col(name: "movie_id") @default(expr: "uuidV4()") + title: String! + releaseYear: Int @col(name: "release_year") + genre: String @col(dataType: "varchar(20)") +} +``` + +### User Table with Auth + +```graphql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String @col(dataType: "varchar(100)") + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +--- + +## Core Directives + +### @table +Defines a database table. + +| Argument | Description | +|----------|-------------| +| `name` | PostgreSQL table name (snake_case default) | +| `key` | Primary key field(s), default `["id"]` | +| `singular` | Singular name for generated fields | +| `plural` | Plural name for generated fields | + +### @col +Customizes column mapping. + +| Argument | Description | +|----------|-------------| +| `name` | Column name in PostgreSQL | +| `dataType` | PostgreSQL type: `serial`, `varchar(n)`, `text`, etc. | +| `size` | Required for `Vector` type | + +### @default +Sets default value for inserts. + +| Argument | Description | +|----------|-------------| +| `value` | Literal value: `@default(value: "draft")` | +| `expr` | CEL expression: `@default(expr: "uuidV4()")`, `@default(expr: "auth.uid")`, `@default(expr: "request.time")` | +| `sql` | Raw SQL: `@default(sql: "now()")` | + +**Common expressions:** +- `uuidV4()` - Generate UUID +- `auth.uid` - Current user's Firebase Auth UID +- `request.time` - Server timestamp + +### @unique +Adds unique constraint. + +```graphql +type User @table { + email: String! @unique +} + +# Composite unique +type Review @table @unique(fields: ["movie", "user"]) { + movie: Movie! + user: User! + rating: Int +} +``` + +### @index +Creates database index for query performance. + +```graphql +type Movie @table @index(fields: ["genre", "releaseYear"], order: [ASC, DESC]) { + title: String! @index + genre: String + releaseYear: Int +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Fields for composite index (on @table) | +| `order` | `[ASC]` or `[DESC]` for each field | +| `type` | `BTREE` (default), `GIN` (arrays), `HNSW`/`IVFFLAT` (vectors) | + +### @searchable +Enables full-text search on String fields. + +```graphql +type Post @table { + title: String! @searchable + body: String! @searchable(language: "english") +} + +# Usage +query SearchPosts($q: String!) @auth(level: PUBLIC) { + posts_search(query: $q) { id title body } +} +``` + +--- + +## Relationships + +### One-to-Many (Implicit Foreign Key) + +```graphql +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! # Creates authorId foreign key + title: String! +} + +type User @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + # Auto-generated: posts_on_author: [Post!]! +} +``` + +### @ref Directive +Customizes foreign key reference. + +```graphql +type Post @table { + author: User! @ref(fields: "authorId", references: "id") + authorId: UUID! # Explicit FK field +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Local FK field name(s) | +| `references` | Target field(s) in referenced table | +| `constraintName` | PostgreSQL constraint name | + +**Cascade behavior:** +- Required reference (`User!`): CASCADE DELETE (post deleted when user deleted) +- Optional reference (`User`): SET NULL (authorId set to null when user deleted) + +### One-to-One + +Use `@unique` on the reference field: + +```graphql +type User @table { id: UUID! name: String! } + +type UserProfile @table { + user: User! @unique # One profile per user + bio: String + avatarUrl: String +} + +# Query: user.userProfile_on_user +``` + +### Many-to-Many + +Use a join table with composite primary key: + +```graphql +type Movie @table { id: UUID! title: String! } +type Actor @table { id: UUID! name: String! } + +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # Extra data on relationship +} + +# Generated fields: +# - movie.actors_via_MovieActor: [Actor!]! +# - actor.movies_via_MovieActor: [Movie!]! +# - movie.movieActors_on_movie: [MovieActor!]! +``` + +--- + +## Data Types + +| GraphQL Type | PostgreSQL Default | Other PostgreSQL Types | +|--------------|-------------------|----------------------| +| `String` | `text` | `varchar(n)`, `char(n)` | +| `Int` | `int4` | `int2`, `serial` | +| `Int64` | `bigint` | `bigserial`, `numeric` | +| `Float` | `float8` | `float4`, `numeric` | +| `Boolean` | `boolean` | | +| `UUID` | `uuid` | | +| `Date` | `date` | | +| `Timestamp` | `timestamptz` | Stored as UTC | +| `Any` | `jsonb` | | +| `Vector` | `vector` | Requires `@col(size: N)` | +| `[Type]` | Array | e.g., `[String]` → `text[]` | + +--- + +## Enumerations + +```graphql +enum Status { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + status: Status! @default(value: DRAFT) + allowedStatuses: [Status!] +} +``` + +**Rules:** +- Enum names: PascalCase, no underscores +- Enum values: UPPER_SNAKE_CASE +- Values are ordered (for comparison operations) +- Changing order or removing values is a breaking change + +--- + +## Views (Advanced) + +Map custom SQL queries to GraphQL types: + +```graphql +type MovieStats @view(sql: """ + SELECT + movie_id, + COUNT(*) as review_count, + AVG(rating) as avg_rating + FROM review + GROUP BY movie_id +""") { + movie: Movie @unique + reviewCount: Int + avgRating: Float +} + +# Query movies with stats +query TopMovies @auth(level: PUBLIC) { + movies(orderBy: [{ rating: DESC }]) { + title + stats: movieStats_on_movie { + reviewCount avgRating + } + } +} +``` diff --git a/.claude/skills/firebase-data-connect/reference/sdks.md b/.claude/skills/firebase-data-connect/reference/sdks.md new file mode 100644 index 0000000..9885056 --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/sdks.md @@ -0,0 +1,287 @@ +# SDK Reference + +## Contents +- [SDK Generation](#sdk-generation) +- [Web SDK](#web-sdk) +- [Android SDK](#android-sdk) +- [iOS SDK](#ios-sdk) +- [Admin SDK](#admin-sdk) + +--- + +## SDK Generation + +Configure SDK generation in `connector.yaml`: + +```yaml +connectorId: my-connector +generate: + javascriptSdk: + outputDir: "../web-app/src/lib/dataconnect" + package: "@movie-app/dataconnect" + kotlinSdk: + outputDir: "../android-app/app/src/main/kotlin/com/example/dataconnect" + package: "com.example.dataconnect" + swiftSdk: + outputDir: "../ios-app/DataConnect" +``` + +Generate SDKs: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` + +--- + +## Web SDK + +### Installation + +```bash +npm install firebase +``` + +### Initialization + +```typescript +import { initializeApp } from 'firebase/app'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@movie-app/dataconnect'; + +const app = initializeApp(firebaseConfig); +const dc = getDataConnect(app, connectorConfig); + +// For local development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dc, 'localhost', 9399); +} +``` + +### Calling Operations + +```typescript +// Generated SDK provides typed functions +import { listMovies, createMovie, getMovie } from '@movie-app/dataconnect'; + +// Accessing Nested Fields +const movie = await getMovie({ id: '...' }); +// Relations are just properties on the object +const director = movie.data.movie.metadata.director; +const firstActor = movie.data.movie.actors[0].name; + +// Query +const result = await listMovies(); +console.log(result.data.movies); + +// Query with variables +const movie = await getMovie({ id: 'uuid-here' }); + +// Mutation +const newMovie = await createMovie({ + title: 'New Movie', + genre: 'Action' +}); +console.log(newMovie.data.movie_insert); // Returns key +``` + +### Subscriptions + +```typescript +import { listMoviesRef, subscribe } from '@movie-app/dataconnect'; + +const unsubscribe = subscribe(listMoviesRef(), { + onNext: (result) => { + console.log('Movies updated:', result.data.movies); + }, + onError: (error) => { + console.error('Subscription error:', error); + } +}); + +// Later: unsubscribe(); +``` + +### With Authentication + +```typescript +import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; + +const auth = getAuth(app); +await signInWithEmailAndPassword(auth, email, password); + +// SDK automatically includes auth token in requests +const myReviews = await myReviews(); // @auth(level: USER) query from examples.md +``` + +--- + +## Android SDK + +### Dependencies (build.gradle.kts) + +```kotlin +dependencies { + implementation(platform("com.google.firebase:firebase-bom:33.0.0")) + implementation("com.google.firebase:firebase-dataconnect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.0") +} +``` + +### Initialization + +```kotlin +import com.google.firebase.Firebase +import com.google.firebase.dataconnect.dataConnect +import com.example.dataconnect.MyConnector + +val connector = MyConnector.instance + +// For emulator +connector.dataConnect.useEmulator("10.0.2.2", 9399) +``` + +### Calling Operations + +```kotlin +// Query +val result = connector.listMovies.execute() +result.data.movies.forEach { movie -> + println(movie.title) + // Access nested fields directly + println(movie.metadata?.director) + println(movie.actors.firstOrNull()?.name) +} + +// Query with variables +val movie = connector.getMovie.execute(id = "uuid-here") + +// Mutation +val newMovie = connector.createMovie.execute( + title = "New Movie", + genre = "Action" +) +``` + +### Flow Subscription + +```kotlin +connector.listMovies.flow().collect { result -> + when (result) { + is DataConnectResult.Success -> updateUI(result.data.movies) + is DataConnectResult.Error -> showError(result.exception) + } +} +``` + +--- + +## iOS SDK + +### Dependencies (Package.swift or SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "11.0.0") +] +// Add FirebaseDataConnect to target dependencies +``` + +### Initialization + +```swift +import FirebaseCore +import FirebaseDataConnect + +FirebaseApp.configure() +let connector = MyConnector.shared + +// For emulator +connector.useEmulator(host: "localhost", port: 9399) +``` + +### Calling Operations + +```swift +// Query +let result = try await connector.listMovies.execute() +for movie in result.data.movies { + print(movie.title) + // Access nested fields directly + print(movie.metadata?.director ?? "Unknown") + print(movie.actors.first?.name ?? "No actors") +} + +// Query with variables +let movie = try await connector.getMovie.execute(id: "uuid-here") + +// Mutation +let newMovie = try await connector.createMovie.execute( + title: "New Movie", + genre: "Action" +) +``` + +### Combine Publisher + +```swift +connector.listMovies.publisher + .sink( + receiveCompletion: { completion in + if case .failure(let error) = completion { + print("Error: \(error)") + } + }, + receiveValue: { result in + self.movies = result.data.movies + } + ) + .store(in: &cancellables) +``` + +--- + + + +## Admin SDK + +Server-side operations with elevated privileges (bypasses @auth): + +### Node.js + +```typescript +import { initializeApp, cert } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +initializeApp({ + credential: cert(serviceAccount) +}); + +const dc = getDataConnect(); + +// Execute operations (bypasses @auth) +const result = await dc.executeGraphql({ + query: `query { users { id email } }`, + operationName: 'ListAllUsers' +}); + +// Or use generated Admin SDK +import { listAllUsers } from './admin-connector'; +const users = await listAllUsers(); +``` + +### Generate Admin SDK + +In `connector.yaml`: + +```yaml +generate: + nodeAdminSdk: + outputDir: "./admin-sdk" + package: "@app/admin-dataconnect" +``` + +Generate: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` diff --git a/.claude/skills/firebase-data-connect/reference/security.md b/.claude/skills/firebase-data-connect/reference/security.md new file mode 100644 index 0000000..5eacee8 --- /dev/null +++ b/.claude/skills/firebase-data-connect/reference/security.md @@ -0,0 +1,289 @@ +# Security Reference + +## Contents +- [@auth Directive](#auth-directive) +- [Access Levels](#access-levels) +- [CEL Expressions](#cel-expressions) +- [@check and @redact](#check-and-redact) +- [Authorization Patterns](#authorization-patterns) +- [Anti-Patterns](#anti-patterns) + +--- + +## @auth Directive + +Every deployable query/mutation must have `@auth`. Without it, operations default to `NO_ACCESS`. + +```graphql +query PublicData @auth(level: PUBLIC) { ... } +query UserData @auth(level: USER) { ... } +query AdminOnly @auth(expr: "auth.token.admin == true") { ... } +``` + +| Argument | Description | +|----------|-------------| +| `level` | Preset access level | +| `expr` | CEL expression (alternative to level) | +| `insecureReason` | Suppress deploy warning for PUBLIC/unfiltered USER | + +--- + +## Access Levels + +| Level | Who Can Access | CEL Equivalent | +|-------|----------------|----------------| +| `PUBLIC` | Anyone, authenticated or not | `true` | +| `USER_ANON` | Any authenticated user (including anonymous) | `auth.uid != nil` | +| `USER` | Authenticated users (excludes anonymous) | `auth.uid != nil && auth.token.firebase.sign_in_provider != 'anonymous'` | +| `USER_EMAIL_VERIFIED` | Users with verified email | `auth.uid != nil && auth.token.email_verified` | +| `NO_ACCESS` | Admin SDK only | `false` | + +> **Important:** Levels like `USER` are starting points. Always add filters or expressions to verify the user can access specific data. + +--- + +## CEL Expressions + +### Available Bindings + +| Binding | Description | +|---------|-------------| +| `auth.uid` | Current user's Firebase UID | +| `auth.token` | Auth token claims (see below) | +| `vars` | Operation variables (e.g., `vars.movieId`) | +| `request.time` | Server timestamp | +| `request.operationName` | "query" or "mutation" | + +### auth.token Fields + +| Field | Description | +|-------|-------------| +| `email` | User's email address | +| `email_verified` | Boolean: email verified | +| `phone_number` | User's phone | +| `name` | Display name | +| `sub` | Firebase UID (same as auth.uid) | +| `firebase.sign_in_provider` | `password`, `google.com`, `anonymous`, etc. | +| `` | Custom claims set via Admin SDK | + +### Expression Examples + +```graphql +# Check custom claim +@auth(expr: "auth.token.role == 'admin'") + +# Check verified email domain +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") + +# Check multiple conditions +@auth(expr: "auth.uid != nil && (auth.token.role == 'editor' || auth.token.role == 'admin')") + +# Check variable +@auth(expr: "has(vars.status) && vars.status in ['draft', 'published']") +``` + +### Using eq_expr in Filters + +Compare database fields with auth values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +mutation UpdateMyPost($id: UUID!, $title: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } + }}, + data: { title: $title } + ) +} +``` + +--- + +## @check and @redact + +Use `@check` to validate data and `@redact` to hide results from client: + +### @check +Validates a field value; aborts if check fails. + +```graphql +@check(expr: "this != null", message: "Not found") +@check(expr: "this == 'editor'", message: "Must be editor") +@check(expr: "this.exists(p, p.role == 'admin')", message: "No admin found") +``` + +| Argument | Description | +|----------|-------------| +| `expr` | CEL expression; `this` = current field value | +| `message` | Error message if check fails | +| `optional` | If `true`, pass when field not present | + +### @redact +Hides field from response (still evaluated for @check): + +```graphql +query @redact { ... } # Query result hidden but @check still runs +``` + +### Authorization Data Lookup + +Check database permissions before allowing mutation: + +```graphql +mutation UpdateMovie($id: UUID!, $title: String!) + @auth(level: USER) + @transaction { + # Step 1: Check user has permission + query @redact { + moviePermission( + key: { movieId: $id, userId_expr: "auth.uid" } + ) @check(expr: "this != null", message: "No access to movie") { + role @check(expr: "this == 'editor'", message: "Must be editor") + } + } + # Step 2: Update if authorized + movie_update(id: $id, data: { title: $title }) +} +``` + +### Validate Key Exists + +```graphql +mutation MustDeleteMovie($id: UUID!) @auth(level: USER) @transaction { + movie_delete(id: $id) + @check(expr: "this != null", message: "Movie not found") +} +``` + +--- + +## Authorization Patterns + +### User-Owned Resources + +```graphql +# Create with owner +mutation CreatePost($content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", + content: $content + }) +} + +# Read own data only +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id content + } +} + +# Update own data only +mutation UpdatePost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}}, + data: { content: $content } + ) +} + +# Delete own data only +mutation DeletePost($id: UUID!) @auth(level: USER) { + post_delete( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}} + ) +} +``` + +### Role-Based Access + +```graphql +# Admin-only query +query AllUsers @auth(expr: "auth.token.admin == true") { + users { id email name } +} + +# Role from database +mutation AdminAction($id: UUID!) @auth(level: USER) @transaction { + query @redact { + user(key: { uid_expr: "auth.uid" }) { + role @check(expr: "this == 'admin'", message: "Admin required") + } + } + # ... admin action +} +``` + +### Public Data with Filters + +```graphql +query PublicPosts @auth(level: PUBLIC) { + posts(where: { + visibility: { eq: "public" }, + publishedAt: { lt_expr: "request.time" } + }) { + id title content + } +} +``` + +### Tiered Access (Pro Content) + +```graphql +query ProContent @auth(expr: "auth.token.plan == 'pro'") { + posts(where: { visibility: { in: ["public", "pro"] }}) { + id title content + } +} +``` + +--- + +## Anti-Patterns + +### ❌ Don't Pass User ID as Variable + +```graphql +# BAD - any user can pass any userId +query GetUserPosts($userId: String!) @auth(level: USER) { + posts(where: { authorUid: { eq: $userId }}) { ... } +} + +# GOOD - use auth.uid +query GetMyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Use USER Without Filters + +```graphql +# BAD - any authenticated user sees all documents +query AllDocs @auth(level: USER) { + documents { id title content } +} + +# GOOD - filter to user's documents +query MyDocs @auth(level: USER) { + documents(where: { ownerId: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Trust Unverified Email + +```graphql +# BAD - email not verified +@auth(expr: "auth.token.email.endsWith('@company.com')") + +# GOOD - verify email first +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") +``` + +### ❌ Don't Use PUBLIC/USER for Prototyping + +During development, set operations to `NO_ACCESS` until you implement proper authorization. Use emulator and VS Code extension for testing. diff --git a/.claude/skills/firebase-data-connect/templates.md b/.claude/skills/firebase-data-connect/templates.md new file mode 100644 index 0000000..75d20dc --- /dev/null +++ b/.claude/skills/firebase-data-connect/templates.md @@ -0,0 +1,269 @@ +# Templates + +Ready-to-use templates for common Firebase Data Connect patterns. + +--- + +## Basic CRUD Schema + +```graphql +# schema.gql +type Item @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + description: String + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query ListItems @auth(level: PUBLIC) { + items(orderBy: [{ createdAt: DESC }]) { + id name description createdAt + } +} + +query GetItem($id: UUID!) @auth(level: PUBLIC) { + item(id: $id) { id name description createdAt updatedAt } +} +``` + +```graphql +# mutations.gql +mutation CreateItem($name: String!, $description: String) @auth(level: USER) { + item_insert(data: { name: $name, description: $description }) +} + +mutation UpdateItem($id: UUID!, $name: String, $description: String) @auth(level: USER) { + item_update(id: $id, data: { + name: $name, + description: $description, + updatedAt_expr: "request.time" + }) +} + +mutation DeleteItem($id: UUID!) @auth(level: USER) { + item_delete(id: $id) +} +``` + +--- + +## User-Owned Resources + +```graphql +# schema.gql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String +} + +type Note @table { + id: UUID! @default(expr: "uuidV4()") + owner: User! + title: String! + content: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query MyNotes @auth(level: USER) { + notes( + where: { owner: { uid: { eq_expr: "auth.uid" }}}, + orderBy: [{ createdAt: DESC }] + ) { id title content createdAt } +} + +query GetMyNote($id: UUID!) @auth(level: USER) { + note( + first: { where: { + id: { eq: $id }, + owner: { uid: { eq_expr: "auth.uid" }} + }} + ) { id title content } +} +``` + +```graphql +# mutations.gql +mutation CreateNote($title: String!, $content: String) @auth(level: USER) { + note_insert(data: { + owner: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +mutation UpdateNote($id: UUID!, $title: String, $content: String) @auth(level: USER) { + note_update( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}}, + data: { title: $title, content: $content } + ) +} + +mutation DeleteNote($id: UUID!) @auth(level: USER) { + note_delete( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}} + ) +} +``` + +--- + +## Many-to-Many Relationship + +```graphql +# schema.gql +type Tag @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @unique +} + +type Article @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + content: String! +} + +type ArticleTag @table(key: ["article", "tag"]) { + article: Article! + tag: Tag! +} +``` + +```graphql +# queries.gql +query ArticlesByTag($tagName: String!) @auth(level: PUBLIC) { + articles(where: { + articleTags_on_article: { tag: { name: { eq: $tagName }}} + }) { + id title + tags: tags_via_ArticleTag { name } + } +} + +query ArticleWithTags($id: UUID!) @auth(level: PUBLIC) { + article(id: $id) { + id title content + tags: tags_via_ArticleTag { id name } + } +} +``` + +```graphql +# mutations.gql +mutation AddTagToArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_insert(data: { + article: { id: $articleId }, + tag: { id: $tagId } + }) +} + +mutation RemoveTagFromArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_delete(key: { articleId: $articleId, tagId: $tagId }) +} +``` + +--- + +## dataconnect.yaml Template + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +--- + +## connector.yaml Template + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" + dartSdk: + outputDir: "../flutter/lib/dataconnect" + package: myapp_dataconnect +``` + +--- + +## Firebase Init Commands + +```bash +# Initialize Data Connect in project +npx -y firebase-tools@latest init dataconnect + +# Initialize with specific project +npx -y firebase-tools@latest use +npx -y firebase-tools@latest init dataconnect + +# Start emulator for development +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +--- + +## SDK Initialization (Web) + +```typescript +// lib/firebase.ts +import { initializeApp } from 'firebase/app'; +import { getAuth } from 'firebase/auth'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@myapp/dataconnect'; + +const firebaseConfig = { + apiKey: "...", + authDomain: "...", + projectId: "...", +}; + +export const app = initializeApp(firebaseConfig); +export const auth = getAuth(app); +export const dataConnect = getDataConnect(app, connectorConfig); + +// Connect to emulator in development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dataConnect, 'localhost', 9399); +} +``` + +```typescript +// Example usage +import { listItems, createItem } from '@myapp/dataconnect'; + +// List items +const { data } = await listItems(); +console.log(data.items); + +// Create item (requires auth) +await createItem({ name: 'New Item', description: 'Description' }); +``` diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/SKILL.md b/.claude/skills/firebase-firestore-enterprise-native-mode/SKILL.md new file mode 100644 index 0000000..1eeb40f --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/SKILL.md @@ -0,0 +1,31 @@ +--- +name: firebase-firestore-enterprise-native-mode +description: Comprehensive guide for Firestore enterprise native including provisioning, data model, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore Enterprise with the Native mode, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Enterprise Native Mode + +This skill provides a complete guide for getting started with Firestore Enterprise Native Mode, including provisioning, data model, security rules, and SDK usage. + +## Provisioning + +To set up Firestore Enterprise Native Mode in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Data Model + +To learn about Firestore data model and how to organize your data, see [data_model.md](references/data_model.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Firestore Enterprise Native Mode in your application code, see: +- [Web SDK Usage](references/web_sdk_usage.md) +- [Python SDK Usage](references/python_sdk_usage.md) + +## Indexes + +Indexes help improve query performance and speed up slow queries. For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/data_model.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/data_model.md new file mode 100644 index 0000000..0fe42c0 --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/data_model.md @@ -0,0 +1,54 @@ +# Firestore Data Model Reference + +Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in **documents**, which are organized into **collections**. + +## Document Data Model + +Data in Firestore is organized into documents, collections, and subcollections. + +### Documents +A **document** is a lightweight record that contains fields, which map to values. Each document is identified by a name. A document can contain complex nested objects in addition to basic data types like strings, numbers, and booleans. Documents are limited to a maximum size of 1 MiB. + +Example document (e.g., in a `users` collection): +```json +{ + "first": "Ada", + "last": "Lovelace", + "born": 1815 +} +``` + +### Collections +Documents live in **collections**, which are containers for your documents. For example, you could have a `users` collection to contain your various users, each represented by a document. +* Collections can only contain documents. They cannot directly contain raw fields with values, and they cannot contain other collections. +* Documents within a collection can contain different fields. +* You don't need to "create" or "delete" collections explicitly. After you create the first document in a collection, the collection exists. If you delete all of the documents in a collection, the collection no longer exists. + +### Subcollections +Documents can contain subcollections natively. A subcollection is a collection associated with a specific document. +For example, a user document in the `users` collection could have a `messages` subcollection containing message documents exclusively for that user. This creates a powerful hierarchical data structure. + +Data path example: `users/user1/messages/message1` + +## Collection Group Support + +A **collection group** consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection. + +### Use Cases +Collection group queries are useful when you want to query across multiple subcollections that share the same organizational structure. + +For example, imagine an app with a `landmarks` collection where each landmark has a `reviews` subcollection. If you want to find all 5-star reviews across *all* landmarks, it would involve checking many separate `reviews` subcollections. With a collection group, you can perform a single query against the `reviews` collection group. + +### Examples + +**Standard Query** (Single Collection): +Find all 5-star reviews for a specific landmark. +```javascript +db.collection('landmarks/golden_gate_bridge/reviews').where('rating', '==', 5) +``` + +**Collection Group Query**: +Find all 5-star reviews across *all* landmarks. +```javascript +db.collectionGroup('reviews').where('rating', '==', 5) +``` \ No newline at end of file diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/indexes.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/indexes.md new file mode 100644 index 0000000..f1031bd --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/indexes.md @@ -0,0 +1,111 @@ +# Firestore Indexes Reference + +Indexes helps to improve query performance. Firestore Enterprise edition does not create any indexes by default. By default, Firestore Enterprise performs a full collection scan to find documents that match a query, which can be slow and expensive for large collections. To avoid this, you can create indexes to optimize your queries. + +## Index Structure + +An index consists of the following: + +* a collection ID. +* a list of fields in the given collection. +* an order, either ascending or descending, for each field. + +### Index Ordering + +The order and sort direction of each field uniquely defines the index. For example, the following indexes are two distinct indexes and not interchangeable: + +* Field name `name` (ascending) and `population` (descending) +* Field name `name` (descending) and `population` (ascending) + +### Index Density + +Dense indexes: By default, Firestore indexes store data from all documents in a collection. An index entry will be added for a document regardless of whether the document contains any of the fields specified in the index. Non-existent fields are treated as having a NULL value when generating index entries. + +Sparse indexes: To change this behavior, you can define the index as a sparse index. A sparse index indexes only the documents in the collection that contain a value (including null) for at least one of the indexed fields. A sparse index reduces storage costs and can improve performance. + +### Unique Indexes + +You can use unique index option to enforce unique values for the indexed fields. For indexes on multiple fields, each combination of values must be unique across the index. The database rejects any update and insert operations that attempt to create index entries with duplicate values. + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Single-Field Index on field `a` | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Single-Field Index on field `a` | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Single-Field Index on field `a` and `b` | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** on field `tags` and `active` | + +If no indexes is present, Firestore Enterprise will perform a full collection scan to find documents that match a query. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +Define a dense index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "DENSE", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a sparse-any index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a unique index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "unique": true, + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx firebase-tools@latest -y deploy --only firestore:indexes +``` \ No newline at end of file diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md new file mode 100644 index 0000000..02a97e3 --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md @@ -0,0 +1,101 @@ +# Provisioning Firestore Enterprise Native Mode + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create a Firestore Enterprise Database**: Create a Firestore Enterprise database using the Firebase CLI. +2. **Create `firebase.json`**: This file contains database configuration for the Firebase CLI. +3. **Create `firestore.rules`**: This file contains your security rules. +4. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create a Firestore Enterprise Database + +Use the following command to create a Firestore Enterprise database: + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" +``` + +This will create an enterprise database in `nam5` with native mode enabled. A database id is required to create an enterprise database and the database id must not be `(default)`. To enable realtime-updates feature, use `--realtime-updates` flag. + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" \ + --realtime-updates="ENABLED" +``` + +### 2. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "edition": "enterprise", + "database": "my-database-id", + "location": "nam5" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +firebase deploy --only firestore + +# To deploy just rules +firebase deploy --only firestore:rules + +# To deploy just indexes +firebase deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +firebase emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). \ No newline at end of file diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md new file mode 100644 index 0000000..8bd67a4 --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md @@ -0,0 +1,126 @@ +# Python SDK Usage + +The Python Server SDK is used for backend/server environments and utilizes Google Application Default Credentials in most Google Cloud environments. + +### Writing Data + +#### Set a Document +Creates a document if it does not exist or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```python +city_ref = db.collection("cities").document("LA") + +# Create/Overwrite +city_ref.set({ + "name": "Los Angeles", + "state": "CA", + "country": "USA" +}) + +# Merge +city_ref.set({"population": 3900000}, merge=True) +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```python +update_time, city_ref = db.collection("cities").add({ + "name": "Tokyo", + "country": "Japan" +}) +print("Document written with ID: ", city_ref.id) +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```python +city_ref = db.collection("cities").document("LA") +city_ref.update({ + "capital": True +}) +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```python +from google.cloud.firestore import Transaction + +transaction = db.transaction() +city_ref = db.collection("cities").document("SF") + +@firestore.transactional +def update_in_transaction(transaction, city_ref): + snapshot = city_ref.get(transaction=transaction) + if not snapshot.exists: + raise Exception("Document does not exist!") + + new_population = snapshot.get("population") + 1 + transaction.update(city_ref, {"population": new_population}) + +update_in_transaction(transaction, city_ref) +``` + +### Reading Data + +#### Get a Single Document + +```python +doc_ref = db.collection("cities").document("SF") +doc = doc_ref.get() + +if doc.exists: + print(f"Document data: {doc.to_dict()}") +else: + print("No such document!") +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```python +docs = db.collection("cities").stream() + +for doc in docs: + print(f"{doc.id} => {doc.to_dict()}") +``` + +### Queries + +#### Simple and Compound Queries +Use `.where()` to combine filters safely. Stack `.where()` calls for compound queries. + +```python +from google.cloud.firestore import FieldFilter + +cities_ref = db.collection("cities") + +# Simple equality +query_1 = cities_ref.where(filter=FieldFilter("state", "==", "CA")) + +# Compound (AND) +query_2 = cities_ref.where( + filter=FieldFilter("state", "==", "CA") +).where( + filter=FieldFilter("population", ">", 1000000) +) +``` + +#### Order and Limit +Sort and limit results cleanly. + +```python +query = cities_ref.order_by("name").limit(3) +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```python +pipeline = client.pipeline().collection("users") +for result in pipeline.execute(): + print(f"{result.id} => {result.data()}") +``` diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md b/.claude/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md new file mode 100644 index 0000000..1eee422 --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md @@ -0,0 +1,201 @@ +# Web SDK Usage + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +### Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'firebase apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); +``` + +### Writing Data + +#### Set a Document +Creates a document if it doesn't exist, or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +### Reading Data + +#### Get a Single Document + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + console.log(doc.id, " => ", doc.data()); +}); +``` + +### Realtime Updates + +#### Listen to a Document or Query + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// To stop listening: +// unsub(); +``` + +### Handle Changes + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +### Queries + +#### Simple and Compound Queries +Use `query()` and `where()` to combine filters safely. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires a composite index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +#### Order and Limit +Sort and limit results cleanly. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```javascript + +const readDataPipeline = db.pipeline() + .collection("users"); + +// Execute the pipeline and handle the result +try { + const querySnapshot = await execute(readDataPipeline); + querySnapshot.results.forEach((result) => { + console.log(`${result.id} => ${result.data()}`); + }); +} catch (error) { + console.error("Error getting documents: ", error); +} +``` diff --git a/.claude/skills/firebase-firestore-standard/SKILL.md b/.claude/skills/firebase-firestore-standard/SKILL.md new file mode 100644 index 0000000..0eb6c2e --- /dev/null +++ b/.claude/skills/firebase-firestore-standard/SKILL.md @@ -0,0 +1,27 @@ +--- +name: firebase-firestore-standard +description: Comprehensive guide for Firestore Standard Edition, including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Standard Edition + +This skill provides a complete guide for getting started with Cloud Firestore Standard Edition, including provisioning, securing, and integrating it into your application. + +## Provisioning + +To set up Cloud Firestore in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Cloud Firestore in your application code, choose your platform: + +* **Web (Modular SDK)**: [web_sdk_usage.md](references/web_sdk_usage.md) + +## Indexes + +For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.claude/skills/firebase-firestore-standard/references/indexes.md b/.claude/skills/firebase-firestore-standard/references/indexes.md new file mode 100644 index 0000000..7623eb8 --- /dev/null +++ b/.claude/skills/firebase-firestore-standard/references/indexes.md @@ -0,0 +1,82 @@ +# Firestore Indexes Reference + +Indexes allow Firestore to ensure that query performance depends on the size of the result set, not the size of the database. + +## Index Types + +### Single-Field Indexes +In Standard Edition, Firestore **automatically creates** a single-field index for every field in a document (and subfields in maps). +* **Support**: Simple equality queries (`==`) and single-field range/sort queries (`<`, `<=`, `orderBy`). +* **Behavior**: You generally don't need to manage these unless you want to *exempt* a field. + +### Composite Indexes +A composite index stores a sorted mapping of all documents based on an ordered list of fields. +* **Support**: Complex queries that filter or sort by **multiple fields**. +* **Creation**: These are **NOT** automatically created. You must define them manually or via the console/CLI. + +## Automatic vs. Manual Management + +### What is Automatic? +* Indexes for simple queries. +* Merging of single-field indexes for multiple equality filters (e.g., `where("state", "==", "CA").where("country", "==", "USA")`). + +### When Do I Need to Act? +If you attempt a query that requires a composite index, the SDK will throw an error containing a **direct link** to the Firebase Console to create that specific index. + +**Example Error:** +> "The query requires an index. You can create it here: https://console.firebase.google.com/project/..." + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Automatic (Single-Field) | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Automatic (Single-Field) | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Automatic (Merged Single-Field) | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** (and technically limited query support) | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** | + +## Best Practices & Exemptions + +You can **exempt** fields from automatic indexing to save storage or strictly enforce write limits. + +### 1. High Write Rates (Sequential Values) +* **Problem**: Indexing fields that increase sequentially (like `timestamp`) limits the write rate to ~500 writes/second per collection. +* **Solution**: If you don't query on this field, **exempt** it from simple indexing. + +### 2. Large String/Map/Array Fields +* **Problem**: Indexing limits (40k entries per doc). Indexing large blobs wastes storage. +* **Solution**: Exempt large text blobs or huge arrays if they aren't used for filtering. + +### 3. TTL Fields +* **Problem**: TTL (Time-To-Live) deletion can cause index churn. +* **Solution**: Exempt the TTL timestamp field from indexing if you don't query it. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx -y firebase-tools@latest deploy --only firestore:indexes +``` diff --git a/.claude/skills/firebase-firestore-standard/references/provisioning.md b/.claude/skills/firebase-firestore-standard/references/provisioning.md new file mode 100644 index 0000000..5278801 --- /dev/null +++ b/.claude/skills/firebase-firestore-standard/references/provisioning.md @@ -0,0 +1,87 @@ +# Provisioning Cloud Firestore + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create `firebase.json`**: This file configures the Firebase CLI. +2. **Create `firestore.rules`**: This file contains your security rules. +3. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json" + } +} +``` + +This will use the default database with the Standard edition. To use a different database, specify the database ID and location. You can check the list of available databases using `npx -y firebase-tools@latest firestore:databases:list`. If the database does not exist, it will be created when you deploy: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "database": "my-database-id", + "location": "us-central1" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +npx -y firebase-tools@latest deploy --only firestore + +# To deploy just rules +npx -y firebase-tools@latest deploy --only firestore:rules + +# To deploy just indexes +npx -y firebase-tools@latest deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +npx -y firebase-tools@latest emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). diff --git a/.claude/skills/firebase-firestore-standard/references/security_rules.md b/.claude/skills/firebase-firestore-standard/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.claude/skills/firebase-firestore-standard/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.claude/skills/firebase-firestore-standard/references/web_sdk_usage.md b/.claude/skills/firebase-firestore-standard/references/web_sdk_usage.md new file mode 100644 index 0000000..3d85134 --- /dev/null +++ b/.claude/skills/firebase-firestore-standard/references/web_sdk_usage.md @@ -0,0 +1,183 @@ +# Firestore Web SDK Usage Guide + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +## Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'npx -y firebase-tools@latest apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); + +``` + +## Writing Data + +### Set a Document (`setDoc`) +Creates a document if it doesn't exist, or overwrites it if it does. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +### Add a Document with Auto-ID (`addDoc`) +Use when you don't care about the document ID. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +### Update a Document (`updateDoc`) +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +## Reading Data + +### Get a Single Document (`getDoc`) + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +### Get Multiple Documents (`getDocs`) +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + // doc.data() is never undefined for query doc snapshots + console.log(doc.id, " => ", doc.data()); +}); +``` + +## Realtime Updates + +### Listen to a Document/Query (`onSnapshot`) + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// Stop listening +// unsub(); +``` + +### Handle Changes (Added/Modified/Removed) + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +## Queries + +### Simple and Compound Queries +Use `query()` to combine filters. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires an index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +### Order and Limit +Sort and limit results. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` diff --git a/.claude/skills/firebase-hosting-basics/SKILL.md b/.claude/skills/firebase-hosting-basics/SKILL.md new file mode 100644 index 0000000..a83ac28 --- /dev/null +++ b/.claude/skills/firebase-hosting-basics/SKILL.md @@ -0,0 +1,46 @@ +--- +name: firebase-hosting-basics +description: Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting. +--- + +# hosting-basics + +This skill provides instructions and references for working with Firebase Hosting, a fast and secure hosting service for your web app, static and dynamic content, and microservices. + +## Overview + +Firebase Hosting provides production-grade web content hosting for developers. With a single command, you can deploy web apps and serve both static and dynamic content to a global CDN (content delivery network). + +**Key Features:** +- **Fast Content Delivery:** Files are cached on SSDs at CDN edges around the world. +- **Secure by Default:** Zero-configuration SSL is built-in. +- **Preview Channels:** View and test changes on temporary preview URLs before deploying live. +- **GitHub Integration:** Automate previews and deploys with GitHub Actions. +- **Dynamic Content:** Serve dynamic content and microservices using Cloud Functions or Cloud Run. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Instructions + +### 1. Configuration (`firebase.json`) +For details on configuring Hosting behavior, including public directories, redirects, rewrites, and headers, see [configuration.md](references/configuration.md). + +### 2. Deploying +For instructions on deploying your site, using preview channels, and managing releases, see [deploying.md](references/deploying.md). + +### 3. Emulation +To test your app locally: +```bash +npx -y firebase-tools@latest emulators:start --only hosting +``` +This serves your app at `http://localhost:5000` by default. diff --git a/.claude/skills/firebase-hosting-basics/references/configuration.md b/.claude/skills/firebase-hosting-basics/references/configuration.md new file mode 100644 index 0000000..adb9050 --- /dev/null +++ b/.claude/skills/firebase-hosting-basics/references/configuration.md @@ -0,0 +1,101 @@ +# Hosting Configuration (`firebase.json`) + +The `hosting` section of `firebase.json` configures how your site is deployed and served. + +## Key Attributes + +### `public` (Required) +Specifies the directory to deploy to Firebase Hosting. +```json +"hosting": { + "public": "public" +} +``` + +### `ignore` (Optional) +Files to ignore on deploy. Uses glob patterns (like `.gitignore`). +**Default ignores:** `firebase.json`, `**/.*`, `**/node_modules/**` + +### `redirects` (Optional) +URL redirects to prevent broken links or shorten URLs. +```json +"redirects": [ + { + "source": "/foo", + "destination": "/bar", + "type": 301 + } +] +``` + +### `rewrites` (Optional) +Serve the same content for multiple URLs, useful for SPAs or Dynamic Content. +```json +"rewrites": [ + { + "source": "**", + "destination": "/index.html" + }, + { + "source": "/api/**", + "function": "apiFunction" + }, + { + "source": "/container/**", + "run": { + "serviceId": "helloworld", + "region": "us-central1" + } + } +] +``` + +### `headers` (Optional) +Custom response headers. +```json +"headers": [ + { + "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)", + "headers": [ + { + "key": "Access-Control-Allow-Origin", + "value": "*" + } + ] + } +] +``` + +### `cleanUrls` (Optional) +If `true`, drops `.html` extension from URLs. +```json +"cleanUrls": true +``` + +### `trailingSlash` (Optional) +Controls trailing slashes in static content URLs. +- `true`: Adds trailing slash. +- `false`: Removes trailing slash. + +## Full Example + +```json +{ + "hosting": { + "public": "dist", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ], + "cleanUrls": true, + "trailingSlash": false + } +} +``` diff --git a/.claude/skills/firebase-hosting-basics/references/deploying.md b/.claude/skills/firebase-hosting-basics/references/deploying.md new file mode 100644 index 0000000..df26c5e --- /dev/null +++ b/.claude/skills/firebase-hosting-basics/references/deploying.md @@ -0,0 +1,39 @@ +# Deploying to Firebase Hosting + +## Standard Deployment +To deploy your Hosting content and configuration to your live site: + +```bash +npx -y firebase-tools@latest deploy --only hosting +``` + +This deploys to your default sites (`PROJECT_ID.web.app` and `PROJECT_ID.firebaseapp.com`). + +## Preview Channels +Preview channels allow you to test changes on a temporary URL before going live. + +### Deploy to a Preview Channel +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID +``` +Replace `CHANNEL_ID` with a name (e.g., `feature-beta`). +This returns a preview URL like `PROJECT_ID--CHANNEL_ID-RANDOM_HASH.web.app`. + +### Expiration +Channels expire after 7 days by default. To set a different expiration: +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID --expires 1d +``` + +## Cloning to Live +You can promote a version from a preview channel to your live channel without rebuilding. + +```bash +npx -y firebase-tools@latest hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL_ID TARGET_SITE_ID:live +``` + +**Example:** +Clone the `feature-beta` channel on your default site to live: +```bash +npx -y firebase-tools@latest hosting:clone my-project:feature-beta my-project:live +``` diff --git a/.claude/skills/firestore-security-rules-auditor/SKILL.md b/.claude/skills/firestore-security-rules-auditor/SKILL.md new file mode 100644 index 0000000..dbc60af --- /dev/null +++ b/.claude/skills/firestore-security-rules-auditor/SKILL.md @@ -0,0 +1,45 @@ +--- +name: firestore-security-rules-auditor +description: A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust. +--- + +# Overview +This skill acts as an auditor for Firebase Security Rules, evaluating them against a rigorous set of criteria to ensure they are secure, robust, and correctly implemented. + +# Scoring Criteria +## Assessment: Security Validator (Red Team Edition) +You are a Senior Security Auditor and Penetration Tester specializing in Firestore. Your goal is to find "the hole in the wall." Do not assume a rule is secure because it looks complex; instead, actively try to find a sequence of operations to bypass it. + +### Mandatory Audit Checklist: +1. **The Update Bypass:** Compare 'create' and 'update' rules. Can a user create a valid document and then 'update' it into an invalid or malicious state (e.g., changing their role, bypassing size limits, or corrupting data types)? +2. **Authority Source:** Does the security rely on user-provided data (request.resource.data) for sensitive fields like 'role', 'isAdmin', or 'ownerId'? Carefully consider the source for that authority. +3. **Business Logic vs. Rules:** Does the rule set actually support the app's purpose? (e.g., In a collaboration app, can collaborators actually read the data? If not, the rules are "broken" or will force insecure workarounds). +4. **Storage Abuse:** Are there string length or array size limits? If not, label it as a "Resource Exhaustion/DoS" risk. +5. **Type Safety:** Are fields checked with 'is string', 'is int', or 'is timestamp'? +6. **Field-Level vs. Identity-Level Security:** Be careful with rules that use \`hasOnly()\` or \`diff()\`. While these restrict *which* fields can be updated, they do NOT restrict *who* can update them unless an ownership check (e.g., \`resource.data.uid == request.auth.uid\`) is also present. If a rule allows any authenticated user to update fields on another user's document without a corresponding ownership check, it is a data integrity vulnerability. + +### Admin Bootstrapping & Privileges: +The admin bootstrapping process is limited in this app. If the rules use a single hardcoded admin email (e.g., checking request.auth.token.email == 'admin@example.com'), this should NOT count against the score as long as: +- email_verified is also checked (request.auth.token.email_verified == true). +- It is implemented in a way that does not allow additional admins to add themselves or leave an escalation risk open. + +### Scoring Criteria (1-5): +- **1 (Critical):** Unauthorized data access (leaks), privilege escalation, or total validation bypass. +- **2 (Major):** Broken business logic, self-assigned roles, bypass of controls. +- **3 (Moderate):** PII exposure (e.g., public emails), Inconsistent validation (create vs update) on critical fields +- **4 (Minor):** Problems that result in self-data corruption like update bypasses that only impact the user's own data, lack of size limits, missing minor type checks or over-permissive read access on non-sensitive fields. +- **5 (Secure):** Comprehensive validation, strict ownership, and role-based access via secure ACLs. + +Return your assessment in JSON format using the following structure: +{ + "score": 1-5, + "summary": "overall assessment", + "findings": [ + { + "check": "checklist item", + "severity": "critical|major|moderate|minor", + "issue": "description", + "recommendation": "fix" + } + ] +} \ No newline at end of file diff --git a/database-debug.log b/database-debug.log new file mode 100644 index 0000000..e69de29 diff --git a/firebase-debug.log b/firebase-debug.log new file mode 100644 index 0000000..03cf687 --- /dev/null +++ b/firebase-debug.log @@ -0,0 +1,1571 @@ +[debug] [2026-04-12T23:59:29.449Z] ---------------------------------------------------------------------- +[debug] [2026-04-12T23:59:29.451Z] Command: C:\Program Files\nodejs\node.exe C:\Users\윤정민\AppData\Roaming\npm\node_modules\firebase-tools\lib\bin\firebase.js emulators:start --only auth,database,firestore,functions +[debug] [2026-04-12T23:59:29.451Z] CLI Version: 15.14.0 +[debug] [2026-04-12T23:59:29.451Z] Platform: win32 +[debug] [2026-04-12T23:59:29.451Z] Node Version: v24.14.1 +[debug] [2026-04-12T23:59:29.451Z] Time: Mon Apr 13 2026 08:59:29 GMT+0900 (한국 표준시) +[debug] [2026-04-12T23:59:29.451Z] ---------------------------------------------------------------------- +[debug] +[debug] [2026-04-12T23:59:30.094Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"] +[debug] [2026-04-12T23:59:30.094Z] > authorizing via signed-in user (graywolf147@gmail.com) +[debug] [2026-04-12T23:59:30.189Z] java version "26" 2026-03-17 + +[debug] [2026-04-12T23:59:30.189Z] Java(TM) SE Runtime Environment (build 26+35-2893) +Java HotSpot(TM) 64-Bit Server VM (build 26+35-2893, mixed mode, sharing) + +[debug] [2026-04-12T23:59:30.196Z] Parsed Java major version: 26 +[info] i emulators: Starting emulators: auth, functions, firestore, database {"metadata":{"emulator":{"name":"hub"},"message":"Starting emulators: auth, functions, firestore, database"}} +[debug] [2026-04-12T23:59:30.202Z] [logging] Logging Emulator only supports listening on one address (127.0.0.1). Not listening on ::1 +[debug] [2026-04-12T23:59:30.202Z] assigned listening specs for emulators {"user":{"ui":[{"address":"0.0.0.0","family":"IPv4","port":4000}],"auth":[{"address":"0.0.0.0","family":"IPv4","port":9099}],"firestore":[{"address":"0.0.0.0","family":"IPv4","port":8080}],"firestore.websocket":[{"address":"0.0.0.0","family":"IPv4","port":9150}],"database":[{"address":"0.0.0.0","family":"IPv4","port":9000}],"hub":[{"address":"127.0.0.1","family":"IPv4","port":4400},{"address":"::1","family":"IPv6","port":4400}],"logging":[{"address":"127.0.0.1","family":"IPv4","port":4500}]},"metadata":{"message":"assigned listening specs for emulators"}} +[debug] [2026-04-12T23:59:30.205Z] Write emulator hub locator at C:\Users\윤정민\AppData\Local\Temp\hub-mmday-panit.json +[debug] [2026-04-12T23:59:30.210Z] [eventarc] Eventarc Emulator only supports listening on one address (127.0.0.1). Not listening on ::1 +[debug] [2026-04-12T23:59:30.210Z] [tasks] Cloud Tasks Emulator only supports listening on one address (127.0.0.1). Not listening on ::1 +[debug] [2026-04-12T23:59:30.210Z] late-assigned ports for functions and eventarc emulators {"user":{"ui":[{"address":"0.0.0.0","family":"IPv4","port":4000}],"auth":[{"address":"0.0.0.0","family":"IPv4","port":9099}],"firestore":[{"address":"0.0.0.0","family":"IPv4","port":8080}],"firestore.websocket":[{"address":"0.0.0.0","family":"IPv4","port":9150}],"database":[{"address":"0.0.0.0","family":"IPv4","port":9000}],"hub":[{"address":"127.0.0.1","family":"IPv4","port":4400},{"address":"::1","family":"IPv6","port":4400}],"logging":[{"address":"127.0.0.1","family":"IPv4","port":4500}],"functions":[{"address":"0.0.0.0","family":"IPv4","port":5001}],"eventarc":[{"address":"127.0.0.1","family":"IPv4","port":9299}],"tasks":[{"address":"127.0.0.1","family":"IPv4","port":9499}]},"metadata":{"message":"late-assigned ports for functions and eventarc emulators"}} +[warn] ! functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: apphosting, hosting, pubsub, storage, dataconnect {"metadata":{"emulator":{"name":"functions"},"message":"The following emulators are not running, calls to these services from the Functions emulator will affect production: \u001b[1mapphosting, hosting, pubsub, storage, dataconnect\u001b[22m"}} +[debug] [2026-04-12T23:59:30.220Z] defaultcredentials: writing to file C:\Users\윤정민\AppData\Roaming\firebase\graywolf147_gmail_com_application_default_credentials.json +[debug] [2026-04-12T23:59:30.221Z] Setting GAC to C:\Users\윤정민\AppData\Roaming\firebase\graywolf147_gmail_com_application_default_credentials.json {"metadata":{"emulator":{"name":"functions"},"message":"Setting GAC to C:\\Users\\윤정민\\AppData\\Roaming\\firebase\\graywolf147_gmail_com_application_default_credentials.json"}} +[debug] [2026-04-12T23:59:30.221Z] Checked if tokens are valid: true, expires at: 1776041278436 +[debug] [2026-04-12T23:59:30.221Z] Checked if tokens are valid: true, expires at: 1776041278436 +[debug] [2026-04-12T23:59:30.222Z] >>> [apiv2][query] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit/adminSdkConfig [none] +[debug] [2026-04-12T23:59:30.958Z] <<< [apiv2][status] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit/adminSdkConfig 200 +[debug] [2026-04-12T23:59:30.959Z] <<< [apiv2][body] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit/adminSdkConfig {"projectId":"mmday-panit","databaseURL":"https://mmday-panit-default-rtdb.asia-southeast1.firebasedatabase.app","storageBucket":"mmday-panit.firebasestorage.app"} +[debug] [2026-04-12T23:59:30.967Z] Ignoring unsupported arg: auto_download {"metadata":{"emulator":{"name":"firestore"},"message":"Ignoring unsupported arg: auto_download"}} +[debug] [2026-04-12T23:59:30.967Z] Ignoring unsupported arg: single_project_mode_error {"metadata":{"emulator":{"name":"firestore"},"message":"Ignoring unsupported arg: single_project_mode_error"}} +[debug] [2026-04-12T23:59:30.967Z] Starting Firestore Emulator with command {"binary":"java","args":["-Dgoogle.cloud_firestore.debug_log_level=FINE","-Duser.language=en","-jar","C:\\Users\\윤정민\\.cache\\firebase\\emulators\\cloud-firestore-emulator-v1.20.4.jar","--host","0.0.0.0","--port",8080,"--websocket_port",9150,"--database-edition","standard","--project_id","mmday-panit","--rules","D:\\Projects\\WebstormProjects\\mmday-firebase\\firestore.rules","--single_project_mode",true,"--functions_emulator","127.0.0.1:5001"],"optionalArgs":["port","webchannel_port","host","rules","websocket_port","database-edition","functions_emulator","seed_from_export","project_id","single_project_mode"],"joinArgs":false,"shell":false,"port":8080} {"metadata":{"emulator":{"name":"firestore"},"message":"Starting Firestore Emulator with command {\"binary\":\"java\",\"args\":[\"-Dgoogle.cloud_firestore.debug_log_level=FINE\",\"-Duser.language=en\",\"-jar\",\"C:\\\\Users\\\\윤정민\\\\.cache\\\\firebase\\\\emulators\\\\cloud-firestore-emulator-v1.20.4.jar\",\"--host\",\"0.0.0.0\",\"--port\",8080,\"--websocket_port\",9150,\"--database-edition\",\"standard\",\"--project_id\",\"mmday-panit\",\"--rules\",\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\firestore.rules\",\"--single_project_mode\",true,\"--functions_emulator\",\"127.0.0.1:5001\"],\"optionalArgs\":[\"port\",\"webchannel_port\",\"host\",\"rules\",\"websocket_port\",\"database-edition\",\"functions_emulator\",\"seed_from_export\",\"project_id\",\"single_project_mode\"],\"joinArgs\":false,\"shell\":false,\"port\":8080}"}} +[info] i firestore: Firestore Emulator logging to firestore-debug.log {"metadata":{"emulator":{"name":"firestore"},"message":"Firestore Emulator logging to \u001b[1mfirestore-debug.log\u001b[22m"}} +[info] + firestore: Firestore Emulator was started in standard edition. {"metadata":{"emulator":{"name":"firestore"},"message":"Firestore Emulator was started in standard edition."}} +[info] + firestore: Firestore Emulator UI websocket is running on 9150. {"metadata":{"emulator":{"name":"firestore"},"message":"Firestore Emulator UI websocket is running on 9150."}} +[debug] [2026-04-12T23:59:32.021Z] Checked if tokens are valid: true, expires at: 1776041278436 +[debug] [2026-04-12T23:59:32.021Z] Checked if tokens are valid: true, expires at: 1776041278436 +[debug] [2026-04-12T23:59:32.021Z] >>> [apiv2][query] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit [none] +[debug] [2026-04-12T23:59:32.361Z] <<< [apiv2][status] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit 200 +[debug] [2026-04-12T23:59:32.361Z] <<< [apiv2][body] GET https://firebase.googleapis.com/v1beta1/projects/mmday-panit {"projectId":"mmday-panit","projectNumber":"650638194863","displayName":"mmday-panit","name":"projects/mmday-panit","resources":{"hostingSite":"mmday-panit","realtimeDatabaseInstance":"mmday-panit-default-rtdb"},"state":"ACTIVE","etag":"1_b78f2391-577f-4d81-b273-047d44119194"} +[debug] [2026-04-12T23:59:32.361Z] database rules config: [{"instance":"mmday-panit-default-rtdb","rules":"D:\\Projects\\WebstormProjects\\mmday-firebase\\database.rules.json"}] +[debug] [2026-04-12T23:59:32.362Z] Ignoring unsupported arg: projectId {"metadata":{"emulator":{"name":"database"},"message":"Ignoring unsupported arg: projectId"}} +[debug] [2026-04-12T23:59:32.362Z] Ignoring unsupported arg: auto_download {"metadata":{"emulator":{"name":"database"},"message":"Ignoring unsupported arg: auto_download"}} +[debug] [2026-04-12T23:59:32.362Z] Ignoring unsupported arg: rules {"metadata":{"emulator":{"name":"database"},"message":"Ignoring unsupported arg: rules"}} +[debug] [2026-04-12T23:59:32.363Z] Starting Database Emulator with command {"binary":"java","args":["-Duser.language=en","-jar","C:\\Users\\윤정민\\.cache\\firebase\\emulators\\firebase-database-emulator-v4.11.2.jar","--host","0.0.0.0","--port",9000,"--single_project_mode","Warning","--functions_emulator_host","127.0.0.1","--functions_emulator_port",5001],"optionalArgs":["port","host","functions_emulator_port","functions_emulator_host","single_project_mode"],"joinArgs":false,"shell":false,"port":9000} {"metadata":{"emulator":{"name":"database"},"message":"Starting Database Emulator with command {\"binary\":\"java\",\"args\":[\"-Duser.language=en\",\"-jar\",\"C:\\\\Users\\\\윤정민\\\\.cache\\\\firebase\\\\emulators\\\\firebase-database-emulator-v4.11.2.jar\",\"--host\",\"0.0.0.0\",\"--port\",9000,\"--single_project_mode\",\"Warning\",\"--functions_emulator_host\",\"127.0.0.1\",\"--functions_emulator_port\",5001],\"optionalArgs\":[\"port\",\"host\",\"functions_emulator_port\",\"functions_emulator_host\",\"single_project_mode\"],\"joinArgs\":false,\"shell\":false,\"port\":9000}"}} +[info] i database: Database Emulator logging to database-debug.log {"metadata":{"emulator":{"name":"database"},"message":"Database Emulator logging to \u001b[1mdatabase-debug.log\u001b[22m"}} +[debug] [2026-04-12T23:59:36.767Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:36.767Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:36.767Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:36.767Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:36.769Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:36.769Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:36.769Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:36.769Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:36.769Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:36.770Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[info] i functions: Watching "D:\Projects\WebstormProjects\mmday-firebase" for Cloud Functions... {"metadata":{"emulator":{"name":"functions"},"message":"Watching \"D:\\Projects\\WebstormProjects\\mmday-firebase\" for Cloud Functions..."}} +[debug] [2026-04-12T23:59:36.775Z] Validating nodejs source +[warn] ! functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions@latest in your functions directory. +[debug] [2026-04-12T23:59:37.265Z] > [functions] package.json contents: { + "name": "functions", + "scripts": { + "lint": "eslint --ext .js,.ts .", + "build": "tsc", + "build:watch": "tsc --watch", + "serve": "npm run build && firebase emulators:start --only auth,functions,firestore,database,storage", + "shell": "npm run build && firebase functions:shell", + "start": "npm run shell", + "deploy": "firebase deploy --only functions", + "logs": "firebase functions:log", + "test": "firebase emulators:exec --only firestore,database,auth \"vitest run\"", + "test:watch": "vitest" + }, + "engines": { + "node": "24" + }, + "main": "lib/index.js", + "dependencies": { + "firebase-admin": "^13.6.0", + "firebase-functions": "^7.0.0" + }, + "devDependencies": { + "@typescript-eslint/eslint-plugin": "^5.12.0", + "@typescript-eslint/parser": "^5.12.0", + "eslint": "^8.9.0", + "eslint-config-google": "^0.14.0", + "eslint-plugin-import": "^2.25.4", + "firebase-functions-test": "^3.4.1", + "typescript": "^5.7.3", + "vitest": "^4.1.4" + }, + "private": true +} +[debug] [2026-04-12T23:59:37.265Z] Building nodejs source +[debug] [2026-04-12T23:59:37.265Z] Failed to find version of module node: reached end of search path D:\Projects\WebstormProjects\mmday-firebase\node_modules +[warn] ! functions: Your requested "node" version "22" doesn't match your global version "24". Using node@24 from host. +[debug] [2026-04-12T23:59:37.268Z] Could not find functions.yaml. Must use http discovery +[debug] [2026-04-12T23:59:37.273Z] Found firebase-functions binary at 'D:\Projects\WebstormProjects\mmday-firebase\node_modules\.bin\firebase-functions' +[info] Serving at port 8226 + +[debug] [2026-04-12T23:59:37.612Z] Got response from /__/functions.yaml {"endpoints":{"kbo":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"httpsTrigger":{},"entryPoint":"kbo"},"auth":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"httpsTrigger":{},"entryPoint":"auth"},"prediction":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"httpsTrigger":{},"entryPoint":"prediction"},"stats":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"httpsTrigger":{},"entryPoint":"stats"},"admin":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"httpsTrigger":{},"entryPoint":"admin"},"kboDailyRefresh":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"scheduleTrigger":{"schedule":"0 2 * * *","retryConfig":{},"timeZone":"Asia/Seoul"},"entryPoint":"kboDailyRefresh"},"dailyArchive":{"availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":10,"ingressSettings":null,"concurrency":null,"serviceAccountEmail":null,"vpc":null,"platform":"gcfv2","region":["asia-northeast3"],"labels":{},"scheduleTrigger":{"schedule":"0 2 * * *","retryConfig":{},"timeZone":"Asia/Seoul"},"entryPoint":"dailyArchive"}},"specVersion":"v1alpha1","requiredAPIs":[{"api":"cloudscheduler.googleapis.com","reason":"Needed for scheduled functions."}],"extensions":{}} +[debug] [2026-04-12T23:59:39.059Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:39.059Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:39.059Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:39.059Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:39.059Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:39.082Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:39.082Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:39.082Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:39.082Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:39.082Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:40.664Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:40.664Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:40.664Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:40.664Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:40.664Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:40.675Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:40.675Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:40.675Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:40.675Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:40.675Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[info] + functions: Loaded functions definitions from source: kbo, auth, prediction, stats, admin, kboDailyRefresh, dailyArchive. {"metadata":{"emulator":{"name":"functions"},"message":"Loaded functions definitions from source: kbo, auth, prediction, stats, admin, kboDailyRefresh, dailyArchive."}} +[info] + functions[asia-northeast3-kbo]: http function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/kbo). {"metadata":{"emulator":{"name":"functions"},"message":"\u001b[1mhttp\u001b[22m function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/kbo)."}} +[info] + functions[asia-northeast3-auth]: http function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/auth). {"metadata":{"emulator":{"name":"functions"},"message":"\u001b[1mhttp\u001b[22m function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/auth)."}} +[info] + functions[asia-northeast3-prediction]: http function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/prediction). {"metadata":{"emulator":{"name":"functions"},"message":"\u001b[1mhttp\u001b[22m function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/prediction)."}} +[info] + functions[asia-northeast3-stats]: http function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/stats). {"metadata":{"emulator":{"name":"functions"},"message":"\u001b[1mhttp\u001b[22m function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/stats)."}} +[info] + functions[asia-northeast3-admin]: http function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/admin). {"metadata":{"emulator":{"name":"functions"},"message":"\u001b[1mhttp\u001b[22m function initialized (http://127.0.0.1:5001/mmday-panit/asia-northeast3/admin)."}} +[info] i functions[asia-northeast3-kboDailyRefresh]: function ignored because the pubsub emulator does not exist or is not running. {"metadata":{"emulator":{"name":"functions"},"message":"function ignored because the pubsub emulator does not exist or is not running."}} +[info] i functions[asia-northeast3-dailyArchive]: function ignored because the pubsub emulator does not exist or is not running. {"metadata":{"emulator":{"name":"functions"},"message":"function ignored because the pubsub emulator does not exist or is not running."}} +[debug] [2026-04-12T23:59:41.642Z] >>> [apiv2][query] PUT http://127.0.0.1:9000/.settings/rules.json ns=mmday-panit-default-rtdb +[debug] [2026-04-12T23:59:41.642Z] >>> [apiv2][body] PUT http://127.0.0.1:9000/.settings/rules.json "{\n \"rules\": {\n \"votes\": {\n \"$gameId\": {\n \".read\": \"auth != null\",\n \"counts\": {\n \".read\": true\n },\n \".write\": false\n }\n },\n \"userVotes\": {\n \"$uid\": {\n \".read\": \"auth != null && auth.uid == $uid\",\n \".write\": false\n }\n },\n \"cache\": {\n \".read\": false,\n \".write\": false\n }\n }\n}\n" +[debug] [2026-04-12T23:59:41.886Z] <<< [apiv2][status] PUT http://127.0.0.1:9000/.settings/rules.json 200 +[debug] [2026-04-12T23:59:41.886Z] <<< [apiv2][body] PUT http://127.0.0.1:9000/.settings/rules.json {"status":"ok"} +[debug] [2026-04-12T23:59:41.888Z] Could not find VSCode notification endpoint: FetchError: request to http://localhost:40001/vscode/notify failed, reason: . If you are not running the Firebase Data Connect VSCode extension, this is expected and not an issue. +[info] +┌─────────────────────────────────────────────────────────────┐ +│ ✔ All emulators ready! It is now safe to connect your app. │ +│ i View Emulator UI at http://127.0.0.1:4000/ │ +└─────────────────────────────────────────────────────────────┘ + +┌────────────────┬──────────────┬─────────────────────────────────┐ +│ Emulator │ Host:Port │ View in Emulator UI │ +├────────────────┼──────────────┼─────────────────────────────────┤ +│ Authentication │ 0.0.0.0:9099 │ http://127.0.0.1:4000/auth │ +├────────────────┼──────────────┼─────────────────────────────────┤ +│ Functions │ 0.0.0.0:5001 │ http://127.0.0.1:4000/functions │ +├────────────────┼──────────────┼─────────────────────────────────┤ +│ Firestore │ 0.0.0.0:8080 │ http://127.0.0.1:4000/firestore │ +├────────────────┼──────────────┼─────────────────────────────────┤ +│ Database │ 0.0.0.0:9000 │ http://127.0.0.1:4000/database │ +└────────────────┴──────────────┴─────────────────────────────────┘ + Emulator Hub host: 127.0.0.1 port: 4400 + Other reserved ports: 4500, 9150 + +Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files. + +[debug] [2026-04-12T23:59:43.010Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:43.010Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:43.011Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:43.010Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:43.011Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-12T23:59:43.011Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:43.011Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-12T23:59:43.018Z] [worker-pool] addWorker(asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] addWorker(asia-northeast3-stats)"}} +[debug] [2026-04-12T23:59:43.019Z] [worker-pool] Adding worker with key asia-northeast3-stats, total=1 {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] Adding worker with key asia-northeast3-stats, total=1"}} +[debug] [2026-04-12T23:59:43.028Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:43.028Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:43.010Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:43.028Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:43.010Z","/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:43.028Z"],"workRunningCount":2} +[debug] [2026-04-12T23:59:43.028Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-12T23:59:43.029Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:43.029Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-12T23:59:43.031Z] [worker-pool] addWorker(asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] addWorker(asia-northeast3-kbo)"}} +[debug] [2026-04-12T23:59:43.031Z] [worker-pool] Adding worker with key asia-northeast3-kbo, total=1 {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] Adding worker with key asia-northeast3-kbo, total=1"}} +[debug] [2026-04-12T23:59:43.549Z] [runtime-status] [751372] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.550Z] [runtime-status] [748032] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.550Z] [runtime-status] [751372] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.550Z] [runtime-status] [751372] Outgoing network have been stubbed. [{"name":"http","status":"mocked"},{"name":"http","status":"mocked"},{"name":"https","status":"mocked"},{"name":"https","status":"mocked"},{"name":"net","status":"mocked"}] {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Outgoing network have been stubbed. [{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"net\",\"status\":\"mocked\"}]"}} +[debug] [2026-04-12T23:59:43.550Z] [runtime-status] [748032] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.550Z] [runtime-status] [748032] Outgoing network have been stubbed. [{"name":"http","status":"mocked"},{"name":"http","status":"mocked"},{"name":"https","status":"mocked"},{"name":"https","status":"mocked"},{"name":"net","status":"mocked"}] {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Outgoing network have been stubbed. [{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"net\",\"status\":\"mocked\"}]"}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [751372] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [751372] Detected firebase-functions v7+, skipping legacy stubs. {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Detected firebase-functions v7+, skipping legacy stubs."}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [748032] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [748032] Detected firebase-functions v7+, skipping legacy stubs. {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Detected firebase-functions v7+, skipping legacy stubs."}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [751372] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.551Z] [runtime-status] [748032] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.580Z] [runtime-status] [751372] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.580Z] [runtime-status] [748032] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:43.705Z] [runtime-status] [751372] firebase-admin has been stubbed. {"adminResolution":{"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"}} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] firebase-admin has been stubbed. {\"adminResolution\":{\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}}"}} +[debug] [2026-04-12T23:59:43.706Z] [runtime-status] [748032] firebase-admin has been stubbed. {"adminResolution":{"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"}} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] firebase-admin has been stubbed. {\"adminResolution\":{\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}}"}} +[debug] [2026-04-12T23:59:43.722Z] [runtime-status] [751372] Functions runtime initialized. {"cwd":"D:\\Projects\\WebstormProjects\\mmday-firebase","node_version":"24.14.1"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Functions runtime initialized. {\"cwd\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\",\"node_version\":\"24.14.1\"}"}} +[debug] [2026-04-12T23:59:43.722Z] [runtime-status] [751372] Listening to port: \\?\pipe\fire_emu_819f8b585d1de522 {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[runtime-status] [751372] Listening to port: \\\\?\\pipe\\fire_emu_819f8b585d1de522"}} +[debug] [2026-04-12T23:59:43.723Z] [runtime-status] [748032] Functions runtime initialized. {"cwd":"D:\\Projects\\WebstormProjects\\mmday-firebase","node_version":"24.14.1"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Functions runtime initialized. {\"cwd\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\",\"node_version\":\"24.14.1\"}"}} +[debug] [2026-04-12T23:59:43.723Z] [runtime-status] [748032] Listening to port: \\?\pipe\fire_emu_30f3d2eb1c09b165 {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[runtime-status] [748032] Listening to port: \\\\?\\pipe\\fire_emu_30f3d2eb1c09b165"}} +[debug] [2026-04-12T23:59:43.782Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-12T23:59:43.782Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-12T23:59:43.783Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-12T23:59:43.787Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 4.6158ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 4.6158ms"}} +[debug] [2026-04-12T23:59:43.788Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-12T23:59:43.788Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:43.788Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:43.788Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-12T23:59:43.028Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:43.791Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-12T23:59:43.791Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-12T23:59:43.791Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-12T23:59:44.801Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 1009.8071ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 1009.8071ms"}} +[debug] [2026-04-12T23:59:44.801Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-12T23:59:44.801Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:44.801Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:44.802Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:50.181Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:50.181Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:50.181Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:50.181Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:50.181Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-12T23:59:50.183Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:50.183Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-12T23:59:50.183Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-12T23:59:50.183Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-12T23:59:50.184Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:50.184Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:50.181Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:50.184Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:50.181Z","/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:50.184Z"],"workRunningCount":2} +[debug] [2026-04-12T23:59:50.184Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:50.185Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:50.185Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:50.189Z] [worker-pool] addWorker(asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] addWorker(asia-northeast3-prediction)"}} +[debug] [2026-04-12T23:59:50.189Z] [worker-pool] Adding worker with key asia-northeast3-prediction, total=1 {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] Adding worker with key asia-northeast3-prediction, total=1"}} +[debug] [2026-04-12T23:59:50.190Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 6.493ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 6.493ms"}} +[debug] [2026-04-12T23:59:50.190Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-12T23:59:50.190Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:50.190Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:50.190Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:50.184Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:50.727Z] [runtime-status] [756912] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:50.728Z] [runtime-status] [756912] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:50.728Z] [runtime-status] [756912] Outgoing network have been stubbed. [{"name":"http","status":"mocked"},{"name":"http","status":"mocked"},{"name":"https","status":"mocked"},{"name":"https","status":"mocked"},{"name":"net","status":"mocked"}] {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Outgoing network have been stubbed. [{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"http\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"https\",\"status\":\"mocked\"},{\"name\":\"net\",\"status\":\"mocked\"}]"}} +[debug] [2026-04-12T23:59:50.728Z] [runtime-status] [756912] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:50.728Z] [runtime-status] [756912] Detected firebase-functions v7+, skipping legacy stubs. {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Detected firebase-functions v7+, skipping legacy stubs."}} +[debug] [2026-04-12T23:59:50.729Z] [runtime-status] [756912] Resolved module firebase-admin {"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Resolved module firebase-admin {\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:50.757Z] [runtime-status] [756912] Resolved module firebase-functions {"declared":true,"installed":true,"version":"7.2.2","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-functions\\lib\\v2\\index.js"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Resolved module firebase-functions {\"declared\":true,\"installed\":true,\"version\":\"7.2.2\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-functions\\\\lib\\\\v2\\\\index.js\"}"}} +[debug] [2026-04-12T23:59:50.882Z] [runtime-status] [756912] firebase-admin has been stubbed. {"adminResolution":{"declared":true,"installed":true,"version":"13.7.0","resolution":"D:\\Projects\\WebstormProjects\\mmday-firebase\\node_modules\\firebase-admin\\lib\\index.js"}} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] firebase-admin has been stubbed. {\"adminResolution\":{\"declared\":true,\"installed\":true,\"version\":\"13.7.0\",\"resolution\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\\\\node_modules\\\\firebase-admin\\\\lib\\\\index.js\"}}"}} +[debug] [2026-04-12T23:59:50.898Z] [runtime-status] [756912] Functions runtime initialized. {"cwd":"D:\\Projects\\WebstormProjects\\mmday-firebase","node_version":"24.14.1"} {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Functions runtime initialized. {\"cwd\":\"D:\\\\Projects\\\\WebstormProjects\\\\mmday-firebase\",\"node_version\":\"24.14.1\"}"}} +[debug] [2026-04-12T23:59:50.898Z] [runtime-status] [756912] Listening to port: \\?\pipe\fire_emu_954ab81c025cad8f {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[runtime-status] [756912] Listening to port: \\\\?\\pipe\\fire_emu_954ab81c025cad8f"}} +[debug] [2026-04-12T23:59:50.949Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:50.949Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:50.950Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:50.954Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 4.2172ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 4.2172ms"}} +[debug] [2026-04-12T23:59:50.954Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:50.954Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:50.954Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:50.954Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:51.189Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:51.189Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:51.189Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:51.189Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:51.189Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:51.190Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:51.190Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:51.190Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:51.190Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:51.192Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.7718ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.7718ms"}} +[debug] [2026-04-12T23:59:51.192Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:51.192Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:51.192Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:51.192Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:51.623Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:51.623Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:51.623Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:51.623Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:51.623Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:51.624Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:51.624Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:51.624Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:51.624Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:51.626Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3829ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3829ms"}} +[debug] [2026-04-12T23:59:51.626Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:51.626Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:51.626Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:51.626Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:52.461Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:52.461Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:52.461Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:52.461Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:52.461Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:52.462Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:52.462Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:52.462Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:52.462Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:52.463Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1489ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1489ms"}} +[debug] [2026-04-12T23:59:52.463Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:52.463Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:52.463Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:52.464Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:54.091Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:54.091Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:54.091Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:54.091Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:54.091Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:54.091Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:54.091Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:54.092Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:54.092Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:54.093Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3804ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3804ms"}} +[debug] [2026-04-12T23:59:54.093Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:54.093Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:54.093Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:54.093Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:56.633Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:56.633Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:56.633Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-12T23:59:56.633Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:56.633Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-12T23:59:56.633Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:56.634Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-12T23:59:56.634Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-12T23:59:56.634Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-12T23:59:56.637Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 2.5694ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 2.5694ms"}} +[debug] [2026-04-12T23:59:56.637Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-12T23:59:56.637Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:56.637Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:56.637Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:57.312Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:57.312Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-12T23:59:57.312Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-12T23:59:57.312Z"],"workRunningCount":1} +[debug] [2026-04-12T23:59:57.312Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-12T23:59:57.312Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-12T23:59:57.313Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-12T23:59:57.313Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-12T23:59:57.313Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-12T23:59:57.315Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.7487ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.7487ms"}} +[debug] [2026-04-12T23:59:57.315Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-12T23:59:57.315Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-12T23:59:57.315Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-12T23:59:57.315Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:03.081Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:03.081Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:03.081Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:03.081Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:03.081Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:00:03.082Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:03.082Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:00:03.082Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:00:03.083Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:00:03.084Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.6566ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.6566ms"}} +[debug] [2026-04-13T00:00:03.084Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:00:03.084Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:03.084Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:03.084Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:03.737Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:03.737Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:03.737Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:03.737Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:03.737Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:00:03.738Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:03.738Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:00:03.738Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:00:03.738Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:00:03.740Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.8128ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.8128ms"}} +[debug] [2026-04-13T00:00:03.740Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:00:03.740Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:03.740Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:03.740Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:09.521Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:09.521Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:09.521Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:09.521Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:09.521Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:00:09.522Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:09.523Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:00:09.523Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:00:09.523Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:00:09.524Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.5983ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.5983ms"}} +[debug] [2026-04-13T00:00:09.525Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:00:09.525Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:09.525Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:09.525Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:10.177Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:10.177Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:10.177Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:10.177Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:10.177Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:00:10.177Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:10.177Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:00:10.177Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:00:10.177Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:00:10.179Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.5731ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.5731ms"}} +[debug] [2026-04-13T00:00:10.179Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:00:10.179Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:10.179Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:10.179Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:15.972Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:15.972Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:15.973Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:15.972Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:15.973Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:00:15.974Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:15.974Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:00:15.974Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:00:15.974Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:00:15.975Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.5083ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.5083ms"}} +[debug] [2026-04-13T00:00:15.976Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:00:15.976Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:15.976Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:15.976Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:16.602Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:16.602Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:16.602Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:16.602Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:16.603Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:00:16.603Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:16.603Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:00:16.603Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:00:16.603Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:00:16.605Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.7249ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.7249ms"}} +[debug] [2026-04-13T00:00:16.605Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:00:16.605Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:16.605Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:16.605Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:22.409Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:22.409Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:22.410Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:00:22.409Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:22.410Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:00:22.410Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:22.411Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:00:22.411Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:00:22.411Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:00:22.412Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3951ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3951ms"}} +[debug] [2026-04-13T00:00:22.412Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:00:22.412Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:22.412Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:22.412Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:23.048Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:23.048Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:23.048Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:23.048Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:23.048Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:00:23.049Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:23.049Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:00:23.049Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:00:23.049Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:00:23.050Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.4773ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.4773ms"}} +[debug] [2026-04-13T00:00:23.051Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:00:23.051Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:23.051Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:23.051Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:29.489Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:29.489Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:00:29.489Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:00:29.489Z"],"workRunningCount":1} +[debug] [2026-04-13T00:00:29.489Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:00:29.490Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:00:29.490Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:00:29.490Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:00:29.490Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:00:29.492Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.2511ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.2511ms"}} +[debug] [2026-04-13T00:00:29.492Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:00:29.492Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:00:29.492Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:00:29.492Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.069Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.069Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.069Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.069Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.069Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:13.070Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.070Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:13.070Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:13.071Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:13.071Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.069Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.071Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.069Z","/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:13.071Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:05:13.072Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.072Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:05:13.072Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:05:13.072Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:05:13.074Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 3.2608ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 3.2608ms"}} +[debug] [2026-04-13T00:05:13.074Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:13.074Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.074Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.074Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.080Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.080Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.080Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.080Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:13.080Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:13.080Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.080Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:13.080Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:13.081Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:13.082Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.2778ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.2778ms"}} +[debug] [2026-04-13T00:05:13.082Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:13.082Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.082Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.082Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:13.071Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.100Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 27.8505ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 27.8505ms"}} +[debug] [2026-04-13T00:05:13.100Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:05:13.101Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.101Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.101Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.299Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.299Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.300Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.299Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.300Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:13.300Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.300Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:13.300Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:13.301Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:13.302Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.5433ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.5433ms"}} +[debug] [2026-04-13T00:05:13.302Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:13.302Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.302Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.302Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.313Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.313Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.313Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.313Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.313Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:13.314Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.314Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:13.314Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:13.314Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:13.315Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1884ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1884ms"}} +[debug] [2026-04-13T00:05:13.315Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:13.315Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.315Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.315Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.728Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.728Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.728Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:13.728Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.728Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:13.729Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.729Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:13.729Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:13.729Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:13.730Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3346ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3346ms"}} +[debug] [2026-04-13T00:05:13.730Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:13.731Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.731Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.731Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.774Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.774Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:13.774Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:13.774Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:13.774Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:13.775Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:13.775Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:13.775Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:13.775Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:13.776Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0664ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0664ms"}} +[debug] [2026-04-13T00:05:13.776Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:13.776Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:13.776Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:13.776Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:14.568Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:14.568Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:14.568Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:14.568Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:14.568Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:14.569Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:14.569Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:14.569Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:14.569Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:14.570Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.2275ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.2275ms"}} +[debug] [2026-04-13T00:05:14.570Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:14.570Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:14.570Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:14.570Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:14.605Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:14.605Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:14.605Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:14.605Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:14.605Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:14.606Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:14.606Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:14.606Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:14.606Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:14.607Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0241ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0241ms"}} +[debug] [2026-04-13T00:05:14.607Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:14.607Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:14.607Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:14.607Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:17.299Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:17.299Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.299Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:05:17.299Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:17.299Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:05:17.299Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:05:17.300Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:05:17.312Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.312Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.312Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.312Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:17.312Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:17.313Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:17.313Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:17.313Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:17.313Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:17.313Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.313Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.312Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:17.313Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.312Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.313Z"],"workRunningCount":3} +[debug] [2026-04-13T00:05:17.313Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:17.313Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:17.314Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:17.314Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:17.314Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.7353ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.7353ms"}} +[debug] [2026-04-13T00:05:17.315Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:17.315Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.313Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3294ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3294ms"}} +[debug] [2026-04-13T00:05:17.315Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:17.315Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:05:17.299Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.315Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 15.7336ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 15.7336ms"}} +[debug] [2026-04-13T00:05:17.316Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:05:17.316Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:17.316Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:17.316Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:17.578Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.578Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:17.578Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.578Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.578Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:17.578Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:17.578Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:17.578Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:17.578Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:17.579Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.579Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.578Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.579Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:17.578Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.579Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:17.579Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:17.579Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:17.579Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:17.579Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:17.579Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:17.580Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3858ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3858ms"}} +[debug] [2026-04-13T00:05:17.580Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:17.580Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:17.580Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:17.580Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:17.579Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:17.580Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1773ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1773ms"}} +[debug] [2026-04-13T00:05:17.581Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:17.581Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:17.581Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:17.581Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.019Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:18.019Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.019Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:18.019Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:18.019Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:18.019Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:18.020Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:18.020Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:18.020Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:18.021Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3609ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3609ms"}} +[debug] [2026-04-13T00:05:18.021Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:18.021Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:18.021Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:18.021Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.036Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:18.036Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.036Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:18.036Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:18.036Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:18.036Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:18.037Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:18.037Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:18.037Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:18.038Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 0.8937ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 0.8937ms"}} +[debug] [2026-04-13T00:05:18.038Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:18.038Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:18.038Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:18.038Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.862Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:18.862Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.862Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:18.862Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:18.862Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:18.862Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:18.862Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:18.862Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:18.863Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:18.864Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.41ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.41ms"}} +[debug] [2026-04-13T00:05:18.864Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:18.864Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:18.864Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:18.864Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.894Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:18.894Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:18.894Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:18.894Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:18.894Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:18.894Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:18.894Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:18.894Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:18.895Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:18.896Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0673ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0673ms"}} +[debug] [2026-04-13T00:05:18.896Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:18.896Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:18.896Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:18.896Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:20.499Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:20.499Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:20.499Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:20.499Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:20.499Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:20.499Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:20.500Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:20.500Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:20.500Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:20.501Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1987ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1987ms"}} +[debug] [2026-04-13T00:05:20.501Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:20.501Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:20.501Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:20.501Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:20.538Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:20.538Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:20.538Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:20.538Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:20.538Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:20.538Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:20.538Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:20.538Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:20.538Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:20.539Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1158ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1158ms"}} +[debug] [2026-04-13T00:05:20.539Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:20.540Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:20.540Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:20.540Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:23.747Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:23.747Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:23.747Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:23.747Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:23.747Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:23.748Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:23.748Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:23.748Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:23.748Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:23.749Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3198ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3198ms"}} +[debug] [2026-04-13T00:05:23.749Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:23.749Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:23.750Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:23.750Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:23.763Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:23.763Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:23.763Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:23.763Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:23.763Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:23.763Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:23.763Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:23.763Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:23.763Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:23.764Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 0.927ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 0.927ms"}} +[debug] [2026-04-13T00:05:23.764Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:23.764Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:23.764Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:23.764Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:30.187Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:30.187Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:30.187Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:30.187Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:30.187Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:30.188Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:30.189Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:30.189Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:30.189Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:30.190Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.3343ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.3343ms"}} +[debug] [2026-04-13T00:05:30.190Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:30.190Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:30.190Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:30.190Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:30.202Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:30.202Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:30.202Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:30.202Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:30.202Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:30.203Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:30.203Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:30.203Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:30.203Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:30.204Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.2217ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.2217ms"}} +[debug] [2026-04-13T00:05:30.204Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:30.204Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:30.204Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:30.204Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:36.650Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:36.650Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:36.650Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:36.650Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:36.650Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:36.651Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:36.652Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:36.652Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:36.652Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:36.653Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:36.653Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:36.650Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:36.653Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:36.650Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:36.653Z"],"workRunningCount":2} +[debug] [2026-04-13T00:05:36.653Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:36.654Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:36.654Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:36.654Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:36.654Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 2.7965ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 2.7965ms"}} +[debug] [2026-04-13T00:05:36.655Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:36.655Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:36.653Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1551ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1551ms"}} +[debug] [2026-04-13T00:05:36.655Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:36.655Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:36.655Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:43.106Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:43.106Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:43.106Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:43.106Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:43.106Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:43.107Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:43.107Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:43.107Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:43.107Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:43.108Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1379ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1379ms"}} +[debug] [2026-04-13T00:05:43.108Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:43.108Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:43.108Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:43.108Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:43.115Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:43.115Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:43.115Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:43.115Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:43.115Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:43.116Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:43.116Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:43.116Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:43.116Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:43.117Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 0.9888ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 0.9888ms"}} +[debug] [2026-04-13T00:05:43.118Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:43.118Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:43.118Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:43.118Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:49.563Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:49.563Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:49.564Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:49.563Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:49.564Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:49.565Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:49.565Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:49.565Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:49.565Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:49.567Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.324ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.324ms"}} +[debug] [2026-04-13T00:05:49.567Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:49.567Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:49.567Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:49.567Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:49.573Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:49.573Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:49.573Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:49.573Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:49.573Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:49.574Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:49.574Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:49.574Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:49.574Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:49.575Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1997ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1997ms"}} +[debug] [2026-04-13T00:05:49.575Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:49.575Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:49.575Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:49.575Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:56.061Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:56.061Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:56.061Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:05:56.061Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:56.061Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:05:56.062Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:56.062Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:05:56.062Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:05:56.063Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:05:56.064Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.2378ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.2378ms"}} +[debug] [2026-04-13T00:05:56.064Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:05:56.064Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:56.064Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:56.064Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:56.104Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:56.104Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:05:56.104Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:05:56.104Z"],"workRunningCount":1} +[debug] [2026-04-13T00:05:56.104Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:05:56.105Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:05:56.105Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:05:56.105Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:05:56.105Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:05:56.106Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1669ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1669ms"}} +[debug] [2026-04-13T00:05:56.106Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:05:56.106Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:05:56.106Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:05:56.106Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.449Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.449Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.449Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:06:20.451Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.451Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:06:20.451Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:06:20.451Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:06:20.456Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.456Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.456Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.456Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:20.456Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:20.457Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.457Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:20.457Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:20.458Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:20.458Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:20.458Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.456Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:20.458Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.456Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:20.458Z"],"workRunningCount":3} +[debug] [2026-04-13T00:06:20.458Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:20.459Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.459Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:20.459Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:20.459Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:20.460Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 2.5115ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 2.5115ms"}} +[debug] [2026-04-13T00:06:20.460Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:20.460Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.460Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.461Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:20.458Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:20.461Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.5899ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.5899ms"}} +[debug] [2026-04-13T00:06:20.461Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:20.461Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.461Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.461Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.449Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.467Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 16.4582ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 16.4582ms"}} +[debug] [2026-04-13T00:06:20.468Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:06:20.468Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.468Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.468Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.543Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.543Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.543Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:06:20.543Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.543Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:06:20.544Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.544Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:06:20.544Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:06:20.544Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:06:20.560Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 15.8885ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 15.8885ms"}} +[debug] [2026-04-13T00:06:20.560Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:06:20.561Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.561Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.561Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.721Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:20.721Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.721Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:20.721Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.721Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:20.722Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.722Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:20.722Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:20.722Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:20.723Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3876ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3876ms"}} +[debug] [2026-04-13T00:06:20.724Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:20.724Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.724Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.724Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.724Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.724Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:20.724Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:20.724Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:20.724Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:20.724Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:20.724Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:20.724Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:20.724Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:20.725Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 0.9421ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 0.9421ms"}} +[debug] [2026-04-13T00:06:20.725Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:20.725Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:20.725Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:20.725Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:21.149Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.149Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:21.149Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.149Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.149Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:21.149Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:21.149Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:21.149Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:21.150Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:21.150Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.150Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.149Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.150Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.149Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.150Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:21.150Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:21.150Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:21.150Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:21.150Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:21.150Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:21.151Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.4123ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.4123ms"}} +[debug] [2026-04-13T00:06:21.151Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:21.151Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:21.151Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:21.151Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.150Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.151Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0466ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0466ms"}} +[debug] [2026-04-13T00:06:21.152Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:21.152Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:21.152Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:21.152Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:21.969Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.969Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:21.969Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.969Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.969Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:21.970Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:21.970Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:21.970Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:21.970Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:21.971Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.971Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.969Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.971Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:21.969Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.971Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:21.971Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:21.971Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:21.971Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:21.971Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:21.971Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:21.972Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 2.0467ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 2.0467ms"}} +[debug] [2026-04-13T00:06:21.972Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:21.972Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:21.972Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:21.972Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:21.971Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:21.972Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.044ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.044ms"}} +[debug] [2026-04-13T00:06:21.972Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:21.973Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:21.973Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:21.973Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:23.604Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:23.604Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:23.604Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:23.604Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:23.604Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:23.605Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:23.605Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:23.605Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:23.605Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:23.606Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1062ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1062ms"}} +[debug] [2026-04-13T00:06:23.606Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:23.606Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:23.606Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:23.606Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:23.606Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:23.606Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:23.606Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:23.606Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:23.606Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:23.607Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:23.607Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:23.607Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:23.607Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:23.608Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 0.9691ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 0.9691ms"}} +[debug] [2026-04-13T00:06:23.608Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:23.608Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:23.608Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:23.608Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:27.147Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:27.147Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:27.147Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:27.147Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:27.147Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:27.147Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:27.147Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:27.147Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:27.148Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:27.148Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:27.148Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:27.147Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:27.148Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:27.147Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:27.148Z"],"workRunningCount":2} +[debug] [2026-04-13T00:06:27.148Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:27.148Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:27.149Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:27.149Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:27.149Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:27.149Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.5813ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.5813ms"}} +[debug] [2026-04-13T00:06:27.149Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:27.149Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:27.149Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:27.149Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:27.148Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:27.150Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0804ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0804ms"}} +[debug] [2026-04-13T00:06:27.150Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:27.150Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:27.150Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:27.150Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:33.585Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:33.585Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:33.586Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:33.585Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:33.586Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:33.587Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:33.587Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:33.587Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:33.587Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:33.588Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3012ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3012ms"}} +[debug] [2026-04-13T00:06:33.588Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:33.588Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:33.588Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:33.588Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:33.590Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:33.590Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:33.590Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:33.590Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:33.590Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:33.591Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:33.591Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:33.591Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:33.591Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:33.592Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 0.9282ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 0.9282ms"}} +[debug] [2026-04-13T00:06:33.592Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:33.592Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:33.592Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:33.592Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:40.045Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:40.045Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:40.045Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:40.045Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:40.045Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:40.047Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:40.047Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:40.047Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:40.047Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:40.048Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1724ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1724ms"}} +[debug] [2026-04-13T00:06:40.048Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:40.048Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:40.048Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:40.048Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:40.055Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:40.055Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:40.055Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:40.055Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:40.055Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:40.056Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:40.056Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:40.056Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:40.056Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:40.057Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.0751ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.0751ms"}} +[debug] [2026-04-13T00:06:40.057Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:40.057Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:40.057Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:40.057Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:46.504Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:46.504Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:46.504Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:46.504Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:46.504Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:46.505Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:46.505Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:46.505Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:46.505Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:46.507Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.2163ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.2163ms"}} +[debug] [2026-04-13T00:06:46.507Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:46.507Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:46.507Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:46.507Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:46.515Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:46.515Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:46.515Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:46.515Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:46.515Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:46.515Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:46.516Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:46.516Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:46.516Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:46.517Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.0528ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.0528ms"}} +[debug] [2026-04-13T00:06:46.517Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:46.517Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:46.517Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:46.517Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:52.944Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:52.944Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:52.944Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:52.944Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:52.944Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:52.945Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:52.945Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:52.945Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:52.945Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:52.947Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.4173ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.4173ms"}} +[debug] [2026-04-13T00:06:52.947Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:52.947Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:52.947Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:52.947Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:52.978Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:52.978Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:52.978Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:52.978Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:52.978Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:52.979Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:52.979Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:52.979Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:52.979Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:52.980Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1266ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1266ms"}} +[debug] [2026-04-13T00:06:52.980Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:52.980Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:52.981Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:52.981Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:59.383Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:59.383Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:59.383Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:06:59.383Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:59.383Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:06:59.384Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:59.384Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:06:59.384Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:06:59.384Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:06:59.386Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.4093ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.4093ms"}} +[debug] [2026-04-13T00:06:59.386Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:06:59.386Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:59.386Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:59.386Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:59.410Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:59.410Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:06:59.410Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:06:59.410Z"],"workRunningCount":1} +[debug] [2026-04-13T00:06:59.410Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:06:59.411Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:06:59.411Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:06:59.411Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:06:59.411Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:06:59.412Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1723ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1723ms"}} +[debug] [2026-04-13T00:06:59.412Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:06:59.412Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:06:59.412Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:06:59.412Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:28.832Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:28.832Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:28.832Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:07:28.833Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:28.833Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:07:28.833Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:07:28.834Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:07:28.837Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:28.837Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:28.837Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:28.837Z"],"workRunningCount":2} +[debug] [2026-04-13T00:07:28.837Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:28.838Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:28.838Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:28.838Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:28.839Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:28.839Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:28.839Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:28.837Z"],"workRunningCount":2} +[debug] [2026-04-13T00:07:28.839Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:28.837Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:28.839Z"],"workRunningCount":3} +[debug] [2026-04-13T00:07:28.839Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:28.840Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:28.840Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:28.840Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:28.840Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:28.841Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1747ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1747ms"}} +[debug] [2026-04-13T00:07:28.841Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:28.841Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:28.841Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:28.841Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:28.837Z"],"workRunningCount":2} +[debug] [2026-04-13T00:07:28.842Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 3.1091ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 3.1091ms"}} +[debug] [2026-04-13T00:07:28.842Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:28.842Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:28.842Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:28.842Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.832Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:28.845Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 11.0578ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 11.0578ms"}} +[debug] [2026-04-13T00:07:28.845Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:07:28.845Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:28.845Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:28.845Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:28.929Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.929Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:28.929Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/kbo/schedule-2026-04-13T00:07:28.929Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:28.929Z] Accepted request GET /mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4 --> asia-northeast3-kbo +[debug] [2026-04-13T00:07:28.930Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:28.930Z] [functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/kbo/schedule?year=2026&month=4, mapping to path=/schedule?year=2026&month=4"}} +[debug] [2026-04-13T00:07:28.930Z] [worker-pool] submitRequest(triggerId=asia-northeast3-kbo) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-kbo)"}} +[info] i functions: Beginning execution of "asia-northeast3-kbo" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Beginning execution of \"asia-northeast3-kbo\""}} +[debug] [2026-04-13T00:07:28.930Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: BUSY"}} +[debug] [2026-04-13T00:07:28.951Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-kbo" in 20.357ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finished \"asia-northeast3-kbo\" in 20.357ms"}} +[debug] [2026-04-13T00:07:28.951Z] [worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"[worker-asia-northeast3-kbo-3f128ef3-ac4b-4713-99d2-6cf0f9972135]: IDLE"}} +[debug] [2026-04-13T00:07:28.951Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:28.951Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-kbo"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:28.951Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.108Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.108Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.108Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.108Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:29.108Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:29.108Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:29.108Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:29.108Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:29.108Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:29.109Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:29.109Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.108Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:29.109Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.108Z","/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:29.109Z"],"workRunningCount":2} +[debug] [2026-04-13T00:07:29.109Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:29.109Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:29.109Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:29.109Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:29.109Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:29.110Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.4325ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.4325ms"}} +[debug] [2026-04-13T00:07:29.110Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:29.110Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:29.110Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:29.110Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:29.109Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:29.111Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.2817ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.2817ms"}} +[debug] [2026-04-13T00:07:29.111Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:29.111Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:29.111Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:29.111Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.537Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.537Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.537Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:29.537Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:29.537Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:29.537Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:29.537Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:29.537Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:29.538Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:29.539Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0596ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0596ms"}} +[debug] [2026-04-13T00:07:29.539Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:29.539Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:29.539Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:29.539Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.539Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:29.539Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:29.539Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:29.539Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:29.539Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:29.539Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:29.539Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:29.539Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:29.540Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:29.541Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1491ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1491ms"}} +[debug] [2026-04-13T00:07:29.541Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:29.541Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:29.541Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:29.541Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:30.362Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:30.362Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:30.362Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:30.362Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:30.362Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:30.363Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:30.363Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:30.363Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:30.363Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:30.364Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1329ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1329ms"}} +[debug] [2026-04-13T00:07:30.364Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:30.364Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:30.364Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:30.364Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:30.370Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:30.370Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:30.370Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:30.370Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:30.370Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:30.370Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:30.370Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:30.370Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:30.370Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:30.372Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1941ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1941ms"}} +[debug] [2026-04-13T00:07:30.372Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:30.372Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:30.372Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:30.372Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:31.993Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:31.993Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:31.993Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:31.993Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:31.993Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:31.994Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:31.994Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:31.994Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:31.994Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:31.995Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1318ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1318ms"}} +[debug] [2026-04-13T00:07:31.995Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:31.995Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:31.995Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:31.995Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:32.047Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:32.047Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:32.047Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:32.047Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:32.047Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:32.047Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:32.047Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:32.047Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:32.048Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:32.049Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0093ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0093ms"}} +[debug] [2026-04-13T00:07:32.049Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:32.049Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:32.049Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:32.049Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:35.223Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:35.223Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:35.223Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:35.223Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:35.223Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:35.224Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:35.224Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:35.224Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:35.224Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:35.225Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.0257ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.0257ms"}} +[debug] [2026-04-13T00:07:35.225Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:35.225Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:35.225Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:35.225Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:35.263Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:35.263Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:35.264Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:35.263Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:35.264Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:35.264Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:35.264Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:35.264Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:35.264Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:35.265Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.0916ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.0916ms"}} +[debug] [2026-04-13T00:07:35.265Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:35.265Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:35.265Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:35.265Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:41.676Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:41.676Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:41.676Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:41.676Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:41.676Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:41.677Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:41.677Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:41.677Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:41.678Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:41.679Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.2136ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.2136ms"}} +[debug] [2026-04-13T00:07:41.679Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:41.679Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:41.679Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:41.679Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:41.694Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:41.694Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:41.694Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:41.694Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:41.694Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:41.694Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:41.694Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:41.694Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:41.695Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:41.696Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 0.974ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 0.974ms"}} +[debug] [2026-04-13T00:07:41.696Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:41.696Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:41.696Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:41.696Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:48.131Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:48.131Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:48.131Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:48.131Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:48.131Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:48.132Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:48.132Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:48.132Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:48.132Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:48.133Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.0474ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.0474ms"}} +[debug] [2026-04-13T00:07:48.134Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:48.134Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:48.134Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:48.134Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:48.149Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:48.149Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:48.149Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:48.149Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:48.149Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:48.150Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:48.150Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:48.150Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:48.150Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:48.151Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.1108ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.1108ms"}} +[debug] [2026-04-13T00:07:48.151Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:48.151Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:48.151Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:48.151Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:54.578Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:54.578Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:54.578Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:07:54.578Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:54.578Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:07:54.579Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:54.579Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:07:54.579Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:07:54.580Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:07:54.581Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.1723ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.1723ms"}} +[debug] [2026-04-13T00:07:54.581Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:07:54.581Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:54.581Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:54.581Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:54.582Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:54.582Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:07:54.582Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:07:54.582Z"],"workRunningCount":1} +[debug] [2026-04-13T00:07:54.582Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:07:54.582Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:07:54.582Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:07:54.582Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:07:54.582Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:07:54.583Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 0.9499ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 0.9499ms"}} +[debug] [2026-04-13T00:07:54.584Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:07:54.584Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:07:54.584Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:07:54.584Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:01.027Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:01.027Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:01.027Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:01.027Z"],"workRunningCount":1} +[debug] [2026-04-13T00:08:01.027Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:08:01.028Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:08:01.028Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:08:01.028Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:08:01.029Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:08:01.029Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:08:01.029Z"],"queueLength":1,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:01.027Z"],"workRunningCount":1} +[debug] [2026-04-13T00:08:01.029Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:01.027Z","/mmday-panit/asia-northeast3/prediction-2026-04-13T00:08:01.029Z"],"workRunningCount":2} +[debug] [2026-04-13T00:08:01.029Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:08:01.030Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:08:01.030Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:08:01.030Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:08:01.030Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:08:01.031Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 2.1792ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 2.1792ms"}} +[debug] [2026-04-13T00:08:01.031Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:08:01.031Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:08:01.031Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:08:01.031Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:08:01.029Z"],"workRunningCount":1} +[debug] [2026-04-13T00:08:01.031Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.156ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.156ms"}} +[debug] [2026-04-13T00:08:01.031Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:08:01.031Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:08:01.032Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:08:01.032Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:07.476Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:08:07.476Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:07.476Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/prediction-2026-04-13T00:08:07.476Z"],"workRunningCount":1} +[debug] [2026-04-13T00:08:07.476Z] Accepted request GET /mmday-panit/asia-northeast3/prediction?date=2026-04-13 --> asia-northeast3-prediction +[debug] [2026-04-13T00:08:07.477Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:08:07.478Z] [functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13 {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/prediction?date=2026-04-13, mapping to path=/?date=2026-04-13"}} +[debug] [2026-04-13T00:08:07.478Z] [worker-pool] submitRequest(triggerId=asia-northeast3-prediction) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-prediction)"}} +[info] i functions: Beginning execution of "asia-northeast3-prediction" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Beginning execution of \"asia-northeast3-prediction\""}} +[debug] [2026-04-13T00:08:07.478Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: BUSY"}} +[debug] [2026-04-13T00:08:07.479Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-prediction" in 1.3179ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finished \"asia-northeast3-prediction\" in 1.3179ms"}} +[debug] [2026-04-13T00:08:07.479Z] [worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"[worker-asia-northeast3-prediction-f1c03d80-5c28-470d-ac9f-e901e16ec1bc]: IDLE"}} +[debug] [2026-04-13T00:08:07.479Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:08:07.479Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-prediction"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:08:07.479Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:07.481Z] [work-queue] {"queuedWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:07.481Z"],"queueLength":1,"runningWork":[],"workRunningCount":0} +[debug] [2026-04-13T00:08:07.481Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":["/mmday-panit/asia-northeast3/stats-2026-04-13T00:08:07.481Z"],"workRunningCount":1} +[debug] [2026-04-13T00:08:07.481Z] Accepted request GET /mmday-panit/asia-northeast3/stats?period=current --> asia-northeast3-stats +[debug] [2026-04-13T00:08:07.482Z] [functions] Runtime ready! Sending request! {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Runtime ready! Sending request!"}} +[debug] [2026-04-13T00:08:07.482Z] [functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current {"metadata":{"emulator":{"name":"functions"},"message":"[functions] Got req.url=/mmday-panit/asia-northeast3/stats?period=current, mapping to path=/?period=current"}} +[debug] [2026-04-13T00:08:07.482Z] [worker-pool] submitRequest(triggerId=asia-northeast3-stats) {"metadata":{"emulator":{"name":"functions"},"message":"[worker-pool] submitRequest(triggerId=asia-northeast3-stats)"}} +[info] i functions: Beginning execution of "asia-northeast3-stats" {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Beginning execution of \"asia-northeast3-stats\""}} +[debug] [2026-04-13T00:08:07.482Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: BUSY"}} +[debug] [2026-04-13T00:08:07.483Z] Finishing up request with event=pause {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=pause"}} +[info] i functions: Finished "asia-northeast3-stats" in 1.0295ms {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finished \"asia-northeast3-stats\" in 1.0295ms"}} +[debug] [2026-04-13T00:08:07.483Z] [worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"[worker-asia-northeast3-stats-7eb5440a-13e4-4039-9b90-13495e9d86e7]: IDLE"}} +[debug] [2026-04-13T00:08:07.484Z] Finishing up request with event=finish {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=finish"}} +[debug] [2026-04-13T00:08:07.484Z] Finishing up request with event=close {"metadata":{"emulator":{"name":"functions"},"function":{"name":"asia-northeast3-stats"},"extension":{},"message":"Finishing up request with event=close"}} +[debug] [2026-04-13T00:08:07.484Z] [work-queue] {"queuedWork":[],"queueLength":0,"runningWork":[],"workRunningCount":0} diff --git a/firestore-debug.log b/firestore-debug.log new file mode 100644 index 0000000..e69de29 diff --git a/remoteconfig.template.json b/remoteconfig.template.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/remoteconfig.template.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..6a2fc18 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,65 @@ +{ + "version": 1, + "skills": { + "developing-genkit-dart": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "ba0025db33c95d8b66cd6de1f4c25b8b70456fb2789ec6c97cd88d432eed3fb3" + }, + "developing-genkit-go": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "14dde37f197a606c7978a0876ca836002cae799dfc677d8da31b2f25ddee74e1" + }, + "developing-genkit-js": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "4d3de47b5be279ab3b0ee6055ae541f28d1cc45f8e8986c0b5df2f8d89f4ea30" + }, + "firebase-ai-logic": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "6ddf74ac9b3366d396e5fa85e695a7c5871e39edffc385533eaee2be159fcf03" + }, + "firebase-app-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "a3ba088442abf5b97281bcf3e4dd11e1f7bdefdc5bd404b4fb30f344d19742d2" + }, + "firebase-auth-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "a8fb7b1bfaf9f7d1bd1ebd7e1d2718f42f51361c8b2776ed1cdc17548334fe51" + }, + "firebase-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "13b74b8f7a751a359a11cff2d20968b94c93cb394f88bf3ffbce477376414fac" + }, + "firebase-data-connect": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "94bc7d16a4c368c9f3b29b3b26cea952a6a016c0e36b13b5805878ef2df1f7b6" + }, + "firebase-firestore-enterprise-native-mode": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "26a8074d01189118a59c0e70dbe6492945e446c3d0d721e60f5dcc5004d1bf97" + }, + "firebase-firestore-standard": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "82820bddbe8acd17df8b9d0555e79cd1783ffd3cdba1306a0c794c35cc5c1919" + }, + "firebase-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "0688a8ad6cb72149924352cc47e6cc8bf815e944b636a67b9da225cc9b025afc" + }, + "firestore-security-rules-auditor": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "f3e47896a49b76db787f47ee97f8cb2e23c51e4b18a73cd2ded32d6cc8c02869" + } + } +} diff --git a/src/constants/levels.ts b/src/constants/levels.ts new file mode 100644 index 0000000..5022574 --- /dev/null +++ b/src/constants/levels.ts @@ -0,0 +1,12 @@ +const LEVEL_THRESHOLDS = [0, 10, 30, 70, 150, 300, 600, 1000] as const; + +export function computeLevel(totalPredictions: number): { level: number; progress: number } { + let level = 1; + for (let i = 0; i < LEVEL_THRESHOLDS.length; i++) { + if (totalPredictions >= LEVEL_THRESHOLDS[i]) level = i + 1; + } + const min = LEVEL_THRESHOLDS[level - 1]; + const next = LEVEL_THRESHOLDS[level]; + const progress = next === undefined ? 1 : (totalPredictions - min) / (next - min); + return { level, progress: Math.max(0, Math.min(1, progress)) }; +} diff --git a/src/firebase.ts b/src/firebase.ts new file mode 100644 index 0000000..ba1290f --- /dev/null +++ b/src/firebase.ts @@ -0,0 +1,12 @@ +import { initializeApp, getApps } from "firebase-admin/app"; +import { getAuth } from "firebase-admin/auth"; +import { getFirestore } from "firebase-admin/firestore"; +import { getDatabase } from "firebase-admin/database"; + +if (getApps().length === 0) { + initializeApp(); +} + +export const auth = getAuth(); +export const firestore = getFirestore(); +export const rtdb = getDatabase(); diff --git a/src/handlers/adminHandlers.ts b/src/handlers/adminHandlers.ts new file mode 100644 index 0000000..99af996 --- /dev/null +++ b/src/handlers/adminHandlers.ts @@ -0,0 +1,24 @@ +import { onRequest } from "firebase-functions/https"; +import { requireAdmin } from "../middleware/admin.js"; +import { sendError } from "../middleware/errors.js"; +import { markGameEnded } from "../services/gameResultService.js"; + +export const admin = onRequest(async (req, res) => { + const segs = req.path.replace(/^\/+|\/+$/g, "").split("/"); + const tail = segs.slice(-2).join("/"); + + try { + await requireAdmin(req); + + if (tail === "game/end" && req.method === "POST") { + const { gameId, winningTeamCode } = req.body ?? {}; + const result = await markGameEnded(gameId, winningTeamCode); + res.status(200).json(result); + return; + } + + res.status(404).json({ error: `Unknown: ${req.method} ${req.path}` }); + } catch (err) { + sendError(res, err); + } +}); diff --git a/src/handlers/authHandlers.ts b/src/handlers/authHandlers.ts new file mode 100644 index 0000000..c772e3a --- /dev/null +++ b/src/handlers/authHandlers.ts @@ -0,0 +1,20 @@ +import { onRequest } from "firebase-functions/https"; +import { requireAuth } from "../middleware/auth.js"; +import { sendError } from "../middleware/errors.js"; +import { register } from "../services/authService.js"; + +export const auth = onRequest(async (req, res) => { + const path = req.path.replace(/^\/+|\/+$/g, "").split("/").pop() ?? ""; + + try { + if (path === "register" && req.method === "POST") { + const uid = await requireAuth(req); + const result = await register(uid, req.body ?? {}); + res.status(result.created ? 201 : 200).json(result); + return; + } + res.status(404).json({ error: `Unknown path: /${path}` }); + } catch (err) { + sendError(res, err); + } +}); diff --git a/src/handlers/kboHandlers.ts b/src/handlers/kboHandlers.ts new file mode 100644 index 0000000..8d9dbfb --- /dev/null +++ b/src/handlers/kboHandlers.ts @@ -0,0 +1,105 @@ +import { onRequest } from "firebase-functions/https"; +import { getRank } from "../services/rankService.js"; +import { getSchedule } from "../services/scheduleService.js"; +import { getPlayerStats, getValidPlayerTypes } from "../services/playerService.js"; +import type { PlayerFilters } from "../types/kbo.js"; + +enum KboPath { + Rank = "rank", + Schedule = "schedule", + Player = "player", +} + +function parseIntParam(val: unknown, fallback: number): number { + if (val === undefined || val === null || val === "") return fallback; + const n = parseInt(String(val), 10); + return isNaN(n) ? fallback : n; +} + +// GET /kbo/rank?year=2026 +// GET /kbo/schedule?year=2026&month=4&team=LG&series=정규 +// GET /kbo/player?type=hitter&year=2025&team=LG&series=7&all=true + +export const kbo = onRequest(async (req, res) => { + const path = req.path.replace(/^\/+|\/+$/g, "").split("/").pop() ?? ""; + + try { + switch (path) { + case KboPath.Rank: { + const yearParam = String(req.query.year ?? new Date().getFullYear()); + const years = yearParam.split(",").map((s) => parseInt(s.trim(), 10)); + + for (const y of years) { + if (isNaN(y) || y < 1982 || y > 2100) { + res.status(400).json({ error: `Invalid year: ${y} (1982~2100)` }); + return; + } + } + + const result = await getRank(years); + res.status(200).json(result); + return; + } + + case KboPath.Schedule: { + const now = new Date(); + const year = parseIntParam(req.query.year, now.getFullYear()); + const month = parseIntParam(req.query.month, now.getMonth() + 1); + const team = req.query.team ? String(req.query.team) : undefined; + const series = req.query.series ? String(req.query.series) : undefined; + + if (year < 1982 || year > 2100) { + res.status(400).json({ error: `Invalid year: ${year} (1982~2100)` }); + return; + } + if (month < 1 || month > 12) { + res.status(400).json({ error: `Invalid month: ${month} (1~12)` }); + return; + } + + const result = await getSchedule(year, month, team, series); + res.status(200).json(result); + return; + } + + case KboPath.Player: { + const type = String(req.query.type ?? ""); + const validTypes = getValidPlayerTypes(); + + if (!validTypes.includes(type)) { + res.status(400).json({ + error: `Invalid type: "${type}". Use: ${validTypes.join(", ")}`, + }); + return; + } + + const year = parseIntParam(req.query.year, new Date().getFullYear()); + const allPages = req.query.all === "true"; + + if (year < 1982 || year > 2100) { + res.status(400).json({ error: `Invalid year: ${year} (1982~2100)` }); + return; + } + + const filters: PlayerFilters = {}; + if (req.query.team) filters.team = String(req.query.team); + if (req.query.series) filters.series = String(req.query.series); + if (req.query.pos) filters.pos = String(req.query.pos); + if (req.query.situation) filters.situation = String(req.query.situation); + if (req.query.situationDetail) { + filters.situationDetail = String(req.query.situationDetail); + } + + const result = await getPlayerStats(type, year, filters, allPages); + res.status(200).json(result); + return; + } + + default: + res.status(404).json({ error: `Unknown path: /${path}. Use: /${Object.values(KboPath).join(", /")}` }); + } + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + res.status(500).json({ error: message }); + } +}); diff --git a/src/handlers/predictionHandlers.ts b/src/handlers/predictionHandlers.ts new file mode 100644 index 0000000..c687437 --- /dev/null +++ b/src/handlers/predictionHandlers.ts @@ -0,0 +1,57 @@ +import { onRequest } from "firebase-functions/https"; +import { requireAuth } from "../middleware/auth.js"; +import { sendError } from "../middleware/errors.js"; +import { + createPrediction, + updatePrediction, + getMyVotes, + getSummary, + listGamesByDate, +} from "../services/predictionService.js"; + +export const prediction = onRequest(async (req, res) => { + const segs = req.path.replace(/^\/+|\/+$/g, "").split("/"); + const tail = segs[segs.length - 1] ?? ""; + + try { + if (tail === "games" && req.method === "GET") { + const date = String(req.query.date ?? ""); + const games = await listGamesByDate(date); + res.status(200).json({ date, games }); + return; + } + + if (tail === "summary" && req.method === "GET") { + const gameId = String(req.query.gameId ?? ""); + const result = await getSummary(gameId); + res.status(200).json(result); + return; + } + + if (tail === "prediction" || segs.length === 1) { + if (req.method === "POST") { + const uid = await requireAuth(req); + const result = await createPrediction(uid, req.body ?? {}); + res.status(201).json(result); + return; + } + if (req.method === "PUT") { + const uid = await requireAuth(req); + const result = await updatePrediction(uid, req.body ?? {}); + res.status(200).json(result); + return; + } + if (req.method === "GET") { + const uid = await requireAuth(req); + const date = String(req.query.date ?? ""); + const result = await getMyVotes(uid, date); + res.status(200).json(result); + return; + } + } + + res.status(404).json({ error: `Unknown: ${req.method} ${req.path}` }); + } catch (err) { + sendError(res, err); + } +}); diff --git a/src/handlers/statsHandlers.ts b/src/handlers/statsHandlers.ts new file mode 100644 index 0000000..b3897f6 --- /dev/null +++ b/src/handlers/statsHandlers.ts @@ -0,0 +1,31 @@ +import { onRequest } from "firebase-functions/https"; +import { requireAuth } from "../middleware/auth.js"; +import { sendError } from "../middleware/errors.js"; +import { getStats, getHistory } from "../services/statsService.js"; + +export const stats = onRequest(async (req, res) => { + const segs = req.path.replace(/^\/+|\/+$/g, "").split("/"); + const tail = segs[segs.length - 1] ?? ""; + + try { + const uid = await requireAuth(req); + + if (tail === "history" && req.method === "GET") { + const date = String(req.query.date ?? ""); + const result = await getHistory(uid, date); + res.status(200).json(result); + return; + } + + if ((tail === "stats" || segs.length === 1) && req.method === "GET") { + const period = req.query.period ? String(req.query.period) : undefined; + const result = await getStats(uid, period); + res.status(200).json(result); + return; + } + + res.status(404).json({ error: `Unknown: ${req.method} ${req.path}` }); + } catch (err) { + sendError(res, err); + } +}); diff --git a/src/kbo/README.md b/src/kbo/README.md new file mode 100644 index 0000000..b1b37d1 --- /dev/null +++ b/src/kbo/README.md @@ -0,0 +1,325 @@ +# KBO 데이터 조회 가이드 + +KBO(한국프로야구) 공식 사이트에서 팀 순위, 선수 기록, 경기 일정/결과를 조회하는 모듈이다. +이 문서는 AI가 사용자 요청에 따라 적절한 함수를 호출하기 위한 참조 문서이다. + +--- + +## 조회 가능한 데이터 + +### 1. 팀 순위 + +특정 연도의 KBO 정규시즌 팀 순위와 팀간 승패표를 조회한다. + +- 조회 범위: 1982년 ~ 현재 +- 반환 데이터: 순위, 팀명, 승/패/무, 승률, 게임차, 최근10경기, 연속, 홈/원정 성적 +- 팀간 승패표: 각 팀의 상대 전적 (승-패-무) + +### 2. 경기 일정/결과 + +특정 연/월의 KBO 경기 일정과 결과를 조회한다. + +- 조회 범위: 연도 + 월 단위 +- 시리즈: 정규시즌, 시범경기, 포스트시즌 +- 반환 데이터: 날짜, 시간, 원정팀, 홈팀, 점수, 경기 상태(완료/취소/예정), 구장, 중계, gameId +- 팀 필터 지원 + +### 3. 선수 기록 + +4가지 카테고리의 선수 기록을 조회한다. + +| 카테고리 | 설명 | Config | +|----------|------|--------| +| hitter | 타자 기본기록 | `HITTER_CONFIG` | +| pitcher | 투수 기본기록 | `PITCHER_CONFIG` | +| defense | 수비 기록 | `DEFENSE_CONFIG` | +| runner | 주루 기록 | `RUNNER_CONFIG` | + +--- + +## 호출 방법 + +### 팀 순위 조회 + +```typescript +import { fetchTeamRankInitial, fetchTeamRank } from "./kbo/team-rank.js"; + +// 현재 연도 순위 +const { result, state, currentYear } = await fetchTeamRankInitial(); + +// 다른 연도 순위 (state 재사용) +const { result: r2024 } = await fetchTeamRank(2024, state, currentYear); +``` + +**result 구조:** +- `result.year` — 조회 연도 +- `result.teams` — 팀 순위 배열, 각 항목의 필드: + - `rank`, `team`, `games`, `wins`, `losses`, `draws`, `winRate`, `gamesBehind`, `last10`, `streak`, `home`, `away` +- `result.vsRecords` — 팀간 승패표 배열, 각 항목의 필드: + - `team` — 팀명 + - `headToHead` — `{ "상대팀명": [승, 패, 무] }` 형태 + - `total` — `[총승, 총패, 총무]` + +### 경기 일정/결과 조회 + +```typescript +import { fetchSchedule, SERIES_CODES } from "./kbo/schedule.js"; + +// 현재 월 정규시즌 전체 경기 +const result = await fetchSchedule({ year: 2026, month: 4 }); + +// 특정 팀 경기만 +const lgGames = await fetchSchedule({ year: 2026, month: 4, team: "LG" }); + +// 시범경기 +const exhibition = await fetchSchedule({ year: 2026, month: 3, series: "1" }); + +// 포스트시즌 +const postseason = await fetchSchedule({ year: 2025, month: 10, series: "3,4,5,7" }); +``` + +**result 구조:** +- `result.year` — 조회 연도 +- `result.month` — 조회 월 +- `result.games` — 경기 배열, 각 항목의 필드: + - `date` — 날짜 (예: `"04.01"`) + - `dayOfWeek` — 요일 (예: `"수"`) + - `time` — 시간 (예: `"18:30"`) + - `awayTeam` — 원정팀명 (예: `"KIA"`) + - `homeTeam` — 홈팀명 (예: `"LG"`) + - `awayScore` — 원정팀 점수 (`null` if 미진행) + - `homeScore` — 홈팀 점수 (`null` if 미진행) + - `status` — 경기 상태: `"completed"` | `"cancelled"` | `"scheduled"` + - `stadium` — 구장 (예: `"잠실"`) + - `broadcast` — 중계 (예: `"KN-T"`) + - `note` — 비고 (예: `"-"`, `"우천취소"`) + - `gameId` — 경기 ID (예: `"20260401HTLG0"`, 미진행 시 `null`) + +**시리즈 코드 (SERIES_CODES):** + +| 키 | 값 | 설명 | +|----|-----|------| +| `"정규"` / `"regular"` | `"0,9,6"` | 정규시즌 (기본값) | +| `"시범"` / `"exhibition"` | `"1"` | 시범경기 | +| `"포스트"` / `"postseason"` | `"3,4,5,7"` | 포스트시즌 | + +### 선수 기록 조회 + +```typescript +import { fetchPlayerStatsInitial, fetchPlayerStats, fetchAllPlayerStats, TEAM_CODES } from "./kbo/player/common.js"; +import { HITTER_CONFIG } from "./kbo/player/hitter.js"; +import { PITCHER_CONFIG } from "./kbo/player/pitcher.js"; +import { DEFENSE_CONFIG } from "./kbo/player/defense.js"; +import { RUNNER_CONFIG } from "./kbo/player/runner.js"; + +// 1. 초기 상태 획득 (반드시 먼저 호출) +const { state } = await fetchPlayerStatsInitial(HITTER_CONFIG); + +// 2. 조건부 조회 +const { result } = await fetchPlayerStats(HITTER_CONFIG, 2025, state, { + team: "LG", // 선택 + series: "0", // 선택 + pos: "7,8,9", // 선택 +}); + +// 3. 전체 선수 조회 (페이지네이션 자동 처리) +const { result: all } = await fetchAllPlayerStats(HITTER_CONFIG, 2025, state, {}); +``` + +**result 구조:** +- `result.year` — 조회 연도 +- `result.filters` — 적용된 필터 +- `result.columns` — 현재 결과의 컬럼 이름 배열 +- `result.records` — 선수 기록 배열, 각 항목은 `{ [컬럼명]: 값 }` 형태 + +--- + +## 필터 상세 + +### team — 팀 필터 + +팀명 또는 팀 코드로 지정한다. 팀명을 사용할 경우 `TEAM_CODES`로 자동 변환된다. + +| 팀명 | 코드 | 팀명 | 코드 | +|------|------|------|------| +| KT | KT | 롯데 | LT | +| NC | NC | 한화 | HH | +| SSG | SK | 두산 | OB | +| LG | LG | 삼성 | SS | +| KIA | HT | 키움 | WO | + +### series — 시리즈 필터 + +| 값 | 시리즈 | +|----|--------| +| `"0"` | KBO 정규시즌 (기본값) | +| `"1"` | KBO 시범경기 | +| `"3"` | KBO 준플레이오프 | +| `"4"` | KBO 와일드카드 | +| `"5"` | KBO 플레이오프 | +| `"7"` | KBO 한국시리즈 | + +> 정규시즌이 아닌 시리즈를 선택하면 테이블 컬럼이 변경된다. 아래 "컬럼 정의" 참조. + +### pos — 포지션 필터 + +| 값 | 포지션 | +|----|--------| +| `"2"` | 포수 | +| `"3,4,5,6"` | 내야수 | +| `"7,8,9"` | 외야수 | + +> hitter, defense, runner에만 적용된다. pitcher에는 없다. + +### situation — 경기 상황별 필터 + +| 값 | 설명 | 적용 대상 | +|----|------|-----------| +| `"MONTH_SC"` | 월별 | 타자, 투수 | +| `"WEEK_SC"` | 요일별 | 타자, 투수 | +| `"STADIUM_SC"` | 구장별 | 타자, 투수 | +| `"HOMEAYAY_SC"` | 홈/방문별 | 타자, 투수 | +| `"OPPTEAM_SC"` | 상대팀별 | 타자, 투수 | +| `"DAYNIGHT_SC"` | 주/야간별 | 타자, 투수 | +| `"HALF_SC"` | 전/후반기별 | 타자, 투수 | +| `"41"` | 투수유형별 | 타자 전용 | +| `"42"` | 타자유형별 | 투수 전용 | +| `"43"` | 주자상황별 | 타자, 투수 | +| `"44"` | 볼카운트별 | 타자, 투수 | +| `"45"` | 아웃카운트별 | 타자, 투수 | +| `"46"` | 이닝별 | 타자, 투수 | +| `"47"` | 타순별 | 타자, 투수 | + +> defense, runner에는 situation 필터가 없다. + +### situationDetail — 상황 세부 필터 + +situation에 종속되는 하위 필터. situation 선택 시 서버가 동적으로 선택지를 반환한다. + +--- + +## 컬럼 정의 + +### 타자 — 정규시즌 (16컬럼) + +| 컬럼 | 설명 | 컬럼 | 설명 | +|------|------|------|------| +| rank | 순위 | runs | 득점 | +| player | 선수명 | hits | 안타 | +| team | 팀명 | doubles | 2루타 | +| avg | 타율 | triples | 3루타 | +| games | 경기 수 | hr | 홈런 | +| pa | 타석 | tb | 루타 | +| ab | 타수 | rbi | 타점 | +| sac | 희생번트 | sf | 희생플라이 | + +### 타자 — 포스트시즌 (19컬럼) + +| 컬럼 | 설명 | 컬럼 | 설명 | +|------|------|------|------| +| rank | 순위 | rbi | 타점 | +| player | 선수명 | sb | 도루 | +| team | 팀명 | cs | 도루실패 | +| avg | 타율 | bb | 볼넷 | +| games | 경기 수 | hbp | 사구 | +| pa | 타석 | so | 삼진 | +| ab | 타수 | gdp | 병살타 | +| hits | 안타 | errors | 실책 | +| doubles | 2루타 | | | +| triples | 3루타 | | | +| hr | 홈런 | | | + +### 투수 — 정규시즌 (19컬럼) + +| 컬럼 | 설명 | 컬럼 | 설명 | +|------|------|------|------| +| rank | 순위 | ip | 이닝 | +| player | 선수명 | hits | 피안타 | +| team | 팀명 | hr | 피홈런 | +| era | 평균자책점 | bb | 볼넷 | +| games | 경기 수 | hbp | 사구 | +| wins | 승 | so | 탈삼진 | +| losses | 패 | runs | 실점 | +| saves | 세이브 | er | 자책점 | +| holds | 홀드 | whip | WHIP | +| wpct | 승률 | | | + +### 투수 — 포스트시즌 (21컬럼) + +| 컬럼 | 설명 | 컬럼 | 설명 | +|------|------|------|------| +| rank | 순위 | wpct | 승률 | +| player | 선수명 | tbf | 타자 수 | +| team | 팀명 | ip | 이닝 | +| era | 평균자책점 | hits | 피안타 | +| games | 경기 수 | hr | 피홈런 | +| cg | 완투 | bb | 볼넷 | +| sho | 완봉 | hbp | 사구 | +| wins | 승 | so | 탈삼진 | +| losses | 패 | runs | 실점 | +| saves | 세이브 | er | 자책점 | +| holds | 홀드 | | | + +### 수비 (17컬럼) + +| 컬럼 | 설명 | 컬럼 | 설명 | +|------|------|------|------| +| rank | 순위 | po | 자살 | +| player | 선수명 | assists | 보살 | +| team | 팀명 | dp | 병살 | +| pos | 포지션 | fpct | 수비율 | +| games | 경기 수 | pb | 포일 | +| gs | 선발 출장 | sb | 도루 허용 | +| ip | 수비 이닝 | cs | 도루 저지 | +| errors | 실책 | csPct | 도루 저지율 | +| pko | 견제사 | | | + +### 주루 (10컬럼) + +| 컬럼 | 설명 | +|------|------| +| rank | 순위 | +| player | 선수명 | +| team | 팀명 | +| games | 경기 수 | +| sba | 도루 시도 | +| sb | 도루 성공 | +| cs | 도루 실패 | +| sbPct | 도루 성공률 | +| oob | 아웃 온 베이스 | +| pko | 견제사 | + +--- + +## 요청 → 호출 매핑 예시 + +| 사용자 요청 | Config | 연도 | 필터 | +|-------------|--------|------|------| +| "2025 팀 순위 알려줘" | (team-rank) | 2025 | — | +| "올해 LG 타자 성적" | HITTER_CONFIG | 2025 | `{ team: "LG" }` | +| "2024 삼성 투수 기록" | PITCHER_CONFIG | 2024 | `{ team: "삼성" }` | +| "2025 한국시리즈 타자 성적" | HITTER_CONFIG | 2025 | `{ series: "7" }` | +| "올해 포수 수비 기록" | DEFENSE_CONFIG | 2025 | `{ pos: "2" }` | +| "2025 NC 도루 기록" | RUNNER_CONFIG | 2025 | `{ team: "NC" }` | +| "2024 KIA 외야수 타자 기록" | HITTER_CONFIG | 2024 | `{ team: "KIA", pos: "7,8,9" }` | +| "2025 시범경기 투수 성적" | PITCHER_CONFIG | 2025 | `{ series: "1" }` | +| "올해 LG 한화 팀간 전적" | (team-rank) | 2025 | — (vsRecords에서 추출) | +| "2025 홈/원정별 타자 성적" | HITTER_CONFIG | 2025 | `{ situation: "HOMEAYAY_SC" }` | +| "2025 월별 투수 성적" | PITCHER_CONFIG | 2025 | `{ situation: "MONTH_SC" }` | +| "올해 플레이오프 LG 타자 기록" | HITTER_CONFIG | 2025 | `{ series: "5", team: "LG" }` | +| "이번 달 경기 일정" | (schedule) | 현재 | — | +| "2026년 4월 LG 경기 결과" | (schedule) | 2026-04 | `{ team: "LG" }` | +| "올해 시범경기 일정" | (schedule) | 2026-03 | `{ series: "1" }` | +| "2025년 10월 포스트시즌 경기" | (schedule) | 2025-10 | `{ series: "3,4,5,7" }` | + +--- + +## 주의사항 + +- `fetchPlayerStatsInitial()`은 반드시 `fetchPlayerStats()` 또는 `fetchAllPlayerStats()` 전에 호출하여 `state`를 획득해야 한다. +- 한 번의 `fetchPlayerStats()` 호출은 1페이지(최대 30명)만 반환한다. 전체 선수 목록이 필요하면 `fetchAllPlayerStats()`를 사용한다. +- 포스트시즌(series != "0") 조회 시 컬럼 구성이 정규시즌과 다르다. `result.columns`를 확인하여 현재 결과의 컬럼 구성을 파악한다. +- 팀 필터에 팀명(한글/영문)을 넣으면 `TEAM_CODES`를 통해 내부 코드로 자동 변환된다. +- 데이터 조회 가능 연도 범위는 1982년부터 현재 연도까지이다. +- `fetchSchedule()`은 별도의 초기 상태(state) 없이 바로 호출할 수 있다 (JSON API 사용). +- 경기 일정은 월 단위로 조회되며, `series` 미지정 시 정규시즌(`"0,9,6"`)이 기본값이다. \ No newline at end of file diff --git a/src/kbo/schedule.ts b/src/kbo/schedule.ts new file mode 100644 index 0000000..6ca22ff --- /dev/null +++ b/src/kbo/schedule.ts @@ -0,0 +1,241 @@ +import { stripTags, decodeHtmlEntities } from "./html-utils.js"; +import { TEAM_CODES } from "./player/common.js"; + +function toTeamCode(name: string): string { + return TEAM_CODES[name] ?? name; +} + +const SCHEDULE_URL = + "https://www.koreabaseball.com/ws/Schedule.asmx/GetScheduleList"; + +const USER_AGENT = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/147.0.0.0 Safari/537.36"; + +// ── Types ── + +export type GameStatus = "completed" | "cancelled" | "scheduled"; + +export interface ScheduleGame { + date: string; + dayOfWeek: string; + time: string; + awayTeamCode: string; + homeTeamCode: string; + awayScore: number | null; + homeScore: number | null; + status: GameStatus; + stadium: string; + broadcast: string; + note: string; + gameId: string | null; +} + +export interface ScheduleFilters { + year: number; + month: number; + series?: string; + team?: string; +} + +export interface ScheduleResult { + year: number; + month: number; + games: ScheduleGame[]; +} + +export const SERIES_CODES: Record = { + 정규: "0,9,6", + regular: "0,9,6", + 시범: "1", + exhibition: "1", + 포스트: "3,4,5,7", + postseason: "3,4,5,7", +}; + +// ── API Response Types ── + +interface Cell { + Text: string; + Class: string | null; + RowSpan: string | null; +} + +interface Row { + row: Cell[]; +} + +interface ScheduleResponse { + rows: Row[]; +} + +// ── Parsing ── + +function parseDate(text: string): { date: string; dayOfWeek: string } { + const cleaned = stripTags(decodeHtmlEntities(text)); + const m = cleaned.match(/^(\d{2}\.\d{2})\((.)\)/); + if (m) return { date: m[1], dayOfWeek: m[2] }; + return { date: cleaned, dayOfWeek: "" }; +} + +function parseTime(text: string): string { + return stripTags(decodeHtmlEntities(text)); +} + +function parsePlayCell(html: string): { + awayTeamCode: string; + homeTeamCode: string; + awayScore: number | null; + homeScore: number | null; + status: GameStatus; +} { + // Away team: first before + // Home team: last after + const teamMatch = html.match( + /^(.*?)<\/span>([\s\S]*?)<\/em>(.*?)<\/span>$/ + ); + + if (!teamMatch) { + // Fallback: extract all span texts + const spans: string[] = []; + const spanRegex = /]*>(.*?)<\/span>/g; + let m: RegExpExecArray | null; + while ((m = spanRegex.exec(html)) !== null) { + spans.push(m[1]); + } + return { + awayTeamCode: toTeamCode(spans[0] ?? ""), + homeTeamCode: toTeamCode(spans[spans.length - 1] ?? ""), + awayScore: null, + homeScore: null, + status: "scheduled", + }; + } + + const awayTeamCode = toTeamCode(teamMatch[1]); + const homeTeamCode = toTeamCode(teamMatch[3]); + const emContent = teamMatch[2]; + + // Check for scores inside + const scoreRegex = /(\d+)<\/span>/g; + const scores: { cls: string; val: number }[] = []; + let sm: RegExpExecArray | null; + while ((sm = scoreRegex.exec(emContent)) !== null) { + scores.push({ cls: sm[1], val: parseInt(sm[2], 10) }); + } + + if (scores.length === 2) { + // First score = away, second score = home + return { + awayTeamCode, + homeTeamCode, + awayScore: scores[0].val, + homeScore: scores[1].val, + status: "completed", + }; + } + + return { + awayTeamCode, + homeTeamCode, + awayScore: null, + homeScore: null, + status: "scheduled", + }; +} + +function parseGameId(html: string): string | null { + const m = html.match(/gameId=([A-Za-z0-9]+)/); + return m ? m[1] : null; +} + +export function parseScheduleResponse(data: ScheduleResponse): ScheduleGame[] { + const games: ScheduleGame[] = []; + let currentDate = ""; + let currentDayOfWeek = ""; + + for (const row of data.rows) { + const cells = row.row; + if (cells.length === 0) continue; + + let offset = 0; + + // Check if first cell is a date cell (Class=day) + if (cells[0].Class === "day") { + const parsed = parseDate(cells[0].Text); + currentDate = parsed.date; + currentDayOfWeek = parsed.dayOfWeek; + offset = 1; + } + + // Cells relative to offset: + // [0] time, [1] play, [2] relay (review link), [3] highlight, + // [4] TV, [5] radio, [6] stadium, [7] note + const timeCell = cells[offset]; + const playCell = cells[offset + 1]; + const relayCell = cells[offset + 2]; + const tvCell = cells[offset + 4]; + const stadiumCell = cells[offset + 6]; + const noteCell = cells[offset + 7]; + + if (!playCell || playCell.Class !== "play") continue; + + const time = parseTime(timeCell?.Text ?? ""); + const play = parsePlayCell(playCell.Text); + const gameId = parseGameId(relayCell?.Text ?? ""); + const broadcast = stripTags(decodeHtmlEntities(tvCell?.Text ?? "")); + const stadium = stripTags(decodeHtmlEntities(stadiumCell?.Text ?? "")); + const note = stripTags(decodeHtmlEntities(noteCell?.Text ?? "")); + + let status = play.status; + if (status !== "completed" && note && note !== "-") { + status = "cancelled"; + } + + games.push({ + date: currentDate, + dayOfWeek: currentDayOfWeek, + time, + awayTeamCode: play.awayTeamCode, + homeTeamCode: play.homeTeamCode, + awayScore: play.awayScore, + homeScore: play.homeScore, + status, + stadium, + broadcast, + note, + gameId, + }); + } + + return games; +} + +// ── Fetch ── + +export async function fetchSchedule( + filters: ScheduleFilters +): Promise { + const body = new URLSearchParams({ + leId: "1", + srIdList: filters.series ?? "0,9,6", + seasonId: String(filters.year), + gameMonth: String(filters.month).padStart(2, "0"), + teamId: filters.team ?? "", + }); + + const res = await fetch(SCHEDULE_URL, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "User-Agent": USER_AGENT, + "X-Requested-With": "XMLHttpRequest", + Referer: "https://www.koreabaseball.com/Schedule/Schedule.aspx", + }, + body: body.toString(), + }); + + const json: ScheduleResponse = await res.json(); + const games = parseScheduleResponse(json); + + return { year: filters.year, month: filters.month, games }; +} diff --git a/src/middleware/admin.ts b/src/middleware/admin.ts new file mode 100644 index 0000000..ea69e7a --- /dev/null +++ b/src/middleware/admin.ts @@ -0,0 +1,21 @@ +import type { Request } from "firebase-functions/https"; +import { auth } from "../firebase.js"; +import { HttpError } from "./errors.js"; + +export async function requireAdmin(req: Request): Promise { + const header = req.get("authorization") ?? req.get("Authorization"); + if (!header || !header.startsWith("Bearer ")) { + throw new HttpError(401, "Missing Bearer token"); + } + const token = header.substring(7).trim(); + try { + const decoded = await auth.verifyIdToken(token); + if (decoded.admin !== true) { + throw new HttpError(403, "admin claim required"); + } + return decoded.uid; + } catch (err) { + if (err instanceof HttpError) throw err; + throw new HttpError(401, "Invalid token"); + } +} diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts new file mode 100644 index 0000000..af0f945 --- /dev/null +++ b/src/middleware/auth.ts @@ -0,0 +1,19 @@ +import type { Request } from "firebase-functions/https"; +import { auth } from "../firebase.js"; +import { HttpError } from "./errors.js"; + +export async function requireAuth(req: Request): Promise { + const header = req.get("authorization") ?? req.get("Authorization"); + if (!header || !header.startsWith("Bearer ")) { + throw new HttpError(401, "Missing Bearer token"); + } + const token = header.substring(7).trim(); + if (!token) throw new HttpError(401, "Empty token"); + + try { + const decoded = await auth.verifyIdToken(token); + return decoded.uid; + } catch { + throw new HttpError(401, "Invalid token"); + } +} diff --git a/src/middleware/errors.ts b/src/middleware/errors.ts new file mode 100644 index 0000000..acb8408 --- /dev/null +++ b/src/middleware/errors.ts @@ -0,0 +1,16 @@ +import type express from "express"; + +export class HttpError extends Error { + constructor(public status: number, message: string) { + super(message); + } +} + +export function sendError(res: express.Response, err: unknown): void { + if (err instanceof HttpError) { + res.status(err.status).json({ error: err.message }); + return; + } + const message = err instanceof Error ? err.message : String(err); + res.status(500).json({ error: message }); +} diff --git a/src/repositories/gameRepository.ts b/src/repositories/gameRepository.ts new file mode 100644 index 0000000..a58300c --- /dev/null +++ b/src/repositories/gameRepository.ts @@ -0,0 +1,37 @@ +import { Timestamp } from "firebase-admin/firestore"; +import { firestore } from "../firebase.js"; +import type { Game } from "../types/panit.js"; +import { startOfDayKst, type DateString } from "../types/dateString.js"; + +const COLLECTION = "games"; + +export type GameWithId = Game & { gameId: string }; + +/** + * Firestore `games` 컬렉션에서 특정 경기 정보를 조회한다. + * + * @param gameId - KBO 경기 ID (예: `20260401HTLG0`) + * @returns 경기 문서. 존재하지 않으면 `null`. + */ +export async function getGame(gameId: string): Promise { + const snap = await firestore.collection(COLLECTION).doc(gameId).get(); + return snap.exists ? (snap.data() as Game) : null; +} + +/** + * 지정한 KST 날짜의 모든 경기를 시간순으로 조회한다. + * + * @param date - 조회할 KST 날짜 (YYYY-MM-DD) + * @returns `gameId`를 포함한 경기 문서 배열. 없으면 빈 배열. + */ +export async function listByDate(date: DateString): Promise { + const start = Timestamp.fromDate(startOfDayKst(date)); + const end = Timestamp.fromMillis(start.toMillis() + 24 * 60 * 60 * 1000); + const snap = await firestore + .collection(COLLECTION) + .where("time", ">=", start) + .where("time", "<", end) + .orderBy("time") + .get(); + return snap.docs.map((d) => ({ gameId: d.id, ...(d.data() as Game) })); +} diff --git a/src/repositories/kboCacheRepository.ts b/src/repositories/kboCacheRepository.ts new file mode 100644 index 0000000..0b25074 --- /dev/null +++ b/src/repositories/kboCacheRepository.ts @@ -0,0 +1,145 @@ +import { FieldValue } from "firebase-admin/firestore"; +import { firestore } from "../firebase.js"; + +const CACHE_COLLECTION = "kboCache"; +const LOCK_COLLECTION = "kboLocks"; +const LOCK_TTL_MS = 30_000; + +interface CacheDoc { + data: T; + updatedAt: FirebaseFirestore.Timestamp; +} + +interface LockDoc { + acquiredAt: FirebaseFirestore.Timestamp; +} + +/** + * 캐시 키로 사용할 안전한 문자열을 생성한다. + * + * `undefined`/빈 문자열은 제외하고, 영숫자/하이픈/언더스코어 이외의 문자는 `_`로 치환한 뒤 `__`로 연결한다. + * + * @param parts - 키를 구성할 값의 배열 + * @returns Firestore 문서 ID로 안전하게 쓸 수 있는 문자열 + */ +export function encodeKey(parts: Array): string { + return parts + .filter((p) => p !== undefined && p !== "") + .map((p) => String(p).replace(/[^\w-]/g, "_")) + .join("__"); +} + +/** + * 캐시 문서를 조회하고 TTL 이내면 데이터를 반환한다. + * + * @param key - 캐시 키 + * @param ttlMs - 캐시 유효 시간(ms). 이보다 오래된 문서는 `null` 반환. + * @returns 유효한 캐시 데이터. 없거나 만료됐으면 `null`. + */ +export async function getCached(key: string, ttlMs: number): Promise { + const snap = await firestore.collection(CACHE_COLLECTION).doc(key).get(); + if (!snap.exists) return null; + const doc = snap.data() as CacheDoc; + const age = Date.now() - doc.updatedAt.toMillis(); + if (age > ttlMs) return null; + return doc.data; +} + +/** + * 캐시 문서를 저장한다. `updatedAt`은 서버 타임스탬프로 기록된다. + * + * @param key - 캐시 키 + * @param data - 저장할 데이터 + */ +export async function setCached(key: string, data: T): Promise { + await firestore.collection(CACHE_COLLECTION).doc(key).set({ + data, + updatedAt: FieldValue.serverTimestamp(), + }); +} + +/** + * 분산 락을 획득한다. 트랜잭션으로 기존 락의 TTL을 확인해 갱신 여부를 결정한다. + * + * @param key - 락 키 (보통 캐시 키와 동일) + * @returns 락 획득 성공 시 `true`, 이미 유효한 락이 있으면 `false`. + */ +async function acquireLock(key: string): Promise { + const ref = firestore.collection(LOCK_COLLECTION).doc(key); + try { + await firestore.runTransaction(async (tx) => { + const snap = await tx.get(ref); + if (snap.exists) { + const doc = snap.data() as LockDoc; + const age = Date.now() - doc.acquiredAt.toMillis(); + if (age < LOCK_TTL_MS) throw new Error("LOCKED"); + } + tx.set(ref, { acquiredAt: FieldValue.serverTimestamp() }); + }); + return true; + } catch { + return false; + } +} + +/** + * 락을 해제한다. 실패해도 무시한다(TTL로 자동 만료됨). + */ +async function releaseLock(key: string): Promise { + await firestore.collection(LOCK_COLLECTION).doc(key).delete().catch(() => undefined); +} + +/** + * 락이 걸려있는 동안 주기적으로 캐시를 폴링한다. + * + * 다른 요청이 fetch 중일 때 동일 키로 들어온 요청이 불필요하게 외부 API를 호출하지 않도록 대기시키는 용도. + * + * @param key - 폴링할 캐시 키 + * @param ttlMs - 유효 캐시 판정 기준 + * @param timeoutMs - 최대 대기 시간 (기본 25초) + * @returns 타임아웃 전에 캐시를 얻으면 값, 실패하면 `null`. + */ +async function waitForCache(key: string, ttlMs: number, timeoutMs = 25_000): Promise { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + await new Promise((r) => setTimeout(r, 500)); + const cached = await getCached(key, ttlMs); + if (cached !== null) return cached; + } + return null; +} + +/** + * 캐시 우선 조회, 없으면 `fetcher` 실행 후 결과를 캐싱한다. + * + * 동일 키로 동시에 여러 요청이 들어오면 락으로 직렬화하여 외부 API 중복 호출을 방지한다. + * 락 획득에 실패한 요청은 캐시를 폴링하고, 타임아웃 시엔 개별적으로 fetch (캐싱은 하지 않음). + * + * @param key - 캐시 키 + * @param ttlMs - 캐시 유효 시간(ms) + * @param fetcher - 캐시가 없을 때 실제 데이터를 얻는 함수 + * @returns 캐시 또는 새로 fetch한 데이터 + */ +export async function getOrFetch( + key: string, + ttlMs: number, + fetcher: () => Promise +): Promise { + const cached = await getCached(key, ttlMs); + if (cached !== null) return cached; + + const locked = await acquireLock(key); + if (!locked) { + const waited = await waitForCache(key, ttlMs); + if (waited !== null) return waited; + return fetcher(); + } + + try { + const fresh = await fetcher(); + await setCached(key, fresh); + return fresh; + } finally { + await releaseLock(key); + } +} diff --git a/src/repositories/kboRepository.ts b/src/repositories/kboRepository.ts new file mode 100644 index 0000000..03f1e79 --- /dev/null +++ b/src/repositories/kboRepository.ts @@ -0,0 +1,113 @@ +import { + fetchTeamRankInitial, + fetchTeamRank, + type TeamRankResult, +} from "../kbo/team-rank.js"; +import { + fetchSchedule, + type ScheduleFilters, + type ScheduleResult, +} from "../kbo/schedule.js"; +import { + fetchPlayerStatsInitial, + fetchPlayerStats, + fetchAllPlayerStats, + type PlayerPageConfig, + type PlayerFilters, + type PlayerStatsResult, +} from "../kbo/player/common.js"; +import { encodeKey, getOrFetch } from "./kboCacheRepository.js"; + +const TTL_MS = 60 * 60 * 1000; // 1 hour + +// ── 팀 순위 ── + +/** + * 여러 연도의 KBO 팀 순위를 조회한다. 연도별로 개별 캐싱된다. + * + * @param years - 조회할 연도 배열 + * @returns 각 연도의 순위 결과 배열 (입력 순서 유지) + */ +export async function fetchRankFromKbo( + years: number[] +): Promise { + const results: TeamRankResult[] = []; + for (const year of years) { + const key = encodeKey(["rank", year]); + const result = await getOrFetch(key, TTL_MS, () => + fetchSingleYearRank(year) + ); + results.push(result); + } + return results; +} + +/** + * 단일 연도의 팀 순위를 조회한다. 현재 연도면 초기 페이지 결과를 그대로 사용하고, + * 과거 연도는 postback으로 상태를 변경해 가져온다. + */ +async function fetchSingleYearRank(year: number): Promise { + const { result: initial, state, currentYear } = await fetchTeamRankInitial(); + if (year === currentYear) return initial; + const { result } = await fetchTeamRank(year, state, currentYear); + return result; +} + +// ── 경기 일정 ── + +/** + * 필터 조건에 맞는 KBO 경기 일정을 조회한다. 필터 조합별로 개별 캐싱된다. + * + * @param filters - 연도/월/팀/시리즈 필터 + * @returns 일정 결과 + */ +export async function fetchScheduleFromKbo( + filters: ScheduleFilters +): Promise { + const key = encodeKey([ + "schedule", + filters.year, + filters.month, + filters.team, + filters.series, + ]); + return getOrFetch(key, TTL_MS, () => fetchSchedule(filters)); +} + +// ── 선수 기록 ── + +/** + * KBO 선수 기록을 조회한다. 타입/연도/필터/전체페이지 여부 조합별로 개별 캐싱된다. + * + * @param type - 선수 타입 (hitter/pitcher 등). 캐시 키 구성 용도. + * @param config - KBO 페이지 설정 (URL, SM 키 등) + * @param year - 조회할 시즌 연도 + * @param filters - 팀/시리즈/포지션/상황 등 필터 + * @param allPages - `true`면 페이지네이션을 끝까지 순회, `false`면 첫 페이지만 + * @returns 선수 기록 결과 + */ +export async function fetchPlayerFromKbo( + type: string, + config: PlayerPageConfig, + year: number, + filters: PlayerFilters, + allPages: boolean +): Promise { + const key = encodeKey([ + "player", + type, + year, + filters.team, + filters.series, + filters.pos, + filters.situation, + filters.situationDetail, + allPages ? "all" : "one", + ]); + return getOrFetch(key, TTL_MS, async () => { + const { state } = await fetchPlayerStatsInitial(config); + const fetchFn = allPages ? fetchAllPlayerStats : fetchPlayerStats; + const { result } = await fetchFn(config, year, state, filters); + return result; + }); +} diff --git a/src/repositories/userRepository.ts b/src/repositories/userRepository.ts new file mode 100644 index 0000000..1f3cd4d --- /dev/null +++ b/src/repositories/userRepository.ts @@ -0,0 +1,55 @@ +import { FieldValue } from "firebase-admin/firestore"; +import { firestore } from "../firebase.js"; +import type { User, Provider } from "../types/panit.js"; + +const COLLECTION = "users"; + +export interface RegisterInput { + displayName: string; + email: string; + photoUrl?: string; + provider: Provider; +} + +/** + * 특정 유저 문서를 조회한다. + * + * @param uid - Firebase Auth UID + * @returns 유저 문서. 존재하지 않으면 `null`. + */ +export async function getUser(uid: string): Promise { + const snap = await firestore.collection(COLLECTION).doc(uid).get(); + return snap.exists ? (snap.data() as User) : null; +} + +/** + * 신규 유저 문서를 생성한다. `createdAt`은 서버 타임스탬프로 기록되며, + * 같은 UID가 있으면 전체 덮어쓴다(`merge: false`). + * + * @param uid - Firebase Auth UID + * @param input - 생성에 필요한 사용자 정보 + */ +export async function createUser(uid: string, input: RegisterInput): Promise { + const doc: Record = { + displayName: input.displayName, + email: input.email, + provider: input.provider, + createdAt: FieldValue.serverTimestamp(), + }; + if (input.photoUrl) doc.photoUrl = input.photoUrl; + await firestore.collection(COLLECTION).doc(uid).set(doc, { merge: false }); +} + +/** + * 유저가 없으면 새로 생성하고, 있으면 그대로 둔다. + * + * @param uid - Firebase Auth UID + * @param input - 신규 생성 시 사용할 정보 + * @returns 신규 생성했으면 `true`, 기존 유저라 스킵했으면 `false`. + */ +export async function upsertUser(uid: string, input: RegisterInput): Promise { + const existing = await getUser(uid); + if (existing) return false; + await createUser(uid, input); + return true; +} diff --git a/src/repositories/voteHistoryRepository.ts b/src/repositories/voteHistoryRepository.ts new file mode 100644 index 0000000..1e6dc6e --- /dev/null +++ b/src/repositories/voteHistoryRepository.ts @@ -0,0 +1,67 @@ +import { firestore } from "../firebase.js"; +import type { VoteHistoryDoc } from "../types/panit.js"; +import type { DateString } from "../types/dateString.js"; + +/** + * 특정 유저의 voteHistory 서브컬렉션 레퍼런스를 반환한다. + */ +function col(uid: string): FirebaseFirestore.CollectionReference { + return firestore.collection("users").doc(uid).collection("voteHistory"); +} + +/** + * 특정 날짜의 투표 기록 단일 문서를 조회한다. + * + * @param uid - 조회할 유저 ID + * @param date - 조회할 날짜 (YYYY-MM-DD, 문서 ID로 사용됨) + * @returns 해당 날짜의 투표 기록. 존재하지 않으면 `null`. + */ +export async function getDay(uid: string, date: DateString): Promise { + const snap = await col(uid).doc(date).get(); + return snap.exists ? (snap.data() as VoteHistoryDoc) : null; +} + +/** + * 지정한 날짜 범위(양끝 포함)에 해당하는 투표 기록을 조회한다. + * + * 문서 ID(`__name__`) 기준으로 범위 쿼리하므로 문서 ID가 + * `YYYY-MM-DD` 형식이어야 날짜 순 정렬과 일치한다. + * + * @param uid - 조회할 유저 ID + * @param startDate - 범위 시작 날짜 (포함) + * @param endDate - 범위 종료 날짜 (포함) + * @returns `{ date, doc }` 배열 (문서 ID 오름차순) + */ +export async function getRange( + uid: string, + startDate: DateString, + endDate: DateString +): Promise> { + const snap = await col(uid) + .where("__name__", ">=", startDate) + .where("__name__", "<=", endDate) + .get(); + return snap.docs.map((d) => ({ date: d.id as DateString, doc: d.data() as VoteHistoryDoc })); +} + +/** + * 유저의 전체 투표 기록을 날짜 오름차순으로 조회한다. + * + * @param uid - 조회할 유저 ID + * @returns `{ date, doc }` 배열 (날짜 오름차순) + */ +export async function getAll(uid: string): Promise> { + const snap = await col(uid).orderBy("__name__").get(); + return snap.docs.map((d) => ({ date: d.id as DateString, doc: d.data() as VoteHistoryDoc })); +} + +/** + * 특정 날짜의 투표 기록을 저장한다. 동일 날짜 문서가 있으면 전체를 덮어쓴다. + * + * @param uid - 저장할 유저 ID + * @param date - 저장할 날짜 (YYYY-MM-DD, 문서 ID로 사용됨) + * @param doc - 저장할 투표 기록 + */ +export async function setDay(uid: string, date: DateString, doc: VoteHistoryDoc): Promise { + await col(uid).doc(date).set(doc); +} diff --git a/src/repositories/voteRepository.ts b/src/repositories/voteRepository.ts new file mode 100644 index 0000000..9d92d35 --- /dev/null +++ b/src/repositories/voteRepository.ts @@ -0,0 +1,123 @@ +import { ServerValue } from "firebase-admin/database"; +import { rtdb } from "../firebase.js"; +import type { VoteEntry } from "../types/panit.js"; +import type { DateString } from "../types/dateString.js"; + +/** + * 특정 경기의 해당 유저 투표를 조회한다. + * + * @param gameId - 경기 ID + * @param uid - 유저 ID + * @returns 유저의 투표 정보. 없으면 `null`. + */ +export async function getUserVote(gameId: string, uid: string): Promise { + const snap = await rtdb.ref(`/votes/${gameId}/users/${uid}`).get(); + return snap.exists() ? (snap.val() as VoteEntry) : null; +} + +/** + * 경기의 홈/원정 투표 카운트를 조회한다. 값이 없으면 0으로 채운다. + * + * @param gameId - 경기 ID + */ +export async function getCounts( + gameId: string +): Promise<{ homeCount: number; awayCount: number }> { + const snap = await rtdb.ref(`/votes/${gameId}/counts`).get(); + const val = snap.val() ?? {}; + return { + homeCount: Number(val.homeCount ?? 0), + awayCount: Number(val.awayCount ?? 0), + }; +} + +/** + * 특정 경기에 투표한 모든 유저의 기록을 조회한다. + * + * @param gameId - 경기 ID + * @returns `{ [uid]: VoteEntry }` 맵. 아무도 없으면 빈 객체. + */ +export async function getAllUserVotes( + gameId: string +): Promise> { + const snap = await rtdb.ref(`/votes/${gameId}/users`).get(); + return snap.exists() ? (snap.val() as Record) : {}; +} + +/** + * 새로운 투표를 제출한다. 카운트 증가, 유저별 투표, 날짜별 유저 투표 인덱스를 원자적으로 갱신한다. + * + * @param params.gameId - 경기 ID + * @param params.uid - 투표한 유저 ID + * @param params.date - 경기 날짜 (유저별 날짜 인덱스 경로에 사용) + * @param params.side - 투표 진영 (`home` | `away`) + * @param params.team - 투표한 팀 코드 + */ +export async function submitVote(params: { + gameId: string; + uid: string; + date: DateString; + side: "home" | "away"; + team: string; +}): Promise { + const { gameId, uid, date, side, team } = params; + const counterKey = side === "home" ? "homeCount" : "awayCount"; + const updates: Record = {}; + updates[`/votes/${gameId}/counts/${counterKey}`] = ServerValue.increment(1); + updates[`/votes/${gameId}/users/${uid}`] = { team }; + updates[`/userVotes/${uid}/${date}/${gameId}`] = { team }; + await rtdb.ref().update(updates); +} + +/** + * 기존 투표를 다른 진영/팀으로 변경한다. 이전 카운트를 감소시키고 새 카운트를 증가시킨다. + * + * @param params.gameId - 경기 ID + * @param params.uid - 유저 ID + * @param params.date - 경기 날짜 + * @param params.oldSide - 기존 투표 진영 + * @param params.newSide - 변경할 진영 + * @param params.newTeam - 변경할 팀 코드 + */ +export async function changeVote(params: { + gameId: string; + uid: string; + date: DateString; + oldSide: "home" | "away"; + newSide: "home" | "away"; + newTeam: string; +}): Promise { + const { gameId, uid, date, oldSide, newSide, newTeam } = params; + const updates: Record = {}; + updates[`/votes/${gameId}/counts/${oldSide}Count`] = ServerValue.increment(-1); + updates[`/votes/${gameId}/counts/${newSide}Count`] = ServerValue.increment(1); + updates[`/votes/${gameId}/users/${uid}`] = { team: newTeam }; + updates[`/userVotes/${uid}/${date}/${gameId}`] = { team: newTeam }; + await rtdb.ref().update(updates); +} + +/** + * 특정 유저가 특정 날짜에 한 모든 경기 투표를 조회한다. + * + * @param uid - 유저 ID + * @param date - 날짜 (YYYY-MM-DD) + * @returns `{ [gameId]: VoteEntry }` 맵. 투표가 없으면 빈 객체. + */ +export async function getUserDateVotes( + uid: string, + date: DateString +): Promise> { + const snap = await rtdb.ref(`/userVotes/${uid}/${date}`).get(); + return snap.exists() ? (snap.val() as Record) : {}; +} + +/** + * 특정 경기의 모든 투표 데이터를 삭제한다 (카운트/유저 투표 전체). + * + * 주의: `/userVotes/{uid}/{date}/{gameId}` 인덱스는 이 함수로 정리되지 않는다. + * + * @param gameId - 삭제할 경기 ID + */ +export async function deleteGameVotes(gameId: string): Promise { + await rtdb.ref(`/votes/${gameId}`).remove(); +} diff --git a/src/scheduled/dailyArchive.ts b/src/scheduled/dailyArchive.ts new file mode 100644 index 0000000..d6ab449 --- /dev/null +++ b/src/scheduled/dailyArchive.ts @@ -0,0 +1,54 @@ +import { onSchedule } from "firebase-functions/scheduler"; +import { logger } from "firebase-functions"; +import { rtdb } from "../firebase.js"; +import { setDay } from "../repositories/voteHistoryRepository.js"; +import { invalidateStats } from "../services/statsService.js"; +import type { VoteHistoryDoc } from "../types/panit.js"; +import { daysAgoKst } from "../types/dateString.js"; + +interface RawVote { + team: string; + result?: boolean; +} + +export const dailyArchive = onSchedule( + { schedule: "0 2 * * *", timeZone: "Asia/Seoul", region: "asia-northeast3" }, + async () => { + const date = daysAgoKst(1); + logger.info(`dailyArchive start: ${date}`); + + const snap = await rtdb.ref("/userVotes").get(); + if (!snap.exists()) { + logger.info("no userVotes to archive"); + return; + } + const byUid = snap.val() as Record>>; + + let archived = 0; + for (const uid of Object.keys(byUid)) { + const dayVotes = byUid[uid]?.[date]; + if (!dayVotes) continue; + + const data: VoteHistoryDoc["data"] = []; + let allJudged = true; + for (const [gameId, vote] of Object.entries(dayVotes)) { + if (vote.result === undefined) { + allJudged = false; + break; + } + data.push({ gameId, team: vote.team, result: vote.result }); + } + if (!allJudged) { + logger.warn(`skip uid=${uid}: not all games judged for ${date}`); + continue; + } + + await setDay(uid, date, { data }); + await rtdb.ref(`/userVotes/${uid}/${date}`).remove(); + await invalidateStats(uid).catch(() => undefined); + archived += 1; + } + + logger.info(`dailyArchive done: ${archived} users archived for ${date}`); + } +); diff --git a/src/scheduled/kboRefresh.ts b/src/scheduled/kboRefresh.ts new file mode 100644 index 0000000..5ee8a61 --- /dev/null +++ b/src/scheduled/kboRefresh.ts @@ -0,0 +1,57 @@ +import { onSchedule } from "firebase-functions/scheduler"; +import { logger } from "firebase-functions"; +import { firestore } from "../firebase.js"; +import { + fetchRankFromKbo, + fetchScheduleFromKbo, +} from "../repositories/kboRepository.js"; +import { syncGamesForMonth } from "../services/gameSyncService.js"; + +const CACHE_COLLECTION = "kboCache"; + +async function invalidateByPrefix(prefix: string): Promise { + const snap = await firestore + .collection(CACHE_COLLECTION) + .where("__name__", ">=", prefix) + .where("__name__", "<", prefix + "\uf8ff") + .get(); + const batch = firestore.batch(); + snap.docs.forEach((d) => batch.delete(d.ref)); + if (!snap.empty) await batch.commit(); +} + +export const kboDailyRefresh = onSchedule( + { schedule: "0 2 * * *", timeZone: "Asia/Seoul", region: "asia-northeast3" }, + async () => { + const now = new Date(); + const year = now.getFullYear(); + const month = now.getMonth() + 1; + + logger.info(`KBO refresh start: ${year}-${month}`); + + await invalidateByPrefix("rank__"); + await invalidateByPrefix("schedule__"); + + try { + await fetchRankFromKbo([year]); + await fetchScheduleFromKbo({ year, month }); + + const thisMonthCount = await syncGamesForMonth(year, month); + logger.info(`synced ${thisMonthCount} games for ${year}-${month}`); + + // 월말 3일 이내면 다음 달도 함께 sync + const lastDay = new Date(year, month, 0).getDate(); + if (now.getDate() >= lastDay - 2) { + const next = new Date(year, month, 1); + const ny = next.getFullYear(); + const nm = next.getMonth() + 1; + const nextCount = await syncGamesForMonth(ny, nm); + logger.info(`synced ${nextCount} games for ${ny}-${nm}`); + } + + logger.info("KBO refresh complete"); + } catch (err) { + logger.error("KBO refresh failed", err); + } + } +); diff --git a/src/services/authService.ts b/src/services/authService.ts new file mode 100644 index 0000000..b0abbf4 --- /dev/null +++ b/src/services/authService.ts @@ -0,0 +1,27 @@ +import { HttpError } from "../middleware/errors.js"; +import { upsertUser, type RegisterInput } from "../repositories/userRepository.js"; +import type { Provider } from "../types/panit.js"; + +const VALID_PROVIDERS: readonly Provider[] = ["google", "apple"]; + +export async function register( + uid: string, + body: Partial & { provider?: string } +): Promise<{ created: boolean }> { + if (!body.displayName || typeof body.displayName !== "string") { + throw new HttpError(400, "displayName required"); + } + if (!body.email || typeof body.email !== "string") { + throw new HttpError(400, "email required"); + } + if (!body.provider || !VALID_PROVIDERS.includes(body.provider as Provider)) { + throw new HttpError(400, `provider must be one of: ${VALID_PROVIDERS.join(", ")}`); + } + const created = await upsertUser(uid, { + displayName: body.displayName, + email: body.email, + photoUrl: body.photoUrl, + provider: body.provider as Provider, + }); + return { created }; +} diff --git a/src/services/gameResultService.ts b/src/services/gameResultService.ts new file mode 100644 index 0000000..02329b4 --- /dev/null +++ b/src/services/gameResultService.ts @@ -0,0 +1,55 @@ +import { FieldValue } from "firebase-admin/firestore"; +import { logger } from "firebase-functions"; +import { firestore, rtdb } from "../firebase.js"; +import { HttpError } from "../middleware/errors.js"; +import { getGame } from "../repositories/gameRepository.js"; +import { getAllUserVotes, deleteGameVotes } from "../repositories/voteRepository.js"; +import { invalidateStats } from "./statsService.js"; +import { fromTimestamp } from "../types/dateString.js"; + +export async function processGameEnd(gameId: string): Promise<{ processed: number }> { + const game = await getGame(gameId); + if (!game) throw new HttpError(404, `game not found: ${gameId}`); + if (!game.winningTeamCode) throw new HttpError(400, "winningTeamCode not set"); + if (game.status !== "ended") throw new HttpError(409, `game status must be ended, got ${game.status}`); + + const date = fromTimestamp(game.time); + const votes = await getAllUserVotes(gameId); + const uids = Object.keys(votes); + + const rtdbUpdates: Record = {}; + for (const uid of uids) { + const voted = votes[uid].team; + const result = voted === game.winningTeamCode; + rtdbUpdates[`/userVotes/${uid}/${date}/${gameId}/team`] = voted; + rtdbUpdates[`/userVotes/${uid}/${date}/${gameId}/result`] = result; + } + if (Object.keys(rtdbUpdates).length > 0) { + await rtdb.ref().update(rtdbUpdates); + } + + await deleteGameVotes(gameId); + + await Promise.all(uids.map((uid) => invalidateStats(uid).catch(() => undefined))); + + logger.info(`processGameEnd: ${gameId} processed ${uids.length} votes`); + return { processed: uids.length }; +} + +export async function markGameEnded( + gameId: string, + winningTeamCode: string +): Promise<{ processed: number }> { + if (!gameId || !winningTeamCode) { + throw new HttpError(400, "gameId and winningTeamCode required"); + } + const ref = firestore.collection("games").doc(gameId); + const snap = await ref.get(); + if (!snap.exists) throw new HttpError(404, `game not found: ${gameId}`); + await ref.update({ + status: "ended", + winningTeamCode, + endedAt: FieldValue.serverTimestamp(), + }); + return processGameEnd(gameId); +} diff --git a/src/services/gameSyncService.ts b/src/services/gameSyncService.ts new file mode 100644 index 0000000..2c3be1e --- /dev/null +++ b/src/services/gameSyncService.ts @@ -0,0 +1,75 @@ +import { Timestamp } from "firebase-admin/firestore"; +import { firestore } from "../firebase.js"; +import { fetchScheduleFromKbo } from "../repositories/kboRepository.js"; +import type { ScheduleGame } from "../kbo/schedule.js"; +import type { Game, GameStatus } from "../types/panit.js"; + +const COLLECTION = "games"; + +function toGameStatus(s: ScheduleGame["status"]): GameStatus { + if (s === "completed") return "ended"; + if (s === "cancelled") return "canceled"; + return "waiting"; +} + +/** + * KBO schedule의 `date`("MM.DD")와 `time`("HH:mm")을 KST 기준 Firestore Timestamp로 변환한다. + */ +export function toTime(year: number, date: string, time: string): Timestamp { + const [mm, dd] = date.split(".").map((v) => parseInt(v, 10)); + const [hhRaw, miRaw] = (time || "00:00").split(":"); + const hh = parseInt(hhRaw, 10); + const mi = parseInt(miRaw, 10); + // KST = UTC+9 + const utcMs = Date.UTC(year, mm - 1, dd, hh - 9, mi); + return Timestamp.fromMillis(utcMs); +} + +/** + * ScheduleGame → Firestore Game doc 변환. gameId가 없으면 `null`. + * 완료된 경기의 경우 점수로 승리팀 코드를 계산한다. + */ +export function toGameDoc(year: number, g: ScheduleGame): Game | null { + if (!g.gameId) return null; + const doc: Game = { + time: toTime(year, g.date, g.time), + stadium: g.stadium, + status: toGameStatus(g.status), + homeTeamCode: g.homeTeamCode, + awayTeamCode: g.awayTeamCode, + }; + if ( + g.status === "completed" && + g.homeScore !== null && + g.awayScore !== null && + g.homeScore !== g.awayScore + ) { + doc.winningTeamCode = + g.homeScore > g.awayScore ? g.homeTeamCode : g.awayTeamCode; + } + return doc; +} + +/** + * 특정 연도·월의 KBO 경기 일정을 fetch하여 Firestore `games` 컬렉션에 upsert한다. + * + * - `merge: true`로 기존 문서의 수동 필드(예: 외부에서 채운 `winningTeamCode`)를 보존한다. + * - gameId가 없는 일정 엔트리는 스킵. + * + * @returns upsert한 문서 개수 + */ +export async function syncGamesForMonth(year: number, month: number): Promise { + const result = await fetchScheduleFromKbo({ year, month }); + const batch = firestore.batch(); + let count = 0; + for (const g of result.games) { + const doc = toGameDoc(year, g); + if (!doc) continue; + batch.set(firestore.collection(COLLECTION).doc(g.gameId as string), doc, { + merge: true, + }); + count++; + } + if (count > 0) await batch.commit(); + return count; +} diff --git a/src/services/playerService.ts b/src/services/playerService.ts new file mode 100644 index 0000000..8136b45 --- /dev/null +++ b/src/services/playerService.ts @@ -0,0 +1,43 @@ +import { fetchPlayerFromKbo } from "../repositories/kboRepository.js"; +import { TEAM_CODES } from "../types/kbo.js"; +import type { PlayerFilters, PlayerPageConfig, PlayerStatsResult } from "../types/kbo.js"; +import { HITTER_CONFIG } from "../kbo/player/hitter.js"; +import { PITCHER_CONFIG } from "../kbo/player/pitcher.js"; +import { DEFENSE_CONFIG } from "../kbo/player/defense.js"; +import { RUNNER_CONFIG } from "../kbo/player/runner.js"; + +const PLAYER_CONFIGS: Record = { + hitter: HITTER_CONFIG, + pitcher: PITCHER_CONFIG, + defense: DEFENSE_CONFIG, + runner: RUNNER_CONFIG, +}; + +export function getPlayerConfig(type: string): PlayerPageConfig | undefined { + return PLAYER_CONFIGS[type]; +} + +export function getValidPlayerTypes(): string[] { + return Object.keys(PLAYER_CONFIGS); +} + +export async function getPlayerStats( + type: string, + year: number, + filters: PlayerFilters, + allPages: boolean +): Promise { + const config = PLAYER_CONFIGS[type]; + if (!config) { + throw new Error( + `Invalid type: "${type}". Use: ${Object.keys(PLAYER_CONFIGS).join(", ")}` + ); + } + + const resolvedFilters = { ...filters }; + if (resolvedFilters.team) { + resolvedFilters.team = TEAM_CODES[resolvedFilters.team] ?? resolvedFilters.team; + } + + return fetchPlayerFromKbo(type, config, year, resolvedFilters, allPages); +} diff --git a/src/services/predictionService.ts b/src/services/predictionService.ts new file mode 100644 index 0000000..eeaded7 --- /dev/null +++ b/src/services/predictionService.ts @@ -0,0 +1,106 @@ +import { HttpError } from "../middleware/errors.js"; +import { getGame, listByDate, type GameWithId } from "../repositories/gameRepository.js"; +import { + getUserVote, + submitVote, + changeVote, + getCounts, + getUserDateVotes, +} from "../repositories/voteRepository.js"; +import type { Game, VoteEntry } from "../types/panit.js"; +import { fromTimestamp, parseDateString, type DateString } from "../types/dateString.js"; + +function gameDate(game: Game): DateString { + return fromTimestamp(game.time); +} + +function sideOf(game: Game, teamCode: string): "home" | "away" { + if (teamCode === game.homeTeamCode) return "home"; + if (teamCode === game.awayTeamCode) return "away"; + throw new HttpError(400, `teamCode ${teamCode} not in game ${game.homeTeamCode}/${game.awayTeamCode}`); +} + +async function loadWaitingGame(gameId: string): Promise { + const game = await getGame(gameId); + if (!game) throw new HttpError(404, `game not found: ${gameId}`); + if (game.status !== "waiting") { + throw new HttpError(409, `game status is ${game.status}, voting closed`); + } + return game; +} + +export async function createPrediction( + uid: string, + body: { gameId?: string; selectedTeamCode?: string } +): Promise<{ ok: true }> { + if (!body.gameId || !body.selectedTeamCode) { + throw new HttpError(400, "gameId and selectedTeamCode required"); + } + const game = await loadWaitingGame(body.gameId); + const side = sideOf(game, body.selectedTeamCode); + + const existing = await getUserVote(body.gameId, uid); + if (existing) throw new HttpError(409, "already voted; use PUT to change"); + + await submitVote({ + gameId: body.gameId, + uid, + date: gameDate(game), + side, + team: body.selectedTeamCode, + }); + return { ok: true }; +} + +export async function updatePrediction( + uid: string, + body: { gameId?: string; selectedTeamCode?: string } +): Promise<{ ok: true; changed: boolean }> { + if (!body.gameId || !body.selectedTeamCode) { + throw new HttpError(400, "gameId and selectedTeamCode required"); + } + const game = await loadWaitingGame(body.gameId); + const newSide = sideOf(game, body.selectedTeamCode); + + const existing = await getUserVote(body.gameId, uid); + if (!existing) throw new HttpError(400, "no prior vote; use POST"); + + if (existing.team === body.selectedTeamCode) return { ok: true, changed: false }; + + const oldSide = sideOf(game, existing.team); + await changeVote({ + gameId: body.gameId, + uid, + date: gameDate(game), + oldSide, + newSide, + newTeam: body.selectedTeamCode, + }); + return { ok: true, changed: true }; +} + +export async function getMyVotes( + uid: string, + date: string +): Promise> { + try { + return getUserDateVotes(uid, parseDateString(date)); + } catch (err) { + throw new HttpError(400, (err as Error).message); + } +} + +export async function listGamesByDate(date: string): Promise { + try { + return await listByDate(parseDateString(date)); + } catch (err) { + throw new HttpError(400, (err as Error).message); + } +} + +export async function getSummary( + gameId: string +): Promise<{ homeCount: number; awayCount: number }> { + if (!gameId) throw new HttpError(400, "gameId required"); + return getCounts(gameId); +} diff --git a/src/services/rankService.ts b/src/services/rankService.ts new file mode 100644 index 0000000..cae90a3 --- /dev/null +++ b/src/services/rankService.ts @@ -0,0 +1,9 @@ +import { fetchRankFromKbo } from "../repositories/kboRepository.js"; +import type { TeamRankResult } from "../types/kbo.js"; + +export async function getRank( + years: number[] +): Promise { + const results = await fetchRankFromKbo(years); + return results.length === 1 ? results[0] : results; +} diff --git a/src/services/scheduleService.ts b/src/services/scheduleService.ts new file mode 100644 index 0000000..38c7676 --- /dev/null +++ b/src/services/scheduleService.ts @@ -0,0 +1,20 @@ +import { fetchScheduleFromKbo } from "../repositories/kboRepository.js"; +import { TEAM_CODES, SERIES_CODES } from "../types/kbo.js"; +import type { ScheduleResult } from "../types/kbo.js"; + +export async function getSchedule( + year: number, + month: number, + team?: string, + series?: string +): Promise { + const resolvedTeam = team ? (TEAM_CODES[team] ?? team) : undefined; + const resolvedSeries = series ? (SERIES_CODES[series] ?? series) : undefined; + + return fetchScheduleFromKbo({ + year, + month, + series: resolvedSeries, + team: resolvedTeam, + }); +} diff --git a/src/services/statsService.ts b/src/services/statsService.ts new file mode 100644 index 0000000..2126c5f --- /dev/null +++ b/src/services/statsService.ts @@ -0,0 +1,190 @@ +import { rtdb } from "../firebase.js"; +import { HttpError } from "../middleware/errors.js"; +import { computeLevel } from "../constants/levels.js"; +import { getAll, getDay } from "../repositories/voteHistoryRepository.js"; +import type { StatsResponse, VoteHistoryDoc } from "../types/panit.js"; +import { + parseDateString, + toDateString, + startOfDayKst, + todayKst, + type DateString, +} from "../types/dateString.js"; + +type Period = + | "current" + | { kind: "year"; year: number } + | { kind: "month"; year: number; month: number } + | { kind: "week"; year: number; week: number }; + +function parsePeriod(p: string | undefined): Period { + if (!p || p === "current") return "current"; + const mYear = /^(\d{4})$/.exec(p); + if (mYear) return { kind: "year", year: Number(mYear[1]) }; + const mMonth = /^(\d{4})-(\d{2})$/.exec(p); + if (mMonth) return { kind: "month", year: Number(mMonth[1]), month: Number(mMonth[2]) }; + const mWeek = /^(\d{4})-W(\d{1,2})$/.exec(p); + if (mWeek) return { kind: "week", year: Number(mWeek[1]), week: Number(mWeek[2]) }; + throw new HttpError(400, `invalid period: ${p}`); +} + +function parseYmd(date: DateString): { y: number; m: number; d: number } { + const [y, m, d] = date.split("-").map(Number); + return { y, m, d }; +} + +/** ISO week of a KST calendar date. 달력 계산만 하므로 UTC 연산은 안전. */ +function isoWeek(date: DateString): { year: number; week: number } { + const { y, m, d } = parseYmd(date); + const t = new Date(Date.UTC(y, m - 1, d)); + const day = t.getUTCDay() || 7; + t.setUTCDate(t.getUTCDate() + 4 - day); + const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1)); + const week = Math.ceil((((t.getTime() - yearStart.getTime()) / 86400000) + 1) / 7); + return { year: t.getUTCFullYear(), week }; +} + +function matchesPeriod(dateStr: DateString, period: Period): boolean { + if (period === "current") return true; + const { y, m } = parseYmd(dateStr); + if (period.kind === "year") return y === period.year; + if (period.kind === "month") return y === period.year && m === period.month; + const iw = isoWeek(dateStr); + return iw.year === period.year && iw.week === period.week; +} + +function aggregate(entries: Array<{ date: DateString; doc: VoteHistoryDoc }>): { + total: number; + correct: number; +} { + let total = 0; + let correct = 0; + for (const { doc } of entries) { + for (const v of doc.data) { + total += 1; + if (v.result) correct += 1; + } + } + return { total, correct }; +} + +function rate(correct: number, total: number): number { + return total === 0 ? 0 : correct / total; +} + +function computeStreak(entries: Array<{ date: DateString; doc: VoteHistoryDoc }>): number { + if (entries.length === 0) return 0; + const sorted = [...entries].sort((a, b) => (a.date < b.date ? 1 : -1)); + const todayMs = startOfDayKst(todayKst()).getTime(); + let streak = 0; + for (const { date } of sorted) { + const ms = startOfDayKst(date).getTime(); + const diff = Math.round((todayMs - ms) / 86400000); + if (diff === streak || (streak === 0 && diff <= 1)) { + streak += 1; + } else { + break; + } + } + return streak; +} + +function weeklyResultsOf(entries: Array<{ date: DateString; doc: VoteHistoryDoc }>): Array { + const byDate = new Map(entries.map((e) => [e.date, e.doc] as const)); + const today = todayKst(); + const todayMs = startOfDayKst(today).getTime(); + const { y, m, d } = parseYmd(today); + const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay() || 7; + const mondayMs = todayMs - (dow - 1) * 86400000; + + const results: Array = []; + for (let i = 0; i < 7; i++) { + const key = toDateString(new Date(mondayMs + i * 86400000)); + const doc = byDate.get(key); + if (!doc || doc.data.length === 0) { + results.push(null); + } else { + const anyCorrect = doc.data.some((v) => v.result === true); + const allWrong = doc.data.every((v) => v.result === false); + results.push(anyCorrect ? true : allWrong ? false : null); + } + } + return results; +} + +async function computeStats(uid: string, period: Period): Promise { + const all = await getAll(uid); + const overall = aggregate(all); + + const today = todayKst(); + const { y: nowYear, m: nowMonth } = parseYmd(today); + const iw = isoWeek(today); + + const seasonEntries = all.filter((e) => matchesPeriod(e.date, { kind: "year", year: nowYear })); + const season = aggregate(seasonEntries); + + const monthlyEntries = all.filter((e) => + matchesPeriod(e.date, { kind: "month", year: nowYear, month: nowMonth }) + ); + const monthly = aggregate(monthlyEntries); + + const weeklyEntries = all.filter((e) => + matchesPeriod(e.date, { kind: "week", year: iw.year, week: iw.week }) + ); + const weekly = aggregate(weeklyEntries); + + const periodEntries = period === "current" ? all : all.filter((e) => matchesPeriod(e.date, period)); + const periodAgg = aggregate(periodEntries); + + const streakDays = computeStreak(all); + const weeklyResults = weeklyResultsOf(all); + const { level, progress } = computeLevel(periodAgg.total); + + return { + streakDays, + weeklyResults, + winRates: { + overall: rate(overall.correct, overall.total), + weekly: rate(weekly.correct, weekly.total), + monthly: rate(monthly.correct, monthly.total), + season: rate(season.correct, season.total), + }, + totalPredictions: periodAgg.total, + totalCorrect: periodAgg.correct, + weeklyPredictions: weekly.total, + currentLevel: level, + progress, + updatedAt: Date.now(), + }; +} + +function cachePath(uid: string, key: string): string { + return `/cache/stats/${uid}/${key}`; +} + +export async function getStats(uid: string, periodParam?: string): Promise { + const period = parsePeriod(periodParam); + const key = periodParam && periodParam !== "current" ? periodParam : "current"; + + const cached = await rtdb.ref(cachePath(uid, key)).get(); + if (cached.exists()) return cached.val() as StatsResponse; + + const stats = await computeStats(uid, period); + await rtdb.ref(cachePath(uid, key)).set(stats); + return stats; +} + +export async function invalidateStats(uid: string): Promise { + await rtdb.ref(`/cache/stats/${uid}`).remove(); +} + +export async function getHistory(uid: string, date: string): Promise { + let parsed; + try { + parsed = parseDateString(date); + } catch (err) { + throw new HttpError(400, (err as Error).message); + } + const doc = await getDay(uid, parsed); + return doc ?? { data: [] }; +} diff --git a/src/types/dateString.ts b/src/types/dateString.ts new file mode 100644 index 0000000..799ad8d --- /dev/null +++ b/src/types/dateString.ts @@ -0,0 +1,49 @@ +declare const DateStringBrand: unique symbol; + +/** + * KST(Asia/Seoul) 기준 YYYY-MM-DD 문자열. + * 모든 Firestore/RTDB 키·필드의 날짜 표현은 이 타입으로 통일한다. + */ +export type DateString = string & { [DateStringBrand]: true }; + +const PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; + +export function isDateString(value: unknown): value is DateString { + return typeof value === "string" && PATTERN.test(value); +} + +export function parseDateString(value: string): DateString { + if (!PATTERN.test(value)) { + throw new Error(`invalid date (expected YYYY-MM-DD): ${value}`); + } + return value as DateString; +} + +/** + * 절대 시각(Date 또는 Firestore Timestamp)을 KST 기준 YYYY-MM-DD로 변환. + * 실행 환경의 로컬 타임존과 무관하다. + */ +export function toDateString(date: Date): DateString { + const kstWallClock = new Date(date.getTime() + KST_OFFSET_MS); + return kstWallClock.toISOString().slice(0, 10) as DateString; +} + +export function fromTimestamp(ts: { toDate(): Date }): DateString { + return toDateString(ts.toDate()); +} + +/** 현재 시각의 KST 날짜. */ +export function todayKst(): DateString { + return toDateString(new Date()); +} + +/** n일 전 KST 날짜. */ +export function daysAgoKst(n: number): DateString { + return toDateString(new Date(Date.now() - n * 24 * 60 * 60 * 1000)); +} + +/** YYYY-MM-DD → KST 00:00의 절대 시각(Date, UTC epoch). */ +export function startOfDayKst(date: DateString): Date { + return new Date(Date.parse(`${date}T00:00:00+09:00`)); +} diff --git a/src/types/kbo.ts b/src/types/kbo.ts new file mode 100644 index 0000000..db184d7 --- /dev/null +++ b/src/types/kbo.ts @@ -0,0 +1,25 @@ +// 기존 모듈의 타입을 re-export하여 통합 진입점 제공 + +export type { + TeamRank, + WinLossDraw, + TeamVsRecord, + TeamRankResult, +} from "../kbo/team-rank.js"; + +export type { + GameStatus, + ScheduleGame, + ScheduleFilters, + ScheduleResult, +} from "../kbo/schedule.js"; + +export type { + PlayerPageConfig, + PlayerRecord, + PlayerFilters, + PlayerStatsResult, +} from "../kbo/player/common.js"; + +export { TEAM_CODES } from "../kbo/player/common.js"; +export { SERIES_CODES } from "../kbo/schedule.js"; diff --git a/src/types/panit.ts b/src/types/panit.ts new file mode 100644 index 0000000..da66035 --- /dev/null +++ b/src/types/panit.ts @@ -0,0 +1,47 @@ +import type { Timestamp } from "firebase-admin/firestore"; + +export type Provider = "google" | "apple"; +export type GameStatus = "waiting" | "live" | "ended" | "canceled"; + +export interface User { + displayName: string; + email: string; + photoUrl?: string; + provider: Provider; + createdAt: Timestamp; +} + +export interface Game { + time: Timestamp; + stadium: string; + status: GameStatus; + homeTeamCode: string; + awayTeamCode: string; + winningTeamCode?: string; +} + +export interface VoteEntry { + team: string; + result?: boolean; +} + +export interface VoteHistoryDoc { + data: Array<{ gameId: string; team: string; result: boolean }>; +} + +export interface StatsResponse { + streakDays: number; + weeklyResults: Array; + winRates: { + overall: number; + weekly: number; + monthly: number; + season: number; + }; + totalPredictions: number; + totalCorrect: number; + weeklyPredictions: number; + currentLevel: number; + progress: number; + updatedAt: number; +} diff --git a/tests/repositories/gameRepository.test.ts b/tests/repositories/gameRepository.test.ts new file mode 100644 index 0000000..0a6cc10 --- /dev/null +++ b/tests/repositories/gameRepository.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { Timestamp } from "firebase-admin/firestore"; +import { firestore } from "../../src/firebase.js"; +import { getGame, listByDate } from "../../src/repositories/gameRepository.js"; +import type { DateString } from "../../src/types/dateString.js"; + +describe("gameRepository", () => { + beforeEach(async () => { + await firestore.recursiveDelete(firestore.collection("games")); + }); + + it("존재하지 않는 경기는 null을 반환한다", async () => { + const result = await getGame("nonexistent"); + expect(result).toBeNull(); + }); + + describe("listByDate", () => { + it("지정한 KST 날짜의 경기만 시간순으로 반환한다", async () => { + // 2026-04-12 18:30 KST = 2026-04-12 09:30 UTC + const game1 = { + time: Timestamp.fromDate(new Date("2026-04-12T09:30:00.000Z")), + stadium: "잠실", + status: "waiting" as const, + homeTeamCode: "LG", + awayTeamCode: "HT", + }; + // 2026-04-12 14:00 KST = 2026-04-12 05:00 UTC (먼저) + const game2 = { + time: Timestamp.fromDate(new Date("2026-04-12T05:00:00.000Z")), + stadium: "문학", + status: "waiting" as const, + homeTeamCode: "SK", + awayTeamCode: "WO", + }; + // 2026-04-11 18:30 KST = 범위 밖 + const game3 = { + time: Timestamp.fromDate(new Date("2026-04-11T09:30:00.000Z")), + stadium: "사직", + status: "ended" as const, + homeTeamCode: "LT", + awayTeamCode: "KT", + }; + + await firestore.collection("games").doc("g1").set(game1); + await firestore.collection("games").doc("g2").set(game2); + await firestore.collection("games").doc("g3").set(game3); + + const result = await listByDate("2026-04-12" as DateString); + expect(result.map((g) => g.gameId)).toEqual(["g2", "g1"]); + }); + }); + + it("저장된 경기를 정상적으로 조회한다", async () => { + const gameId = "20260412HTLG0"; + const gameData = { + date: "2026-04-12", + homeTeam: "LG", + awayTeam: "KIA", + status: "scheduled", + }; + await firestore.collection("games").doc(gameId).set(gameData); + + const result = await getGame(gameId); + expect(result).toMatchObject(gameData); + }); +}); \ No newline at end of file diff --git a/tests/repositories/kboRepository.test.ts b/tests/repositories/kboRepository.test.ts new file mode 100644 index 0000000..d377dac --- /dev/null +++ b/tests/repositories/kboRepository.test.ts @@ -0,0 +1,78 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { firestore } from "../../src/firebase.js"; +import { + fetchRankFromKbo, + fetchScheduleFromKbo, +} from "../../src/repositories/kboRepository.js"; + +describe("kboRepository (실제 KBO 사이트 호출)", () => { + beforeEach(async () => { + console.log("[setup] 캐시/락 컬렉션 초기화"); + await firestore.recursiveDelete(firestore.collection("kboCache")); + await firestore.recursiveDelete(firestore.collection("kboLocks")); + }); + + it("팀 순위를 정상적으로 fetch한다", async () => { + console.log("\n[rank] 2025년 팀 순위 fetch 시작"); + const t0 = Date.now(); + const [result] = await fetchRankFromKbo([2025]); + console.log(`[rank] fetch 완료 (${Date.now() - t0}ms)`); + console.log(`[rank] year=${result.year}, teams=${result.teams.length}`); + console.table( + result.teams.map((t) => ({ + rank: t.rank, + team: t.team, + winRate: t.winRate, + games: t.games, + })) + ); + + expect(result.year).toBe(2025); + expect(Array.isArray(result.teams)).toBe(true); + expect(result.teams.length).toBe(10); + expect(result.teams[0]).toHaveProperty("team"); + expect(result.teams[0]).toHaveProperty("rank"); + }, 30000); + + it("경기 일정을 정상적으로 fetch한다", async () => { + console.log("\n[schedule] 2025-04 일정 fetch 시작"); + const t0 = Date.now(); + const result = await fetchScheduleFromKbo({ year: 2025, month: 4 }); + console.log(`[schedule] fetch 완료 (${Date.now() - t0}ms)`); + console.log( + `[schedule] year=${result.year}, month=${result.month}, games=${result.games.length}` + ); + console.log("[schedule] 첫 3개 경기:"); + console.table(result.games.slice(0, 3)); + + expect(result.year).toBe(2025); + expect(result.month).toBe(4); + expect(Array.isArray(result.games)).toBe(true); + expect(result.games.length).toBeGreaterThan(0); + expect(result.games[0]).toHaveProperty("gameId"); + expect(result.games[0]).toHaveProperty("homeTeamCode"); + expect(result.games[0]).toHaveProperty("awayTeamCode"); + }, 30000); + + it("같은 요청을 두 번 하면 두 번째는 캐시에서 온다", async () => { + console.log("\n[cache] 1차 호출 (실제 fetch 예상)"); + const start1 = Date.now(); + await fetchScheduleFromKbo({ year: 2025, month: 5 }); + const firstDuration = Date.now() - start1; + console.log(`[cache] 1차 소요: ${firstDuration}ms`); + + console.log("[cache] 2차 호출 (캐시 hit 예상)"); + const start2 = Date.now(); + await fetchScheduleFromKbo({ year: 2025, month: 5 }); + const secondDuration = Date.now() - start2; + console.log(`[cache] 2차 소요: ${secondDuration}ms`); + console.log( + `[cache] 속도 비교: ${firstDuration}ms → ${secondDuration}ms (${( + (1 - secondDuration / firstDuration) * + 100 + ).toFixed(1)}% 빨라짐)` + ); + + expect(secondDuration).toBeLessThan(firstDuration); + }, 30000); +}); \ No newline at end of file diff --git a/tests/repositories/voteHistoryRepository.test.ts b/tests/repositories/voteHistoryRepository.test.ts new file mode 100644 index 0000000..078406a --- /dev/null +++ b/tests/repositories/voteHistoryRepository.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { firestore } from "../../src/firebase.js"; +import { + getAll, + getDay, + getRange, + setDay, +} from "../../src/repositories/voteHistoryRepository.js"; +import type { DateString } from "../../src/types/dateString.js"; +import type { VoteHistoryDoc } from "../../src/types/panit.js"; + +const uid = "test-uid-1"; + +function makeDoc(gameId: string, team: string, result = true): VoteHistoryDoc { + return { data: [{ gameId, team, result }] }; +} + +describe("voteHistoryRepository (Firestore)", () => { + beforeEach(async () => { + console.log("[setup] users 컬렉션 초기화"); + await firestore.recursiveDelete(firestore.collection("users")); + }); + + describe("setDay + getDay", () => { + it("저장 후 조회 시 동일한 문서를 반환한다", async () => { + const date = "2026-04-12" as DateString; + const doc = makeDoc("20260412HTLG0", "LG"); + + await setDay(uid, date, doc); + const result = await getDay(uid, date); + console.log("[setDay+getDay]", result); + + expect(result).toEqual(doc); + }); + + it("존재하지 않는 날짜는 null을 반환한다", async () => { + const result = await getDay(uid, "2020-01-01" as DateString); + expect(result).toBeNull(); + }); + }); + + describe("getRange", () => { + it("지정한 날짜 범위(양끝 포함)만 반환한다", async () => { + const dates: DateString[] = [ + "2026-04-09" as DateString, + "2026-04-10" as DateString, + "2026-04-11" as DateString, + "2026-04-12" as DateString, + "2026-04-13" as DateString, + ]; + for (const d of dates) { + await setDay(uid, d, makeDoc(`game-${d}`, "LG")); + } + + const result = await getRange( + uid, + "2026-04-10" as DateString, + "2026-04-12" as DateString + ); + const resultDates = result.map((r) => r.date); + console.log("[getRange] 반환된 날짜:", resultDates); + + expect(resultDates).toEqual(["2026-04-10", "2026-04-11", "2026-04-12"]); + expect(result[0].doc.data[0].gameId).toBe("game-2026-04-10"); + }); + }); + + describe("getAll", () => { + it("모든 날짜를 오름차순으로 반환한다", async () => { + const dates: DateString[] = [ + "2026-04-12" as DateString, + "2026-04-10" as DateString, + "2026-04-11" as DateString, + ]; + for (const d of dates) { + await setDay(uid, d, makeDoc(`game-${d}`, "LG")); + } + + const result = await getAll(uid); + const resultDates = result.map((r) => r.date); + console.log("[getAll] 정렬된 날짜:", resultDates); + + expect(resultDates).toEqual(["2026-04-10", "2026-04-11", "2026-04-12"]); + }); + + it("투표 기록이 없으면 빈 배열을 반환한다", async () => { + const result = await getAll("no-history-uid"); + expect(result).toEqual([]); + }); + }); +}); diff --git a/tests/repositories/voteRepository.test.ts b/tests/repositories/voteRepository.test.ts new file mode 100644 index 0000000..c85d831 --- /dev/null +++ b/tests/repositories/voteRepository.test.ts @@ -0,0 +1,148 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { rtdb } from "../../src/firebase.js"; +import { + changeVote, + deleteGameVotes, + getAllUserVotes, + getCounts, + getUserDateVotes, + getUserVote, + submitVote, +} from "../../src/repositories/voteRepository.js"; +import type { DateString } from "../../src/types/dateString.js"; + +const gameId = "20260412HTLG0"; +const gameId2 = "20260412WOSK0"; +const uid = "test-uid-1"; +const uid2 = "test-uid-2"; +const date = "2026-04-12" as DateString; + +describe("voteRepository (RTDB)", () => { + beforeEach(async () => { + console.log("[setup] /votes, /userVotes 초기화"); + await rtdb.ref("/votes").remove(); + await rtdb.ref("/userVotes").remove(); + }); + + describe("submitVote", () => { + it("home 투표 시 homeCount가 1 증가하고 인덱스가 저장된다", async () => { + await submitVote({ gameId, uid, date, side: "home", team: "LG" }); + + const counts = await getCounts(gameId); + const userVote = await getUserVote(gameId, uid); + const dateVotes = await getUserDateVotes(uid, date); + console.log("[home vote] counts:", counts); + console.log("[home vote] userVote:", userVote); + console.log("[home vote] dateVotes:", dateVotes); + + expect(counts).toEqual({ homeCount: 1, awayCount: 0 }); + expect(userVote).toEqual({ team: "LG" }); + expect(dateVotes[gameId]).toEqual({ team: "LG" }); + }); + + it("away 투표 시 awayCount만 증가한다", async () => { + await submitVote({ gameId, uid, date, side: "away", team: "KIA" }); + + const counts = await getCounts(gameId); + console.log("[away vote] counts:", counts); + expect(counts).toEqual({ homeCount: 0, awayCount: 1 }); + }); + }); + + describe("changeVote", () => { + it("home→away 변경 시 카운트가 재분배되고 인덱스가 갱신된다", async () => { + await submitVote({ gameId, uid, date, side: "home", team: "LG" }); + console.log("[change] 초기:", await getCounts(gameId)); + + await changeVote({ + gameId, + uid, + date, + oldSide: "home", + newSide: "away", + newTeam: "KIA", + }); + + const counts = await getCounts(gameId); + const userVote = await getUserVote(gameId, uid); + const dateVotes = await getUserDateVotes(uid, date); + console.log("[change] 변경 후 counts:", counts); + console.log("[change] userVote:", userVote); + + expect(counts).toEqual({ homeCount: 0, awayCount: 1 }); + expect(userVote).toEqual({ team: "KIA" }); + expect(dateVotes[gameId]).toEqual({ team: "KIA" }); + }); + }); + + describe("getUserVote", () => { + it("존재하지 않으면 null을 반환한다", async () => { + const result = await getUserVote(gameId, "nonexistent-uid"); + expect(result).toBeNull(); + }); + }); + + describe("getCounts", () => { + it("counts 노드가 없으면 0으로 채워 반환한다", async () => { + const result = await getCounts("nonexistent-game"); + console.log("[counts-empty]", result); + expect(result).toEqual({ homeCount: 0, awayCount: 0 }); + }); + }); + + describe("getAllUserVotes", () => { + it("여러 유저의 투표를 맵으로 반환한다", async () => { + await submitVote({ gameId, uid, date, side: "home", team: "LG" }); + await submitVote({ gameId, uid: uid2, date, side: "away", team: "KIA" }); + + const all = await getAllUserVotes(gameId); + console.log("[all votes]", all); + expect(Object.keys(all).sort()).toEqual([uid, uid2].sort()); + expect(all[uid]).toEqual({ team: "LG" }); + expect(all[uid2]).toEqual({ team: "KIA" }); + }); + + it("투표가 없으면 빈 객체를 반환한다", async () => { + const result = await getAllUserVotes("nonexistent-game"); + expect(result).toEqual({}); + }); + }); + + describe("getUserDateVotes", () => { + it("특정 날짜의 여러 경기 투표를 맵으로 반환한다", async () => { + await submitVote({ gameId, uid, date, side: "home", team: "LG" }); + await submitVote({ + gameId: gameId2, + uid, + date, + side: "away", + team: "키움", + }); + + const result = await getUserDateVotes(uid, date); + console.log("[date votes]", result); + expect(Object.keys(result).sort()).toEqual([gameId, gameId2].sort()); + expect(result[gameId]).toEqual({ team: "LG" }); + expect(result[gameId2]).toEqual({ team: "키움" }); + }); + }); + + describe("deleteGameVotes", () => { + it("/votes/{gameId}는 삭제되지만 /userVotes 인덱스는 남는다", async () => { + await submitVote({ gameId, uid, date, side: "home", team: "LG" }); + + await deleteGameVotes(gameId); + + const counts = await getCounts(gameId); + const users = await getAllUserVotes(gameId); + const dateVotes = await getUserDateVotes(uid, date); + console.log("[delete] counts:", counts); + console.log("[delete] users:", users); + console.log("[delete] dateVotes (남아있음):", dateVotes); + + expect(counts).toEqual({ homeCount: 0, awayCount: 0 }); + expect(users).toEqual({}); + expect(dateVotes[gameId]).toEqual({ team: "LG" }); + }); + }); +}); diff --git a/tests/services/gameSyncService.test.ts b/tests/services/gameSyncService.test.ts new file mode 100644 index 0000000..389c4f8 --- /dev/null +++ b/tests/services/gameSyncService.test.ts @@ -0,0 +1,117 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { firestore } from "../../src/firebase.js"; +import { + toGameDoc, + toTime, + syncGamesForMonth, +} from "../../src/services/gameSyncService.js"; +import type { ScheduleGame } from "../../src/kbo/schedule.js"; + +function baseGame(overrides: Partial = {}): ScheduleGame { + return { + date: "04.12", + dayOfWeek: "일", + time: "18:30", + awayTeamCode: "HT", + homeTeamCode: "LG", + awayScore: null, + homeScore: null, + status: "scheduled", + stadium: "잠실", + broadcast: "KN-T", + note: "-", + gameId: "20260412HTLG0", + ...overrides, + }; +} + +describe("gameSyncService.toTime", () => { + it("KST 18:30은 UTC 09:30으로 변환된다", () => { + const ts = toTime(2026, "04.12", "18:30"); + const d = ts.toDate(); + expect(d.toISOString()).toBe("2026-04-12T09:30:00.000Z"); + }); + + it("시간이 비어있으면 00:00으로 처리한다", () => { + const ts = toTime(2026, "04.12", ""); + expect(ts.toDate().toISOString()).toBe("2026-04-11T15:00:00.000Z"); + }); +}); + +describe("gameSyncService.toGameDoc", () => { + it("scheduled 경기는 status=waiting, 승리팀 없음", () => { + const doc = toGameDoc(2026, baseGame()); + expect(doc).not.toBeNull(); + expect(doc!.status).toBe("waiting"); + expect(doc!.homeTeamCode).toBe("LG"); + expect(doc!.winningTeamCode).toBeUndefined(); + }); + + it("completed 경기는 status=ended, 점수 기반 winningTeamCode 설정", () => { + const doc = toGameDoc( + 2026, + baseGame({ status: "completed", homeScore: 7, awayScore: 2 }) + ); + expect(doc!.status).toBe("ended"); + expect(doc!.winningTeamCode).toBe("LG"); + }); + + it("cancelled 경기는 status=canceled", () => { + const doc = toGameDoc(2026, baseGame({ status: "cancelled" })); + expect(doc!.status).toBe("canceled"); + }); + + it("무승부는 winningTeamCode가 없다", () => { + const doc = toGameDoc( + 2026, + baseGame({ status: "completed", homeScore: 3, awayScore: 3 }) + ); + expect(doc!.winningTeamCode).toBeUndefined(); + }); + + it("gameId가 null이면 null 반환", () => { + const doc = toGameDoc(2026, baseGame({ gameId: null })); + expect(doc).toBeNull(); + }); +}); + +describe("gameSyncService.syncGamesForMonth (실제 KBO 호출)", () => { + beforeEach(async () => { + await firestore.recursiveDelete(firestore.collection("games")); + await firestore.recursiveDelete(firestore.collection("kboCache")); + await firestore.recursiveDelete(firestore.collection("kboLocks")); + }); + + it("실제 KBO 일정을 fetch하여 games 컬렉션에 upsert한다", async () => { + console.log("[sync] 2025-04 경기 sync 시작"); + const t0 = Date.now(); + const count = await syncGamesForMonth(2025, 4); + console.log(`[sync] ${count}경기 저장 완료 (${Date.now() - t0}ms)`); + + expect(count).toBeGreaterThan(0); + + const snap = await firestore.collection("games").get(); + // 더블헤더 등으로 같은 gameId가 반복되면 문서 수가 count보다 작을 수 있다 + expect(snap.size).toBeGreaterThan(0); + expect(snap.size).toBeLessThanOrEqual(count); + + const first = snap.docs[0].data(); + console.log("[sync] 예시 문서:", { id: snap.docs[0].id, ...first }); + expect(first).toHaveProperty("homeTeamCode"); + expect(first).toHaveProperty("awayTeamCode"); + expect(first).toHaveProperty("status"); + expect(first).toHaveProperty("time"); + }, 30000); + + it("동일 월을 두 번 sync해도 중복 없이 upsert된다", async () => { + const first = await syncGamesForMonth(2025, 4); + const snapAfterFirst = await firestore.collection("games").get(); + console.log(`[idempotent] 1차: ${first}건`); + + const second = await syncGamesForMonth(2025, 4); + const snapAfterSecond = await firestore.collection("games").get(); + console.log(`[idempotent] 2차: ${second}건`); + + expect(snapAfterSecond.size).toBe(snapAfterFirst.size); + }, 30000); +}); diff --git a/tests/setup.ts b/tests/setup.ts new file mode 100644 index 0000000..375b8ad --- /dev/null +++ b/tests/setup.ts @@ -0,0 +1,8 @@ +process.env.GCLOUD_PROJECT ??= "demo-test"; +process.env.FIREBASE_DATABASE_EMULATOR_HOST ??= "127.0.0.1:9000"; +process.env.FIRESTORE_EMULATOR_HOST ??= "127.0.0.1:8080"; +process.env.FIREBASE_AUTH_EMULATOR_HOST ??= "127.0.0.1:9099"; +process.env.FIREBASE_CONFIG ??= JSON.stringify({ + projectId: process.env.GCLOUD_PROJECT, + databaseURL: `http://${process.env.FIREBASE_DATABASE_EMULATOR_HOST}/?ns=${process.env.GCLOUD_PROJECT}`, +}); \ No newline at end of file diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..9445902 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["tests/**/*.test.ts"], + setupFiles: ["tests/setup.ts"], + testTimeout: 15000, + hookTimeout: 15000, + pool: "forks", + fileParallelism: false, + }, +}); \ No newline at end of file