diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000..9e29cf1 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,139 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json + +# CodeRabbit Configuration for YNAB MCP Server +# Focus: Security and Safety + +language: "en-US" +tone_instructions: "Be thorough about security issues. Flag any potential vulnerabilities clearly." +early_access: false + +reviews: + profile: "assertive" # Strict reviews for security focus + request_changes_workflow: true + high_level_summary: true + high_level_summary_placeholder: "@coderabbitai summary" + review_status: true + commit_status: true + fail_commit_status: true # Fail on security issues + collapse_walkthrough: false + sequence_diagrams: true + + # Path-specific security instructions + path_instructions: + - path: "src/**/*.ts" + instructions: | + Security Review Checklist: + 1. INPUT VALIDATION: Ensure all user inputs are validated with Zod schemas before use + 2. API TOKENS: Never log, expose, or hardcode YNAB_ACCESS_TOKEN or any credentials + 3. ERROR MESSAGES: Verify error messages don't leak sensitive information (tokens, internal paths) + 4. RATE LIMITING: Confirm API calls go through rateLimiter.acquire() + 5. READ-ONLY MODE: Write operations must call assertWriteAllowed() before execution + 6. AUDIT LOGGING: All write operations must be logged via auditLog + 7. SQL/COMMAND INJECTION: Check for any string interpolation that could allow injection + 8. TYPE SAFETY: Ensure proper TypeScript types, avoid 'any' type + + - path: "src/services/ynab-client.ts" + instructions: | + CRITICAL FILE - YNAB API Client + - Verify all write operations check assertWriteAllowed() + - Confirm rateLimiter.acquire() is called before every API request + - Ensure tokens are never logged or included in error messages + - Check that audit logging captures all mutations + + - path: "src/tools/**/*.ts" + instructions: | + Tool Handler Security: + - Validate ALL inputs with Zod before processing + - Sanitize any user-provided strings before including in responses + - Don't expose internal IDs or paths unnecessarily + - Ensure budget_id resolution uses client.resolveBudgetId() + + - path: "src/config/**/*.ts" + instructions: | + Configuration Security: + - Environment variables must be validated + - Sensitive values (tokens) must never have defaults + - READ_ONLY should default to true for safety + + - path: "tests/**/*.ts" + instructions: | + Test Security: + - Never use real API tokens in tests + - Mock all external API calls + - Test error handling paths for information leakage + + # Auto review settings + auto_review: + enabled: true + auto_incremental_review: true + ignore_title_keywords: + - "WIP" + - "DO NOT MERGE" + drafts: false + + # Pre-merge security checks + pre_merge_checks: + title: + mode: "warning" + description: + mode: "warning" + custom_checks: + - mode: "error" + name: "No Hardcoded Secrets" + instructions: | + FAIL if any of these are found: + - Hardcoded API tokens or keys + - Hardcoded passwords + - YNAB access tokens in code (not from environment) + - Base64 encoded credentials + + - mode: "error" + name: "Input Validation" + instructions: | + FAIL if tool handlers don't validate inputs with Zod schemas + before processing user-provided data. + + - mode: "error" + name: "Rate Limit Compliance" + instructions: | + FAIL if any new API calls are added without calling + rateLimiter.acquire() first. + + - mode: "warning" + name: "Error Message Safety" + instructions: | + WARN if error messages might expose: + - Internal file paths + - API tokens or credentials + - Stack traces with sensitive context + - Database/API internal IDs + + # Enable security-focused tools + tools: + shellcheck: + enabled: true + ruff: + enabled: true + markdownlint: + enabled: true + github-checks: + enabled: true + timeout_ms: 90000 + biome: + enabled: true + ast-grep: + essential_rules: true + +chat: + auto_reply: true + +knowledge_base: + opt_out: false + web_search: + enabled: true + learnings: + scope: "local" + issues: + scope: "local" + pull_requests: + scope: "local" diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..334fd98 --- /dev/null +++ b/.env.example @@ -0,0 +1,24 @@ +# YNAB MCP Server Configuration + +# Required: Your YNAB Personal Access Token +# Get one from: https://app.ynab.com/settings/developer +YNAB_ACCESS_TOKEN=your_personal_access_token_here + +# Optional: Default budget ID (UUID) +# If not set, uses "last-used" (your most recently accessed budget) +# YNAB_BUDGET_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + +# Optional: Log level (debug, info, warn, error) +LOG_LEVEL=info + +# Optional: Cache TTL in milliseconds (default: 300000 = 5 minutes) +CACHE_TTL_MS=300000 + +# Optional: Rate limit per hour (default: 180, max: 200) +# Using 180 as default provides a 10% safety margin +RATE_LIMIT_PER_HOUR=180 + +# Optional: Read-only mode (default: true) +# When true, all write operations (create, update, delete) are blocked +# Set to false to enable write operations +YNAB_READ_ONLY=true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..97ac769 --- /dev/null +++ b/.gitignore @@ -0,0 +1,59 @@ +# Dependencies +node_modules/ + +# Build output +dist/ +*.tsbuildinfo + +# Environment files +.env +.env.local +.env*.local + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*.sublime-* + +# OS +.DS_Store +Thumbs.db +*.orig + +# Test coverage +coverage/ +.nyc_output/ + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Cache +.cache/ +.eslintcache +.npm/ + +# Runtime +*.pid +*.seed + +# Lock files (optional, uncomment if not committing) +# package-lock.json + +# Claude related files +CLAUDE.md +SCRATCHPAD.md +CLAUDE_CODE_PROMPT.md +REMEDIATION_PLAN.md +PLAN.md +.claude/ +.claude* + +# Misc +*.bak +*.tmp +*.temp diff --git a/README.md b/README.md index 08a309c..e8c6002 100644 --- a/README.md +++ b/README.md @@ -1 +1,272 @@ -# ynab-mcp \ No newline at end of file +# YNAB MCP Server + +A Model Context Protocol (MCP) server providing comprehensive YNAB (You Need A Budget) API coverage for integration with Claude and other MCP-compatible AI assistants. + +## Features + +- **55 MCP Tools**: Complete coverage of YNAB API endpoints plus advanced analytics +- **Read-Only Mode**: Safe by default (YNAB_READ_ONLY=true), write operations require explicit opt-in +- **Smart Rate Limiting**: Token bucket algorithm with 180 req/hour budget (10% safety margin from YNAB's 200 limit) +- **Intelligent Caching**: Reduces API calls for infrequently changing data +- **Advanced Analytics**: + - Recurring transaction/subscription detection + - Spending trend analysis + - Budget health assessment + - Savings opportunity identification + +## Quick Start + +### Prerequisites + +- Node.js 20 or later +- A YNAB account with API access +- A YNAB Personal Access Token ([get one here](https://app.ynab.com/settings/developer)) + +### Installation + +```bash +# Clone the repository +git clone https://github.com/auzroz/ynab-mcp.git +cd ynab-mcp + +# Install dependencies +npm install + +# Copy environment template +cp .env.example .env + +# Edit .env and add your YNAB_ACCESS_TOKEN +``` + +### Configuration + +Edit `.env` with your settings: + +```env +# Required: Your YNAB Personal Access Token +YNAB_ACCESS_TOKEN=your_personal_access_token + +# Optional: Default budget UUID (uses "last-used" if not set) +YNAB_BUDGET_ID=optional_default_budget_uuid + +# Optional: Set to false to enable write operations (default: true) +YNAB_READ_ONLY=true +``` + +### Build & Run + +```bash +# Build TypeScript +npm run build + +# Run the server +npm start +``` + +### Claude Desktop Integration + +Add to your Claude Desktop configuration (`~/.config/claude/claude_desktop_config.json` on Linux/Mac or `%APPDATA%\Claude\claude_desktop_config.json` on Windows): + +```json +{ + "mcpServers": { + "ynab": { + "command": "node", + "args": ["/path/to/ynab-mcp/dist/index.js"], + "env": { + "YNAB_ACCESS_TOKEN": "your_token_here" + } + } + } +} +``` + +## Available Tools (55 Total) + +### User Tools (1) + +- `ynab_get_user` - Get authenticated user information + +### Budget Tools (3) + +- `ynab_list_budgets` - List all accessible budgets +- `ynab_get_budget` - Get detailed budget information +- `ynab_get_budget_settings` - Get budget settings (currency format, etc.) + +### Account Tools (3) + +- `ynab_list_accounts` - List all accounts with balances +- `ynab_get_account` - Get specific account details +- `ynab_create_account` - Create a new account *(requires YNAB_READ_ONLY=false)* + +### Category Tools (4) + +- `ynab_list_categories` - List all category groups and categories +- `ynab_get_category` - Get category details +- `ynab_get_month_category` - Get category budget for specific month +- `ynab_update_category` - Update category budgeted amount *(requires YNAB_READ_ONLY=false)* + +### Payee Tools (5) + +- `ynab_list_payees` - List all payees (merchants/vendors) +- `ynab_get_payee` - Get specific payee details +- `ynab_list_payee_locations` - List all payee locations for mapping +- `ynab_get_payee_location` - Get specific payee location +- `ynab_list_payee_locations_by_payee` - List locations for a specific payee + +### Month Tools (2) + +- `ynab_list_months` - List all budget months +- `ynab_get_month` - Get detailed month summary with categories + +### Transaction Tools (10) + +- `ynab_list_transactions` - List transactions with filters (date, category, payee) +- `ynab_get_transaction` - Get transaction details +- `ynab_create_transaction` - Create a new transaction *(requires YNAB_READ_ONLY=false)* +- `ynab_create_transactions` - Bulk create transactions (max 100) *(requires YNAB_READ_ONLY=false)* +- `ynab_update_transaction` - Update a transaction *(requires YNAB_READ_ONLY=false)* +- `ynab_delete_transaction` - Delete a transaction *(requires YNAB_READ_ONLY=false)* +- `ynab_list_account_transactions` - List transactions for a specific account +- `ynab_list_category_transactions` - List transactions for a specific category +- `ynab_list_payee_transactions` - List transactions for a specific payee +- `ynab_import_transactions` - Trigger import from linked bank accounts *(requires YNAB_READ_ONLY=false)* + +### Scheduled Transaction Tools (2) + +- `ynab_list_scheduled_transactions` - List scheduled/recurring transactions +- `ynab_get_scheduled_transaction` - Get scheduled transaction details + +### Analytics Tools (22) + +- `ynab_detect_recurring` - Find subscription patterns and recurring payments +- `ynab_spending_analysis` - Analyze spending trends by category +- `ynab_budget_health` - Assess overall budget health with score and alerts +- `ynab_savings_opportunities` - Identify potential areas to save money +- `ynab_budget_vs_actuals` - Compare budgeted vs actual spending +- `ynab_quick_summary` - At-a-glance budget status overview +- `ynab_income_expense` - Income vs expense breakdown and trends +- `ynab_net_worth` - Calculate total net worth from all accounts +- `ynab_goal_progress` - Track goal funding progress with projections +- `ynab_spending_by_payee` - Analyze spending by merchant/payee +- `ynab_unused_categories` - Find inactive or unused categories +- `ynab_monthly_comparison` - Month-over-month spending comparison +- `ynab_spending_trends` - Multi-month trend analysis with projections +- `ynab_cash_flow_forecast` - Project future cash flow based on scheduled transactions +- `ynab_reconciliation_helper` - Help with account reconciliation +- `ynab_budget_suggestions` - Get budget suggestions based on history +- `ynab_overspending_alerts` - Quick check for overspent categories +- `ynab_transaction_search` - Powerful multi-filter transaction search +- `ynab_spending_pace` - Track daily spending rate vs target +- `ynab_category_balances` - Quick category balance lookup +- `ynab_credit_card_status` - Credit card balances vs payment categories +- `ynab_age_of_money` - Age of money metric with explanation + +### System Tools (3) + +- `ynab_rate_limit_status` - Check API rate limit status +- `ynab_audit_log` - View write operation audit log +- `ynab_health_check` - Test API connectivity + +## Example Conversations + +**Checking account balances:** +> "What's my current net worth?" +> +> Claude uses `ynab_list_accounts` and calculates total assets minus liabilities. + +**Understanding spending:** +> "How much did I spend on dining out this month?" +> +> Claude uses `ynab_list_category_transactions` filtered to the dining category. + +**Finding subscriptions:** +> "What subscriptions do I have?" +> +> Claude uses `ynab_detect_recurring` to identify recurring payments. + +**Budget health check:** +> "Is my budget in good shape?" +> +> Claude uses `ynab_budget_health` to analyze overspending, underfunded goals, and provide a health score. + +**Finding savings:** +> "Where can I cut back on spending?" +> +> Claude uses `ynab_savings_opportunities` to identify discretionary spending and potential cuts. + +## Development + +```bash +# Run with hot reload +npm run dev + +# Run tests +npm test + +# Run tests in watch mode +npm run test:watch + +# Lint code +npm run lint + +# Fix lint issues +npm run lint:fix + +# Type check only +npm run typecheck +``` + +### Testing with MCP Inspector + +```bash +npx @modelcontextprotocol/inspector node dist/index.js +``` + +## Architecture + +```text +src/ +├── index.ts # Entry point (stdio server) +├── server.ts # Tool registration +├── config/ # Environment configuration +├── services/ # Core services +│ ├── ynab-client.ts # YNAB API wrapper with rate limiting +│ ├── rate-limiter.ts # Token bucket rate limiter +│ └── cache.ts # In-memory TTL cache +├── tools/ # MCP tool implementations +│ ├── user/ +│ ├── budgets/ +│ ├── accounts/ +│ ├── categories/ +│ ├── payees/ +│ ├── months/ +│ ├── transactions/ +│ ├── scheduled-transactions/ +│ └── analytics/ +└── utils/ # Helpers (currency, dates, errors) +``` + +## Security + +- **Read-Only by Default**: Write operations are disabled unless `YNAB_READ_ONLY=false` +- **Token Security**: Never commit your `YNAB_ACCESS_TOKEN`; store only in environment variables +- **Input Validation**: All tool parameters are validated with Zod schemas +- **Rate Limiting**: Built-in protection against API quota exhaustion + +## Contributing + +1. Fork the repository +2. Create a feature branch +3. Make your changes +4. Run tests and linting: `npm test && npm run lint` +5. Submit a pull request + +## License + +MIT + +## Acknowledgments + +- [YNAB](https://www.ynab.com/) for their excellent budgeting platform and API +- [Anthropic](https://www.anthropic.com/) for the Model Context Protocol diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..4810368 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,50 @@ +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import prettier from 'eslint-config-prettier'; +import { fileURLToPath } from 'url'; +import path from 'path'; + +// Fallback for import.meta.dirname on older Node 20.x versions +const __dirname = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url)); + +export default tseslint.config( + eslint.configs.recommended, + ...tseslint.configs.recommended, + prettier, + { + languageOptions: { + parserOptions: { + project: true, + tsconfigRootDir: __dirname, + }, + }, + rules: { + // Allow explicit any in specific cases (e.g., error handling) + '@typescript-eslint/no-explicit-any': 'warn', + + // Enforce consistent type imports + '@typescript-eslint/consistent-type-imports': [ + 'error', + { prefer: 'type-imports', disallowTypeAnnotations: false }, + ], + + // Allow unused vars prefixed with _ + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, + ], + + // No floating promises + '@typescript-eslint/no-floating-promises': 'off', + + // Require await for async functions + '@typescript-eslint/require-await': 'off', + + // Allow deprecated APIs (we know what we're using) + '@typescript-eslint/no-deprecated': 'off', + }, + }, + { + ignores: ['dist/**', 'node_modules/**', 'coverage/**', '*.config.*'], + } +); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..698e4fc --- /dev/null +++ b/package-lock.json @@ -0,0 +1,5259 @@ +{ + "name": "ynab-mcp-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ynab-mcp-server", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.25.3", + "decimal.js": "^10.4.3", + "ynab": "^1.35.0", + "zod": "^3.23.8" + }, + "bin": { + "ynab-mcp-server": "dist/index.js" + }, + "devDependencies": { + "@eslint/js": "^9.39.2", + "@types/node": "^20.11.0", + "@vitest/coverage-v8": "^1.2.0", + "eslint": "^9.39.2", + "eslint-config-prettier": "^9.1.0", + "prettier": "^3.2.0", + "tsx": "^4.7.0", + "typescript": "^5.3.0", + "typescript-eslint": "^8.53.1", + "vitest": "^1.2.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.6.tgz", + "integrity": "sha512-TeR9zWR18BvbfPmGbLampPMW+uW1NZnJlRuuHso8i87QZNq2JRF9i6RgxRqtEq+wQGsS19NNTWr2duhnE49mfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.6.tgz", + "integrity": "sha512-0ZrskXVEHSWIqZM/sQZ4EV3jZJXRkio/WCxaqKZP1g//CEWEPSfeZFcms4XeKBCHU0ZKnIkdJeU/kF+eRp5lBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.3.tgz", + "integrity": "sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.2.tgz", + "integrity": "sha512-q1mjIoW1VX4IvSocvM/vbTiveKC4k9eLrajNEuSsmjymSDEbpGddtpfOoN7YGAqBK3NG+uqo8ia4PDTt8buCYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.9", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz", + "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.25.3", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.3.tgz", + "integrity": "sha512-vsAMBMERybvYgKbg/l4L1rhS7VXV1c0CtyJg72vwxONVX0l4ZfKVAnZEWTQixJGTzKnELjQ59e4NbdFDALRiAQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "jose": "^6.1.1", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.56.0.tgz", + "integrity": "sha512-LNKIPA5k8PF1+jAFomGe3qN3bbIgJe/IlpDBwuVjrDKrJhVWywgnJvflMt/zkbVNLFtF1+94SljYQS6e99klnw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.56.0.tgz", + "integrity": "sha512-lfbVUbelYqXlYiU/HApNMJzT1E87UPGvzveGg2h0ktUNlOCxKlWuJ9jtfvs1sKHdwU4fzY7Pl8sAl49/XaEk6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.56.0.tgz", + "integrity": "sha512-EgxD1ocWfhoD6xSOeEEwyE7tDvwTgZc8Bss7wCWe+uc7wO8G34HHCUH+Q6cHqJubxIAnQzAsyUsClt0yFLu06w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.56.0.tgz", + "integrity": "sha512-1vXe1vcMOssb/hOF8iv52A7feWW2xnu+c8BV4t1F//m9QVLTfNVpEdja5ia762j/UEJe2Z1jAmEqZAK42tVW3g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.56.0.tgz", + "integrity": "sha512-bof7fbIlvqsyv/DtaXSck4VYQ9lPtoWNFCB/JY4snlFuJREXfZnm+Ej6yaCHfQvofJDXLDMTVxWscVSuQvVWUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.56.0.tgz", + "integrity": "sha512-KNa6lYHloW+7lTEkYGa37fpvPq+NKG/EHKM8+G/g9WDU7ls4sMqbVRV78J6LdNuVaeeK5WB9/9VAFbKxcbXKYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.56.0.tgz", + "integrity": "sha512-E8jKK87uOvLrrLN28jnAAAChNq5LeCd2mGgZF+fGF5D507WlG/Noct3lP/QzQ6MrqJ5BCKNwI9ipADB6jyiq2A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.56.0.tgz", + "integrity": "sha512-jQosa5FMYF5Z6prEpTCCmzCXz6eKr/tCBssSmQGEeozA9tkRUty/5Vx06ibaOP9RCrW1Pvb8yp3gvZhHwTDsJw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.56.0.tgz", + "integrity": "sha512-uQVoKkrC1KGEV6udrdVahASIsaF8h7iLG0U0W+Xn14ucFwi6uS539PsAr24IEF9/FoDtzMeeJXJIBo5RkbNWvQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.56.0.tgz", + "integrity": "sha512-vLZ1yJKLxhQLFKTs42RwTwa6zkGln+bnXc8ueFGMYmBTLfNu58sl5/eXyxRa2RarTkJbXl8TKPgfS6V5ijNqEA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.56.0.tgz", + "integrity": "sha512-FWfHOCub564kSE3xJQLLIC/hbKqHSVxy8vY75/YHHzWvbJL7aYJkdgwD/xGfUlL5UV2SB7otapLrcCj2xnF1dg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.56.0.tgz", + "integrity": "sha512-z1EkujxIh7nbrKL1lmIpqFTc/sr0u8Uk0zK/qIEFldbt6EDKWFk/pxFq3gYj4Bjn3aa9eEhYRlL3H8ZbPT1xvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.56.0.tgz", + "integrity": "sha512-iNFTluqgdoQC7AIE8Q34R3AuPrJGJirj5wMUErxj22deOcY7XwZRaqYmB6ZKFHoVGqRcRd0mqO+845jAibKCkw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.56.0.tgz", + "integrity": "sha512-MtMeFVlD2LIKjp2sE2xM2slq3Zxf9zwVuw0jemsxvh1QOpHSsSzfNOTH9uYW9i1MXFxUSMmLpeVeUzoNOKBaWg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.56.0.tgz", + "integrity": "sha512-in+v6wiHdzzVhYKXIk5U74dEZHdKN9KH0Q4ANHOTvyXPG41bajYRsy7a8TPKbYPl34hU7PP7hMVHRvv/5aCSew==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.56.0.tgz", + "integrity": "sha512-yni2raKHB8m9NQpI9fPVwN754mn6dHQSbDTwxdr9SE0ks38DTjLMMBjrwvB5+mXrX+C0npX0CVeCUcvvvD8CNQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.56.0.tgz", + "integrity": "sha512-zhLLJx9nQPu7wezbxt2ut+CI4YlXi68ndEve16tPc/iwoylWS9B3FxpLS2PkmfYgDQtosah07Mj9E0khc3Y+vQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.56.0.tgz", + "integrity": "sha512-MVC6UDp16ZSH7x4rtuJPAEoE1RwS8N4oK9DLHy3FTEdFoUTCFVzMfJl/BVJ330C+hx8FfprA5Wqx4FhZXkj2Kw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.56.0.tgz", + "integrity": "sha512-ZhGH1eA4Qv0lxaV00azCIS1ChedK0V32952Md3FtnxSqZTBTd6tgil4nZT5cU8B+SIw3PFYkvyR4FKo2oyZIHA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.56.0.tgz", + "integrity": "sha512-O16XcmyDeFI9879pEcmtWvD/2nyxR9mF7Gs44lf1vGGx8Vg2DRNx11aVXBEqOQhWb92WN4z7fW/q4+2NYzCbBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.56.0.tgz", + "integrity": "sha512-LhN/Reh+7F3RCgQIRbgw8ZMwUwyqJM+8pXNT6IIJAqm2IdKkzpCh/V9EdgOMBKuebIrzswqy4ATlrDgiOwbRcQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.56.0.tgz", + "integrity": "sha512-kbFsOObXp3LBULg1d3JIUQMa9Kv4UitDmpS+k0tinPBz3watcUiV2/LUDMMucA6pZO3WGE27P7DsfaN54l9ing==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.56.0.tgz", + "integrity": "sha512-vSSgny54D6P4vf2izbtFm/TcWYedw7f8eBrOiGGecyHyQB9q4Kqentjaj8hToe+995nob/Wv48pDqL5a62EWtg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.56.0.tgz", + "integrity": "sha512-FeCnkPCTHQJFbiGG49KjV5YGW/8b9rrXAM2Mz2kiIoktq2qsJxRD5giEMEOD2lPdgs72upzefaUvS+nc8E3UzQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.56.0.tgz", + "integrity": "sha512-H8AE9Ur/t0+1VXujj90w0HrSOuv0Nq9r1vSZF2t5km20NTfosQsGGUXDaKdQZzwuLts7IyL1fYT4hM95TI9c4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.30", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.30.tgz", + "integrity": "sha512-WJtwWJu7UdlvzEAUm484QNg5eAoq5QR08KDNx7g45Usrs2NtOPiX8ugDqmKdXkyL03rBqU5dYNYVQetEpBHq2g==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.53.1.tgz", + "integrity": "sha512-WYC4FB5Ra0xidsmlPb+1SsnaSKPmS3gsjIARwbEkHkoWloQmuzcfypljaJcR78uyLA1h8sHdWWPHSLDI+MtNog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.53.1", + "@typescript-eslint/types": "^8.53.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service/node_modules/@typescript-eslint/types": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.53.1.tgz", + "integrity": "sha512-jr/swrr2aRmUAUjW5/zQHbMaui//vQlsZcJKijZf3M26bnmLj8LyZUpj8/Rd6uzaek06OWsqdofN/Thenm5O8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.53.1.tgz", + "integrity": "sha512-qfvLXS6F6b1y43pnf0pPbXJ+YoXIC7HKg0UGZ27uMIemKMKA6XH2DTxsEDdpdN29D+vHV07x/pnlPNVLhdhWiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@vitest/coverage-v8": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-1.6.1.tgz", + "integrity": "sha512-6YeRZwuO4oTGKxD3bijok756oktHSIm3eczVVzNe3scqzuhLwltIF3S9ZL/vwOVIpURmU6SnZhziXXAfw8/Qlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.2.1", + "@bcoe/v8-coverage": "^0.2.3", + "debug": "^4.3.4", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.4", + "istanbul-reports": "^3.1.6", + "magic-string": "^0.30.5", + "magicast": "^0.3.3", + "picocolors": "^1.0.0", + "std-env": "^3.5.0", + "strip-literal": "^2.0.0", + "test-exclude": "^6.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "vitest": "1.6.1" + } + }, + "node_modules/@vitest/expect": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz", + "integrity": "sha512-jXL+9+ZNIJKruofqXuuTClf44eSpcHlgj3CiuNihUF3Ioujtmc0zIa3UJOW5RjDK1YLBJZnWBlPuqhYycLioog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "1.6.1", + "@vitest/utils": "1.6.1", + "chai": "^4.3.10" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-1.6.1.tgz", + "integrity": "sha512-3nSnYXkVkf3mXFfE7vVyPmi3Sazhb/2cfZGGs0JRzFsPFvAMBEcrweV1V1GsrstdXeKCTXlJbvnQwGWgEIHmOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "1.6.1", + "p-limit": "^5.0.0", + "pathe": "^1.1.1" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner/node_modules/p-limit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-5.0.0.tgz", + "integrity": "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@vitest/runner/node_modules/yocto-queue": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz", + "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@vitest/snapshot": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-1.6.1.tgz", + "integrity": "sha512-WvidQuWAzU2p95u8GAKlRMqMyN1yOJkGHnx3M1PL9Raf7AQ1kwLKg04ADlCa3+OXUZE7BceOhVZiuWAbzCKcUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.5", + "pathe": "^1.1.1", + "pretty-format": "^29.7.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-1.6.1.tgz", + "integrity": "sha512-MGcMmpGkZebsMZhbQKkAf9CX5zGvjkBTqf8Zx3ApYWXr3wG+QvEu2eXWfnIIWYSJExIp4V9FCKDEeygzkYrXMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^2.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-1.6.1.tgz", + "integrity": "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "diff-sequences": "^29.6.3", + "estree-walker": "^3.0.3", + "loupe": "^2.3.7", + "pretty-format": "^29.7.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chai": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.5.0.tgz", + "integrity": "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.4.tgz", + "integrity": "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.2.tgz", + "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.39.2", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-prettier": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", + "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "peer": true, + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", + "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fetch-ponyfill": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/fetch-ponyfill/-/fetch-ponyfill-7.1.0.tgz", + "integrity": "sha512-FhbbL55dj/qdVO3YNK7ZEkshvj3eQ7EuIGV2I6ic/2YiocvyWv+7jg2s4AyS0wdRU75s3tA8ZxI/xPigb0v5Aw==", + "license": "MIT", + "dependencies": { + "node-fetch": "~2.6.1" + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", + "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.11.5", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.5.tgz", + "integrity": "sha512-WemPi9/WfyMwZs+ZUXdiwcCh9Y+m7L+8vki9MzDw3jJ+W9Lc+12HGsd368Qc1vZi1xwW8BWMMsnK5efYKPdt4g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jose": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", + "integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/local-pkg": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.1.tgz", + "integrity": "sha512-9rrA30MRRP3gBD3HTGnC6cDFpaE1kVDWxWgqWJUN0RvDNAo+Nz/9GxB+nHOH0ifbVFy0hSA1V6vFDvnx54lTEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mlly": "^1.7.3", + "pkg-types": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz", + "integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.4", + "@babel/types": "^7.25.4", + "source-map-js": "^1.2.0" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mlly": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz", + "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.1" + } + }, + "node_modules/mlly/node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-StxNAxh15zr77QvvkmveSQ8uCQ4+v5FkvNTj0OESmiHu+VRi/gXArXtkWMElOsOUNLtUEvI4yS+rdtOHZTwlQA==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pathe": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", + "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/pkg-types/node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/rollup": { + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.56.0.tgz", + "integrity": "sha512-9FwVqlgUHzbXtDg9RCMgodF3Ua4Na6Gau+Sdt9vyCN4RhHfVKX2DCHy3BjMLTDd47ITDhYAnTwGulWTblJSDLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.56.0", + "@rollup/rollup-android-arm64": "4.56.0", + "@rollup/rollup-darwin-arm64": "4.56.0", + "@rollup/rollup-darwin-x64": "4.56.0", + "@rollup/rollup-freebsd-arm64": "4.56.0", + "@rollup/rollup-freebsd-x64": "4.56.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.56.0", + "@rollup/rollup-linux-arm-musleabihf": "4.56.0", + "@rollup/rollup-linux-arm64-gnu": "4.56.0", + "@rollup/rollup-linux-arm64-musl": "4.56.0", + "@rollup/rollup-linux-loong64-gnu": "4.56.0", + "@rollup/rollup-linux-loong64-musl": "4.56.0", + "@rollup/rollup-linux-ppc64-gnu": "4.56.0", + "@rollup/rollup-linux-ppc64-musl": "4.56.0", + "@rollup/rollup-linux-riscv64-gnu": "4.56.0", + "@rollup/rollup-linux-riscv64-musl": "4.56.0", + "@rollup/rollup-linux-s390x-gnu": "4.56.0", + "@rollup/rollup-linux-x64-gnu": "4.56.0", + "@rollup/rollup-linux-x64-musl": "4.56.0", + "@rollup/rollup-openbsd-x64": "4.56.0", + "@rollup/rollup-openharmony-arm64": "4.56.0", + "@rollup/rollup-win32-arm64-msvc": "4.56.0", + "@rollup/rollup-win32-ia32-msvc": "4.56.0", + "@rollup/rollup-win32-x64-gnu": "4.56.0", + "@rollup/rollup-win32-x64-msvc": "4.56.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-literal": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-2.1.1.tgz", + "integrity": "sha512-631UJ6O00eNGfMiWG78ck80dfBab8X6IVFB51jZK5Icd7XAs60Z5y7QdSd/wGIklnWvRbUNloVzhOKKmutxQ6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/test-exclude/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/test-exclude/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinypool": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.8.4.tgz", + "integrity": "sha512-i11VH5gS6IFeLY3gMBQ00/MmLncVP7JLXOw1vlgkytLmJK7QnEr7NXf0LBdxfmNPAeyetukOk0bOYrJrFGjYJQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz", + "integrity": "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tsx": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-detect": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.53.1.tgz", + "integrity": "sha512-gB+EVQfP5RDElh9ittfXlhZJdjSU4jUSTyE2+ia8CYyNvet4ElfaLlAIqDvQV9JPknKx0jQH1racTYe/4LaLSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.53.1", + "@typescript-eslint/parser": "8.53.1", + "@typescript-eslint/typescript-estree": "8.53.1", + "@typescript-eslint/utils": "8.53.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.53.1.tgz", + "integrity": "sha512-cFYYFZ+oQFi6hUnBTbLRXfTJiaQtYE3t4O692agbBl+2Zy+eqSKWtPjhPXJu1G7j4RLjKgeJPDdq3EqOwmX5Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.53.1", + "@typescript-eslint/type-utils": "8.53.1", + "@typescript-eslint/utils": "8.53.1", + "@typescript-eslint/visitor-keys": "8.53.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.53.1", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/parser": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.53.1.tgz", + "integrity": "sha512-nm3cvFN9SqZGXjmw5bZ6cGmvJSyJPn0wU9gHAZZHDnZl2wF9PhHv78Xf06E0MaNk4zLVHL8hb2/c32XvyJOLQg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@typescript-eslint/scope-manager": "8.53.1", + "@typescript-eslint/types": "8.53.1", + "@typescript-eslint/typescript-estree": "8.53.1", + "@typescript-eslint/visitor-keys": "8.53.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/scope-manager": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.53.1.tgz", + "integrity": "sha512-Lu23yw1uJMFY8cUeq7JlrizAgeQvWugNQzJp8C3x8Eo5Jw5Q2ykMdiiTB9vBVOOUBysMzmRRmUfwFrZuI2C4SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.53.1", + "@typescript-eslint/visitor-keys": "8.53.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/type-utils": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.53.1.tgz", + "integrity": "sha512-MOrdtNvyhy0rHyv0ENzub1d4wQYKb2NmIqG7qEqPWFW7Mpy2jzFC3pQ2yKDvirZB7jypm5uGjF2Qqs6OIqu47w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.53.1", + "@typescript-eslint/typescript-estree": "8.53.1", + "@typescript-eslint/utils": "8.53.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/types": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.53.1.tgz", + "integrity": "sha512-jr/swrr2aRmUAUjW5/zQHbMaui//vQlsZcJKijZf3M26bnmLj8LyZUpj8/Rd6uzaek06OWsqdofN/Thenm5O8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/typescript-estree": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.53.1.tgz", + "integrity": "sha512-RGlVipGhQAG4GxV1s34O91cxQ/vWiHJTDHbXRr0li2q/BGg3RR/7NM8QDWgkEgrwQYCvmJV9ichIwyoKCQ+DTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.53.1", + "@typescript-eslint/tsconfig-utils": "8.53.1", + "@typescript-eslint/types": "8.53.1", + "@typescript-eslint/visitor-keys": "8.53.1", + "debug": "^4.4.3", + "minimatch": "^9.0.5", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/utils": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.53.1.tgz", + "integrity": "sha512-c4bMvGVWW4hv6JmDUEG7fSYlWOl3II2I4ylt0NM+seinYQlZMQIaKaXIIVJWt9Ofh6whrpM+EdDQXKXjNovvrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.53.1", + "@typescript-eslint/types": "8.53.1", + "@typescript-eslint/typescript-estree": "8.53.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/visitor-keys": { + "version": "8.53.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.53.1.tgz", + "integrity": "sha512-oy+wV7xDKFPRyNggmXuZQSBzvoLnpmJs+GhzRhPjrxl2b/jIlyjVokzm47CZCDUdXKr2zd7ZLodPfOBpOPyPlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.53.1", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/typescript-eslint/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/typescript-eslint/node_modules/ts-api-utils": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", + "integrity": "sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ufo": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz", + "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-1.6.1.tgz", + "integrity": "sha512-YAXkfvGtuTzwWbDSACdJSg4A4DZiAqckWe90Zapc/sEX3XvHcw1NdurM/6od8J207tSDqNbSsgdCacBgvJKFuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "pathe": "^1.1.1", + "picocolors": "^1.0.0", + "vite": "^5.0.0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite/node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/vite/node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/vitest": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-1.6.1.tgz", + "integrity": "sha512-Ljb1cnSJSivGN0LqXd/zmDbWEM0RNNg2t1QW/XUhYl/qPqyu7CsqeWtqQXHVaJsecLPuDoak2oJcZN2QoRIOag==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@vitest/expect": "1.6.1", + "@vitest/runner": "1.6.1", + "@vitest/snapshot": "1.6.1", + "@vitest/spy": "1.6.1", + "@vitest/utils": "1.6.1", + "acorn-walk": "^8.3.2", + "chai": "^4.3.10", + "debug": "^4.3.4", + "execa": "^8.0.1", + "local-pkg": "^0.5.0", + "magic-string": "^0.30.5", + "pathe": "^1.1.1", + "picocolors": "^1.0.0", + "std-env": "^3.5.0", + "strip-literal": "^2.0.0", + "tinybench": "^2.5.1", + "tinypool": "^0.8.3", + "vite": "^5.0.0", + "vite-node": "1.6.1", + "why-is-node-running": "^2.2.2" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/node": "^18.0.0 || >=20.0.0", + "@vitest/browser": "1.6.1", + "@vitest/ui": "1.6.1", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ynab": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/ynab/-/ynab-1.55.0.tgz", + "integrity": "sha512-i5MEPWpMILUiqQ9JXFBa//ljGEAtVziyx2C1s09THWoPu8b1R7k/NjDQRsM3YpYUDFTDyKRTmKOA+vxzkkK9dQ==", + "license": "Apache-2.0", + "dependencies": { + "fetch-ponyfill": "^7.1.0" + }, + "engines": { + "node": "<=18" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0104257 --- /dev/null +++ b/package.json @@ -0,0 +1,62 @@ +{ + "name": "ynab-mcp-server", + "version": "0.1.0", + "description": "MCP server providing complete YNAB API coverage for Claude integration", + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "bin": { + "ynab-mcp-server": "dist/index.js" + }, + "scripts": { + "build": "tsc", + "dev": "tsx watch src/index.ts", + "start": "node dist/index.js", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage", + "lint": "eslint src", + "lint:fix": "eslint src --fix", + "format": "prettier --write \"src/**/*.ts\"", + "typecheck": "tsc --noEmit", + "clean": "rm -rf dist", + "prepublishOnly": "npm run build" + }, + "keywords": [ + "mcp", + "model-context-protocol", + "ynab", + "budget", + "finance", + "claude", + "ai" + ], + "author": "", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.25.3", + "decimal.js": "^10.4.3", + "ynab": "^1.35.0", + "zod": "^3.23.8" + }, + "devDependencies": { + "@eslint/js": "^9.39.2", + "@types/node": "^20.11.0", + "@vitest/coverage-v8": "^1.2.0", + "eslint": "^9.39.2", + "eslint-config-prettier": "^9.1.0", + "prettier": "^3.2.0", + "tsx": "^4.7.0", + "typescript": "^5.3.0", + "typescript-eslint": "^8.53.1", + "vitest": "^1.2.0" + }, + "files": [ + "dist", + "README.md", + "LICENSE" + ] +} diff --git a/src/config/environment.ts b/src/config/environment.ts new file mode 100644 index 0000000..93aec55 --- /dev/null +++ b/src/config/environment.ts @@ -0,0 +1,85 @@ +/** + * Environment Configuration + * + * Loads and validates configuration from environment variables. + */ + +import { z } from 'zod'; + +const configSchema = z.object({ + accessToken: z.string().min(1, 'YNAB_ACCESS_TOKEN is required'), + defaultBudgetId: z.union([z.string().uuid(), z.literal('last-used')]).optional(), + logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'), + cacheTtlMs: z.number().int().positive().default(300000), // 5 minutes + rateLimitPerHour: z.number().int().min(1).max(200).default(180), + readOnly: z.boolean().default(true), // Safety: read-only by default +}); + +export type Config = z.infer; + +/** + * Parse a boolean environment variable with strict validation. + * + * Accepts: 'true', '1', 'yes' => true + * 'false', '0', 'no' => false + * undefined/empty => defaultValue + * + * Throws on unrecognized values to prevent security footguns + * (e.g., YNAB_READ_ONLY=ture typo accidentally enabling writes). + */ +function parseBoolean(value: string | undefined, defaultValue: boolean, varName?: string): boolean { + if (value === undefined || value === '') return defaultValue; + const lower = value.toLowerCase(); + if (lower === 'true' || lower === '1' || lower === 'yes') return true; + if (lower === 'false' || lower === '0' || lower === 'no') return false; + + const nameHint = varName ? ` for ${varName}` : ''; + throw new Error( + `Invalid boolean value "${value}"${nameHint}. ` + + `Expected: true, false, 1, 0, yes, or no.` + ); +} + +/** + * Parse an integer environment variable with strict validation. + * + * Rejects partial parses like "10ms" that parseInt would accept as 10. + * Only accepts strings containing only digits. + */ +function parseInteger(value: string | undefined, defaultValue: number, varName?: string): number { + if (value === undefined || value === '') return defaultValue; + + // Strict check: only digits allowed (no partial parses like "10ms" -> 10) + if (!/^\d+$/.test(value)) { + const nameHint = varName ? ` for ${varName}` : ''; + throw new Error( + `Invalid integer value "${value}"${nameHint}. ` + + `Expected a positive integer (digits only).` + ); + } + + return Number(value); +} + +export function loadConfig(): Config { + const rawConfig = { + accessToken: process.env['YNAB_ACCESS_TOKEN'] ?? '', + defaultBudgetId: process.env['YNAB_BUDGET_ID'] || undefined, + logLevel: process.env['LOG_LEVEL'] ?? 'info', + cacheTtlMs: parseInteger(process.env['CACHE_TTL_MS'], 300000, 'CACHE_TTL_MS'), + rateLimitPerHour: parseInteger(process.env['RATE_LIMIT_PER_HOUR'], 180, 'RATE_LIMIT_PER_HOUR'), + // READ_ONLY defaults to true for safety - must explicitly set to false to enable writes + readOnly: parseBoolean(process.env['YNAB_READ_ONLY'], true, 'YNAB_READ_ONLY'), + }; + + const result = configSchema.safeParse(rawConfig); + + if (!result.success) { + const errors = result.error.errors + .map((e) => ` - ${e.path.join('.')}: ${e.message}`) + .join('\n'); + throw new Error(`Configuration validation failed:\n${errors}`); + } + + return result.data; +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..898387d --- /dev/null +++ b/src/index.ts @@ -0,0 +1,61 @@ +#!/usr/bin/env node + +/** + * YNAB MCP Server + * + * A Model Context Protocol server providing complete YNAB API coverage + * for integration with Claude and other MCP-compatible clients. + */ + +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { createServer } from './server.js'; +import { loadConfig } from './config/environment.js'; + +// Store server reference for graceful shutdown +let server: Server | null = null; + +async function shutdown(): Promise { + console.error('Shutting down YNAB MCP Server...'); + if (server) { + try { + await server.close(); + } catch (error) { + // Log close errors at debug level (to stderr), then continue shutdown + // Only log message to avoid leaking sensitive details from full error object + const message = error instanceof Error ? error.message : 'Unknown error'; + console.error('[DEBUG] Error during server close:', message); + } + } + process.exit(0); +} + +async function main(): Promise { + // Load and validate configuration + const config = loadConfig(); + + // Create the MCP server with all tools registered + server = createServer(config); + + // Create stdio transport for communication + const transport = new StdioServerTransport(); + + // Connect server to transport + await server.connect(transport); + + // Log startup (to stderr to avoid interfering with stdio protocol) + console.error(`YNAB MCP Server started (budget: ${config.defaultBudgetId ?? 'last-used'})`); +} + +// Handle graceful shutdown +process.on('SIGINT', () => void shutdown()); +process.on('SIGTERM', () => void shutdown()); +process.stdin.on('close', () => void shutdown()); + +// Run the server +main().catch((error: unknown) => { + // Only log error message to avoid leaking sensitive config details + const message = error instanceof Error ? error.message : 'Unknown error'; + console.error('Failed to start YNAB MCP Server:', message); + process.exit(1); +}); diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..960a267 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,82 @@ +/** + * MCP Server Configuration and Tool Registration + */ + +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { + CallToolRequestSchema, + ListToolsRequestSchema, +} from '@modelcontextprotocol/sdk/types.js'; +import type { Config } from './config/environment.js'; +import { YnabClient } from './services/ynab-client.js'; +import { RateLimiter } from './services/rate-limiter.js'; +import { Cache } from './services/cache.js'; +import { tools, handleToolCall } from './tools/index.js'; +import { formatErrorResponse } from './utils/errors.js'; + +export function createServer(config: Config): Server { + // Initialize services + const rateLimiter = new RateLimiter(config.rateLimitPerHour); + const cache = new Cache(config.cacheTtlMs); + const ynabClient = new YnabClient( + config.accessToken, + config.defaultBudgetId, + rateLimiter, + cache, + config.readOnly + ); + + // Log read-only mode status + if (config.readOnly) { + console.error('YNAB MCP Server running in READ-ONLY mode (write operations disabled)'); + } else { + console.error('YNAB MCP Server running with WRITE operations ENABLED'); + } + + // Create MCP server + const server = new Server( + { + name: 'ynab-mcp-server', + version: '0.1.0', + }, + { + capabilities: { + tools: {}, + }, + } + ); + + // Register tool listing handler + server.setRequestHandler(ListToolsRequestSchema, async () => { + return { tools }; + }); + + // Register tool call handler + server.setRequestHandler(CallToolRequestSchema, async (request) => { + const { name, arguments: args } = request.params; + + try { + const result = await handleToolCall(name, args ?? {}, ynabClient); + return { + content: [ + { + type: 'text', + text: result, + }, + ], + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: formatErrorResponse(error), + }, + ], + isError: true, + }; + } + }); + + return server; +} diff --git a/src/services/audit-log.ts b/src/services/audit-log.ts new file mode 100644 index 0000000..46d8ee2 --- /dev/null +++ b/src/services/audit-log.ts @@ -0,0 +1,226 @@ +/** + * Audit Log Service + * + * Logs all write operations for security and debugging purposes. + * Logs are stored in memory and can be retrieved via the audit log tool. + * + * SECURITY: Audit log entries are accessible via the ynab_audit_log tool. + * Callers must NOT include sensitive data in the `details` or `error` fields: + * - No PII (names, addresses, account numbers) + * - No authentication tokens or credentials + * - No full payee names or memo contents (use has_payee, has_memo flags instead) + * + * Design Decision: The `details` field is NOT sanitized at read time. + * We rely on callers following the documented contract above. Rationale: + * 1. All current callers in ynab-client.ts comply (using has_memo, has_name flags) + * 2. Sanitizing arbitrary nested objects is complex and error-prone + * 3. Generic sanitization risks false positives (redacting non-sensitive data) + * 4. The contract is well-documented at both the service and interface level + * + * Note: Error messages ARE defensively sanitized (sensitive patterns redacted, then truncated). + */ + +import { sanitizeErrorMessage } from '../utils/sanitize.js'; + +/** Maximum length for error messages in audit entries */ +const MAX_ERROR_LENGTH = 500; + +/** + * Represents a single audit log entry. + * + * @property details - Metadata about the operation. MUST NOT contain sensitive data (PII, tokens, credentials). + * @property error - Error message if operation failed. May be exposed via audit log tool. + */ +export interface AuditLogEntry { + timestamp: string; + operation: string; + tool: string; + budgetId: string; + resourceType: string; + resourceId?: string; + /** Operation metadata. MUST NOT contain PII, tokens, or other sensitive data. */ + details: Record; + success: boolean; + /** Error message if failed. Avoid including sensitive information. */ + error?: string; +} + +export class AuditLog { + private readonly entries: AuditLogEntry[] = []; + private readonly maxEntries: number; + + constructor(maxEntries: number = 1000) { + this.maxEntries = maxEntries; + } + + /** + * Log a write operation. + * + * SECURITY: The `details` field MUST NOT contain sensitive data (PII, tokens, + * full payee names, memo contents). Use boolean flags like `has_payee` instead. + * This data is accessible via the ynab_audit_log tool. + */ + log(entry: Omit): void { + // Defensively sanitize error messages: redact sensitive patterns and truncate + let sanitizedError: string | undefined; + if (entry.error !== undefined) { + sanitizedError = sanitizeErrorMessage(entry.error, MAX_ERROR_LENGTH); + } + + const fullEntry: AuditLogEntry = { + ...entry, + timestamp: new Date().toISOString(), + }; + // Only set error if it exists (exactOptionalPropertyTypes compliance) + if (sanitizedError !== undefined) { + fullEntry.error = sanitizedError; + } + + this.entries.push(fullEntry); + + // Trim old entries if over limit + if (this.entries.length > this.maxEntries) { + this.entries.shift(); + } + + // Also log to stderr for server-side visibility + const status = entry.success ? 'SUCCESS' : 'FAILED'; + const resourceInfo = entry.resourceId ? ` (${entry.resourceId})` : ''; + console.error( + `[AUDIT] ${status}: ${entry.operation} on ${entry.resourceType}${resourceInfo} via ${entry.tool}` + ); + } + + /** + * Get all log entries. + */ + getAll(): AuditLogEntry[] { + return [...this.entries]; + } + + /** + * Get entries filtered by criteria. + */ + getFiltered(options: { + operation?: string; + tool?: string; + budgetId?: string; + resourceType?: string; + success?: boolean; + since?: string; + limit?: number; + }): AuditLogEntry[] { + // Create shallow copy immediately to avoid mutating internal state + let filtered = [...this.entries]; + + if (options.operation) { + filtered = filtered.filter((e) => e.operation === options.operation); + } + if (options.tool) { + filtered = filtered.filter((e) => e.tool === options.tool); + } + if (options.budgetId) { + filtered = filtered.filter((e) => e.budgetId === options.budgetId); + } + if (options.resourceType) { + filtered = filtered.filter((e) => e.resourceType === options.resourceType); + } + if (options.success !== undefined) { + filtered = filtered.filter((e) => e.success === options.success); + } + if (options.since !== undefined) { + const sinceDate = options.since; + filtered = filtered.filter((e) => e.timestamp >= sinceDate); + } + + // Return most recent first + filtered.reverse(); + + if (options.limit !== undefined) { + filtered = filtered.slice(0, options.limit); + } + + return filtered; + } + + /** + * Get summary statistics. + */ + getSummary(): { + totalOperations: number; + successCount: number; + failureCount: number; + byOperation: Record; + byResourceType: Record; + oldestEntry?: string; + newestEntry?: string; + } { + const byOperation: Record = {}; + const byResourceType: Record = {}; + let successCount = 0; + let failureCount = 0; + + for (const entry of this.entries) { + byOperation[entry.operation] = (byOperation[entry.operation] ?? 0) + 1; + byResourceType[entry.resourceType] = (byResourceType[entry.resourceType] ?? 0) + 1; + if (entry.success) { + successCount++; + } else { + failureCount++; + } + } + + const result: { + totalOperations: number; + successCount: number; + failureCount: number; + byOperation: Record; + byResourceType: Record; + oldestEntry?: string; + newestEntry?: string; + } = { + totalOperations: this.entries.length, + successCount, + failureCount, + byOperation, + byResourceType, + }; + + const oldest = this.entries[0]?.timestamp; + const newest = this.entries[this.entries.length - 1]?.timestamp; + if (oldest !== undefined) result.oldestEntry = oldest; + if (newest !== undefined) result.newestEntry = newest; + + return result; + } + + /** + * Clear all entries. + */ + clear(): number { + const count = this.entries.length; + this.entries.length = 0; + return count; + } +} + +// Singleton instance +let auditLogInstance: AuditLog | null = null; + +export function getAuditLog(): AuditLog { + if (!auditLogInstance) { + auditLogInstance = new AuditLog(); + } + return auditLogInstance; +} + +/** + * Reset the singleton instance for testing isolation. + * @internal - Only use in test code + */ +export function _resetAuditLogForTesting(): void { + if (process.env['NODE_ENV'] === 'production') { + throw new Error('_resetAuditLogForTesting cannot be called in production'); + } + auditLogInstance = null; +} diff --git a/src/services/cache.ts b/src/services/cache.ts new file mode 100644 index 0000000..45d2e0c --- /dev/null +++ b/src/services/cache.ts @@ -0,0 +1,108 @@ +/** + * Simple In-Memory Cache with TTL + * + * Used to cache YNAB API responses that don't change frequently + * (budgets, accounts, categories, payees). + */ + +interface CacheEntry { + value: T; + expiresAt: number; +} + +export class Cache { + private readonly store: Map> = new Map(); + private readonly defaultTtlMs: number; + + constructor(defaultTtlMs: number = 300000) { // 5 minutes default + if (!Number.isFinite(defaultTtlMs) || defaultTtlMs <= 0) { + throw new Error(`Invalid default TTL: ${defaultTtlMs}. TTL must be a positive finite number.`); + } + this.defaultTtlMs = defaultTtlMs; + } + + /** + * Get a value from the cache. + * Returns undefined if not found or expired. + */ + get(key: string): T | undefined { + const entry = this.store.get(key); + + if (entry === undefined) { + return undefined; + } + + if (Date.now() > entry.expiresAt) { + this.store.delete(key); + return undefined; + } + + return entry.value as T; + } + + /** + * Set a value in the cache. + * Guards against non-finite TTLs to prevent never-expiring entries. + */ + set(key: string, value: T, ttlMs?: number): void { + const ttl = ttlMs ?? this.defaultTtlMs; + // Guard against NaN/Infinity to prevent never-expiring entries + if (!Number.isFinite(ttl) || ttl <= 0) { + throw new Error(`Invalid TTL: ${ttl}. TTL must be a positive finite number.`); + } + const expiresAt = Date.now() + ttl; + this.store.set(key, { value, expiresAt }); + } + + /** + * Delete a specific key from the cache. + */ + delete(key: string): boolean { + return this.store.delete(key); + } + + /** + * Delete all keys matching a prefix. + */ + deleteByPrefix(prefix: string): number { + let count = 0; + for (const key of this.store.keys()) { + if (key.startsWith(prefix)) { + this.store.delete(key); + count++; + } + } + return count; + } + + /** + * Clear all entries from the cache. + */ + clear(): void { + this.store.clear(); + } + + /** + * Get the number of entries in the cache (including expired). + */ + size(): number { + return this.store.size; + } + + /** + * Remove all expired entries. + */ + prune(): number { + const now = Date.now(); + let count = 0; + + for (const [key, entry] of this.store.entries()) { + if (now > entry.expiresAt) { + this.store.delete(key); + count++; + } + } + + return count; + } +} diff --git a/src/services/rate-limiter.ts b/src/services/rate-limiter.ts new file mode 100644 index 0000000..204f5bf --- /dev/null +++ b/src/services/rate-limiter.ts @@ -0,0 +1,129 @@ +/** + * Rate Limiter + * + * Token bucket algorithm to enforce YNAB's API rate limits. + * YNAB allows 200 requests/hour; we default to 180 for safety margin. + */ + +export class RateLimiter { + private tokens: number; + private lastRefill: number; + private readonly maxTokens: number; + private readonly refillRate: number; // tokens per millisecond + private acquireLock: Promise = Promise.resolve(); + + constructor(requestsPerHour: number = 180) { + // Validate requestsPerHour to prevent rate-limit bypass + if (!Number.isFinite(requestsPerHour) || requestsPerHour <= 0) { + throw new Error(`Invalid requestsPerHour: must be a positive finite number, got ${requestsPerHour}`); + } + this.maxTokens = requestsPerHour; + this.tokens = requestsPerHour; + this.lastRefill = Date.now(); + // Convert requests/hour to requests/millisecond + this.refillRate = requestsPerHour / (60 * 60 * 1000); + } + + /** + * Acquire a token, waiting if necessary. + * Call this before making any API request. + * Uses a mutex to prevent race conditions with concurrent callers. + */ + async acquire(): Promise { + // Chain onto the existing lock to ensure sequential execution + const previousLock = this.acquireLock; + let releaseLock: () => void; + this.acquireLock = new Promise((resolve) => { + releaseLock = resolve; + }); + + try { + // Wait for previous acquire to complete + await previousLock; + + this.refill(); + + if (this.tokens < 1) { + // Calculate wait time to get at least 1 token + const waitTime = Math.ceil((1 - this.tokens) / this.refillRate); + await this.sleep(waitTime); + this.refill(); + } + + this.tokens -= 1; + } finally { + releaseLock!(); + } + } + + /** + * Check if a request can be made immediately. + */ + canAcquire(): boolean { + this.refill(); + return this.tokens >= 1; + } + + /** + * Get current number of available tokens. + */ + getAvailableTokens(): number { + this.refill(); + return Math.floor(this.tokens); + } + + /** + * Get estimated time until a token is available (in ms). + */ + getWaitTime(): number { + this.refill(); + if (this.tokens >= 1) return 0; + return Math.ceil((1 - this.tokens) / this.refillRate); + } + + /** + * Get comprehensive rate limit status. + */ + getStatus(): { + available: number; + limit: number; + used: number; + percentUsed: number; + canMakeRequest: boolean; + waitTimeMs: number; + resetTimeMs: number; + } { + this.refill(); + const available = Math.floor(this.tokens); + const used = this.maxTokens - available; + const percentUsed = Math.round((used / this.maxTokens) * 100); + // Inline wait time calculation to avoid redundant refill() call in getWaitTime() + const waitTimeMs = this.tokens >= 1 ? 0 : Math.ceil((1 - this.tokens) / this.refillRate); + // Time until fully refilled + const tokensNeeded = this.maxTokens - this.tokens; + const resetTimeMs = tokensNeeded > 0 ? Math.ceil(tokensNeeded / this.refillRate) : 0; + + return { + available, + limit: this.maxTokens, + used, + percentUsed, + canMakeRequest: available >= 1, + waitTimeMs, + resetTimeMs, + }; + } + + private refill(): void { + const now = Date.now(); + const elapsed = now - this.lastRefill; + const newTokens = elapsed * this.refillRate; + + this.tokens = Math.min(this.maxTokens, this.tokens + newTokens); + this.lastRefill = now; + } + + private sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } +} diff --git a/src/services/ynab-client.ts b/src/services/ynab-client.ts new file mode 100644 index 0000000..876ab91 --- /dev/null +++ b/src/services/ynab-client.ts @@ -0,0 +1,563 @@ +/** + * YNAB Client Wrapper + * + * Wraps the official YNAB SDK with rate limiting, caching, and read-only mode. + */ + +import * as ynab from 'ynab'; +import type { RateLimiter } from './rate-limiter.js'; +import type { Cache } from './cache.js'; +import { ReadOnlyModeError } from '../utils/errors.js'; +import { getAuditLog } from './audit-log.js'; +import { sanitizeErrorMessage } from '../utils/sanitize.js'; + +export class YnabClient { + private readonly api: ynab.API; + private readonly rateLimiter: RateLimiter; + private readonly cache: Cache; + private readonly defaultBudgetId: string; + private readonly readOnly: boolean; + + // Track server knowledge for delta sync + private serverKnowledge: Map = new Map(); + + constructor( + accessToken: string, + defaultBudgetId: string | undefined, + rateLimiter: RateLimiter, + cache: Cache, + readOnly = true + ) { + this.api = new ynab.API(accessToken); + this.rateLimiter = rateLimiter; + this.cache = cache; + this.defaultBudgetId = defaultBudgetId ?? 'last-used'; + this.readOnly = readOnly; + } + + /** + * Check if the client is in read-only mode. + */ + isReadOnly(): boolean { + return this.readOnly; + } + + /** + * Get rate limit status. + */ + getRateLimitStatus(): ReturnType { + return this.rateLimiter.getStatus(); + } + + /** + * Guard against write operations in read-only mode. + * @throws ReadOnlyModeError if in read-only mode + */ + private assertWriteAllowed(operation: string): void { + if (this.readOnly) { + throw new ReadOnlyModeError(operation); + } + } + + /** + * Get the default budget ID, resolving "last-used" if needed. + */ + getDefaultBudgetId(): string { + return this.defaultBudgetId; + } + + /** + * Resolve a budget ID, using default if not provided. + * + * Design Decision: budget_id is intentionally not validated as a UUID. + * The YNAB API accepts both UUIDs and the special sentinel value "last-used" + * to reference the most recently accessed budget. Rather than maintaining a + * union type that could break if YNAB adds more special values, we accept + * any string and let the YNAB API validate it. This provides better forward + * compatibility and clearer error messages from the source of truth. + */ + resolveBudgetId(budgetId?: string): string { + return budgetId ?? this.defaultBudgetId; + } + + /** + * Get server knowledge for a budget (used for delta sync). + */ + getServerKnowledge(budgetId: string): number | undefined { + return this.serverKnowledge.get(budgetId); + } + + /** + * Update server knowledge after a response. + */ + updateServerKnowledge(budgetId: string, knowledge: number): void { + this.serverKnowledge.set(budgetId, knowledge); + } + + // ==================== User ==================== + + async getUser(): Promise { + await this.rateLimiter.acquire(); + return this.api.user.getUser(); + } + + // ==================== Budgets ==================== + + async getBudgets(includeAccounts = false): Promise { + const cacheKey = `budgets:${includeAccounts}`; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) return cached; + + await this.rateLimiter.acquire(); + const response = await this.api.budgets.getBudgets(includeAccounts); + this.cache.set(cacheKey, response); + return response; + } + + async getBudgetById( + budgetId: string, + lastKnowledgeOfServer?: number + ): Promise { + await this.rateLimiter.acquire(); + const response = await this.api.budgets.getBudgetById(budgetId, lastKnowledgeOfServer); + + if (response.data.server_knowledge !== undefined) { + this.updateServerKnowledge(budgetId, response.data.server_knowledge); + } + + return response; + } + + async getBudgetSettingsById(budgetId: string): Promise { + const cacheKey = `budget-settings:${budgetId}`; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) return cached; + + await this.rateLimiter.acquire(); + const response = await this.api.budgets.getBudgetSettingsById(budgetId); + this.cache.set(cacheKey, response); + return response; + } + + // ==================== Accounts ==================== + + async getAccounts(budgetId: string): Promise { + const cacheKey = `accounts:${budgetId}`; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) return cached; + + await this.rateLimiter.acquire(); + const response = await this.api.accounts.getAccounts(budgetId); + this.cache.set(cacheKey, response); + return response; + } + + async getAccountById(budgetId: string, accountId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.accounts.getAccountById(budgetId, accountId); + } + + async createAccount( + budgetId: string, + data: ynab.PostAccountWrapper + ): Promise { + this.assertWriteAllowed('createAccount'); + await this.rateLimiter.acquire(); + // Invalidate accounts cache after creating + // Also invalidate budgets cache since getBudgets(true) includes account data + this.cache.delete(`accounts:${budgetId}`); + // Only invalidate budgets:true since getBudgets(false) doesn't include account data + this.cache.delete('budgets:true'); + + const auditLog = getAuditLog(); + try { + const response = await this.api.accounts.createAccount(budgetId, data); + auditLog.log({ + operation: 'create', + tool: 'ynab_create_account', + budgetId, + resourceType: 'account', + resourceId: response.data.account.id, + details: { type: data.account.type, has_name: !!data.account.name }, + success: true, + }); + return response; + } catch (error) { + auditLog.log({ + operation: 'create', + tool: 'ynab_create_account', + budgetId, + resourceType: 'account', + details: { type: data.account.type, has_name: !!data.account.name }, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + // ==================== Categories ==================== + + async getCategories(budgetId: string): Promise { + const cacheKey = `categories:${budgetId}`; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) return cached; + + await this.rateLimiter.acquire(); + const response = await this.api.categories.getCategories(budgetId); + this.cache.set(cacheKey, response); + return response; + } + + async getCategoryById(budgetId: string, categoryId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.categories.getCategoryById(budgetId, categoryId); + } + + async getMonthCategoryById( + budgetId: string, + month: string, + categoryId: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.categories.getMonthCategoryById(budgetId, month, categoryId); + } + + async updateMonthCategory( + budgetId: string, + month: string, + categoryId: string, + data: ynab.PatchMonthCategoryWrapper + ): Promise { + this.assertWriteAllowed('updateMonthCategory'); + await this.rateLimiter.acquire(); + // Invalidate categories cache after updating + this.cache.delete(`categories:${budgetId}`); + + const auditLog = getAuditLog(); + try { + const response = await this.api.categories.updateMonthCategory(budgetId, month, categoryId, data); + auditLog.log({ + operation: 'update', + tool: 'ynab_update_category', + budgetId, + resourceType: 'category', + resourceId: categoryId, + details: { month, budgeted: data.category.budgeted }, + success: true, + }); + return response; + } catch (error) { + auditLog.log({ + operation: 'update', + tool: 'ynab_update_category', + budgetId, + resourceType: 'category', + resourceId: categoryId, + details: { month, budgeted: data.category.budgeted }, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + // ==================== Transactions ==================== + + async getTransactions( + budgetId: string, + options?: { + sinceDate?: string; + type?: 'uncategorized' | 'unapproved'; + lastKnowledgeOfServer?: number; + } + ): Promise { + await this.rateLimiter.acquire(); + const response = await this.api.transactions.getTransactions( + budgetId, + options?.sinceDate, + options?.type, + options?.lastKnowledgeOfServer + ); + + if (response.data.server_knowledge !== undefined) { + this.updateServerKnowledge(budgetId, response.data.server_knowledge); + } + + return response; + } + + async getTransactionById( + budgetId: string, + transactionId: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.transactions.getTransactionById(budgetId, transactionId); + } + + async createTransaction( + budgetId: string, + data: ynab.PostTransactionsWrapper + ): Promise { + this.assertWriteAllowed('createTransaction'); + await this.rateLimiter.acquire(); + + const auditLog = getAuditLog(); + const txn = data.transaction; + try { + const response = await this.api.transactions.createTransaction(budgetId, data); + // Redact PII from audit logs - payee_name may contain personal information + const logEntry: Parameters[0] = { + operation: 'create', + tool: 'ynab_create_transaction', + budgetId, + resourceType: 'transaction', + details: { + amount: txn?.amount, + date: txn?.date, + has_payee: txn?.payee_name !== undefined && txn?.payee_name !== null, + account_id: txn?.account_id, + }, + success: true, + }; + const createdId = response.data.transaction?.id; + if (createdId !== undefined) logEntry.resourceId = createdId; + auditLog.log(logEntry); + return response; + } catch (error) { + auditLog.log({ + operation: 'create', + tool: 'ynab_create_transaction', + budgetId, + resourceType: 'transaction', + details: { + amount: txn?.amount, + date: txn?.date, + has_payee: txn?.payee_name !== undefined && txn?.payee_name !== null, + account_id: txn?.account_id, + }, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + async updateTransaction( + budgetId: string, + transactionId: string, + data: ynab.PutTransactionWrapper + ): Promise { + this.assertWriteAllowed('updateTransaction'); + await this.rateLimiter.acquire(); + + const auditLog = getAuditLog(); + const txn = data.transaction; + try { + const response = await this.api.transactions.updateTransaction(budgetId, transactionId, data); + // Redact memo from audit logs - may contain sensitive user data + auditLog.log({ + operation: 'update', + tool: 'ynab_update_transaction', + budgetId, + resourceType: 'transaction', + resourceId: transactionId, + details: { + amount: txn.amount, + date: txn.date, + has_memo: txn.memo !== undefined && txn.memo !== null && txn.memo !== '', + category_id: txn.category_id, + }, + success: true, + }); + return response; + } catch (error) { + auditLog.log({ + operation: 'update', + tool: 'ynab_update_transaction', + budgetId, + resourceType: 'transaction', + resourceId: transactionId, + details: { + amount: txn.amount, + date: txn.date, + has_memo: txn.memo !== undefined && txn.memo !== null && txn.memo !== '', + category_id: txn.category_id, + }, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + async deleteTransaction( + budgetId: string, + transactionId: string + ): Promise { + this.assertWriteAllowed('deleteTransaction'); + await this.rateLimiter.acquire(); + + const auditLog = getAuditLog(); + try { + const response = await this.api.transactions.deleteTransaction(budgetId, transactionId); + // Redact PII from audit logs - payee_name may contain personal information + auditLog.log({ + operation: 'delete', + tool: 'ynab_delete_transaction', + budgetId, + resourceType: 'transaction', + resourceId: transactionId, + details: { + deleted_amount: response.data.transaction.amount, + deleted_date: response.data.transaction.date, + }, + success: true, + }); + return response; + } catch (error) { + auditLog.log({ + operation: 'delete', + tool: 'ynab_delete_transaction', + budgetId, + resourceType: 'transaction', + resourceId: transactionId, + details: {}, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + async importTransactions(budgetId: string): Promise { + this.assertWriteAllowed('importTransactions'); + await this.rateLimiter.acquire(); + + const auditLog = getAuditLog(); + try { + const response = await this.api.transactions.importTransactions(budgetId); + auditLog.log({ + operation: 'create', + tool: 'ynab_import_transactions', + budgetId, + resourceType: 'transaction', + details: { imported_count: response.data.transaction_ids.length }, + success: true, + }); + return response; + } catch (error) { + auditLog.log({ + operation: 'create', + tool: 'ynab_import_transactions', + budgetId, + resourceType: 'transaction', + details: {}, + success: false, + error: sanitizeErrorMessage(error), + }); + throw error; + } + } + + async getAccountTransactions( + budgetId: string, + accountId: string, + sinceDate?: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.transactions.getTransactionsByAccount(budgetId, accountId, sinceDate); + } + + async getCategoryTransactions( + budgetId: string, + categoryId: string, + sinceDate?: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.transactions.getTransactionsByCategory(budgetId, categoryId, sinceDate); + } + + async getPayeeTransactions( + budgetId: string, + payeeId: string, + sinceDate?: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.transactions.getTransactionsByPayee(budgetId, payeeId, sinceDate); + } + + // ==================== Scheduled Transactions ==================== + + async getScheduledTransactions(budgetId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.scheduledTransactions.getScheduledTransactions(budgetId); + } + + async getScheduledTransactionById( + budgetId: string, + scheduledTransactionId: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.scheduledTransactions.getScheduledTransactionById( + budgetId, + scheduledTransactionId + ); + } + + // Note: createScheduledTransaction is not available in the official YNAB JS SDK + // The API supports it but the SDK doesn't expose it + + // ==================== Payees ==================== + + async getPayees(budgetId: string): Promise { + const cacheKey = `payees:${budgetId}`; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) return cached; + + await this.rateLimiter.acquire(); + const response = await this.api.payees.getPayees(budgetId); + this.cache.set(cacheKey, response); + return response; + } + + async getPayeeById(budgetId: string, payeeId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.payees.getPayeeById(budgetId, payeeId); + } + + // ==================== Payee Locations ==================== + + async getPayeeLocations(budgetId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.payeeLocations.getPayeeLocations(budgetId); + } + + async getPayeeLocationById( + budgetId: string, + payeeLocationId: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.payeeLocations.getPayeeLocationById(budgetId, payeeLocationId); + } + + async getPayeeLocationsByPayee( + budgetId: string, + payeeId: string + ): Promise { + await this.rateLimiter.acquire(); + return this.api.payeeLocations.getPayeeLocationsByPayee(budgetId, payeeId); + } + + // ==================== Months ==================== + + async getBudgetMonths(budgetId: string): Promise { + await this.rateLimiter.acquire(); + return this.api.months.getBudgetMonths(budgetId); + } + + async getBudgetMonth(budgetId: string, month: string): Promise { + await this.rateLimiter.acquire(); + return this.api.months.getBudgetMonth(budgetId, month); + } +} diff --git a/src/tools/accounts/create-account.ts b/src/tools/accounts/create-account.ts new file mode 100644 index 0000000..695d89a --- /dev/null +++ b/src/tools/accounts/create-account.ts @@ -0,0 +1,117 @@ +/** + * Create Account Tool + * + * Creates a new account in a budget. + * + * Note: Currency formatting uses USD ($) symbols by default for display purposes. + * The underlying data is always stored in milliunits regardless of currency. + * To use the budget's actual currency format, use formatCurrencyWithFormat() + * with the budget's currency_format settings (requires additional API call). + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import * as ynab from 'ynab'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Derive account types from YNAB SDK enum to prevent drift +// AccountType enum has string values like 'checking', 'savings', etc. +const accountTypeValues = Object.values(ynab.AccountType).filter( + (v): v is ynab.AccountType => typeof v === 'string' +); + +// Input schema using nativeEnum for proper enum validation +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + name: z.string().min(1).max(100).describe('The name of the account'), + type: z + .nativeEnum(ynab.AccountType) + .describe('The type of account (checking, savings, creditCard, etc.)'), + balance: z + .number() + .finite() + .describe('The starting balance in dollars (e.g., 1000.50 for $1,000.50)'), +}); + +// Tool definition +export const createAccountTool: Tool = { + name: 'ynab_create_account', + description: `Create a new account in a budget. + +Use when the user asks: +- "Add a new checking account" +- "Create a savings account" +- "I want to add my credit card to YNAB" +- "Set up a new account with balance X" + +Account types: checking, savings, cash, creditCard, lineOfCredit, otherAsset, otherLiability, mortgage, autoLoan, studentLoan, personalLoan, medicalDebt, otherDebt + +Balance should be provided in dollars (e.g., 1000.50). For credit cards and debt accounts, use a negative balance for amounts owed.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + name: { + type: 'string', + description: 'The name of the account', + }, + type: { + type: 'string', + enum: accountTypeValues, + description: 'The type of account', + }, + balance: { + type: 'number', + description: 'The starting balance in dollars (e.g., 1000.50)', + }, + }, + required: ['name', 'type', 'balance'], + }, +}; + +// Handler function +/** + * Handler for the ynab_create_account tool. + */ +export async function handleCreateAccount( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.createAccount(budgetId, { + account: { + name: validated.name, + type: validated.type, + balance: toMilliunits(validated.balance), + }, + }); + + const account = response.data.account; + + const accountName = sanitizeName(account.name); + return JSON.stringify( + { + success: true, + message: `Account "${accountName}" created successfully`, + account: { + id: account.id, + name: accountName, + type: account.type, + balance: formatCurrency(account.balance), + on_budget: account.on_budget, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/accounts/get-account.ts b/src/tools/accounts/get-account.ts new file mode 100644 index 0000000..ad5f4c5 --- /dev/null +++ b/src/tools/accounts/get-account.ts @@ -0,0 +1,95 @@ +/** + * Get Account Tool + * + * Returns details about a specific account. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + account_id: z.string().uuid().describe('The account UUID to retrieve'), +}); + +// Tool definition +export const getAccountTool: Tool = { + name: 'ynab_get_account', + description: `Get details about a specific account including balance and recent activity. + +Use when the user asks: +- "Show me details for my checking account" +- "What's the balance of [account name]?" +- "Tell me about my savings account" +- "Get info on a specific account" + +Requires an account_id. Use ynab_list_accounts first to find the account ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + account_id: { + type: 'string', + format: 'uuid', + description: 'The account UUID to retrieve', + }, + }, + required: ['account_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_account tool. + */ +export async function handleGetAccount( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getAccountById(budgetId, validated.account_id); + const account = response.data.account; + + return JSON.stringify( + { + account: { + id: account.id, + name: sanitizeName(account.name), + type: account.type, + on_budget: account.on_budget, + closed: account.closed, + note: sanitizeMemo(account.note), + balance: formatCurrency(account.balance), + cleared_balance: formatCurrency(account.cleared_balance), + uncleared_balance: formatCurrency(account.uncleared_balance), + direct_import_linked: account.direct_import_linked, + direct_import_in_error: account.direct_import_in_error, + last_reconciled_at: account.last_reconciled_at, + debt_original_balance: + account.debt_original_balance != null + ? formatCurrency(account.debt_original_balance) + : null, + // Debt maps: Keys are month strings (YYYY-MM-DD format) from YNAB API, + // not user-controlled input. Values are numeric (milliunits for payments/escrow, + // basis points for rates). No sanitization needed as these contain no user strings. + debt_interest_rates: account.debt_interest_rates, + debt_minimum_payments: account.debt_minimum_payments, + debt_escrow_amounts: account.debt_escrow_amounts, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/accounts/list-accounts.ts b/src/tools/accounts/list-accounts.ts new file mode 100644 index 0000000..6409291 --- /dev/null +++ b/src/tools/accounts/list-accounts.ts @@ -0,0 +1,161 @@ +/** + * List Accounts Tool + * + * Returns all accounts in a budget with balances. + * + * Note: Currency formatting uses USD ($) symbols by default for display purposes. + * The underlying data is always stored in milliunits regardless of currency. + * To use the budget's actual currency format, use formatCurrencyWithFormat() + * with the budget's currency_format settings (requires additional API call). + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + include_closed: z + .boolean() + .optional() + .describe('Whether to include closed accounts'), +}); + +// Tool definition +export const listAccountsTool: Tool = { + name: 'ynab_list_accounts', + description: `List all accounts in a budget with their current balances. + +Use when the user asks: +- "What accounts do I have?" +- "Show my account balances" +- "What's my net worth?" +- "List my bank accounts" +- "How much money do I have?" + +Returns account names, types, and current/cleared/uncleared balances.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + include_closed: { + type: 'boolean', + description: 'Whether to include closed accounts', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_accounts tool. + */ +export async function handleListAccounts( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const includeClosed = validated.include_closed ?? false; + + const response = await client.getAccounts(budgetId); + let accounts = response.data.accounts; + + if (!includeClosed) { + accounts = accounts.filter((a) => !a.closed); + } + + // Group by account type + const byType: Record> = {}; + + for (const account of accounts) { + const type = account.type; + if (byType[type] === undefined) { + byType[type] = []; + } + byType[type].push({ + id: account.id, + name: sanitizeName(account.name), + balance: formatCurrency(account.balance), + cleared_balance: formatCurrency(account.cleared_balance), + uncleared_balance: formatCurrency(account.uncleared_balance), + closed: account.closed, + }); + } + + // Calculate totals + const assetTypes: string[] = ['checking', 'savings', 'cash', 'otherAsset']; + const liabilityTypes: string[] = [ + 'creditCard', + 'lineOfCredit', + 'otherLiability', + 'mortgage', + 'autoLoan', + 'studentLoan', + 'personalLoan', + 'medicalDebt', + 'otherDebt', + ]; + + const totalAssets = accounts + .filter((a) => assetTypes.includes(String(a.type))) + .reduce((sum, a) => sum + a.balance, 0); + + // Calculate liability totals properly: + // - Negative balances on liability accounts = actual debt + // - Positive balances on liability accounts = credits (overpayments) + const liabilityAccounts = accounts.filter((a) => + liabilityTypes.includes(String(a.type)) + ); + + // Sum only negative balances as liabilities (Math.min ensures we only count debt) + const totalLiabilities = liabilityAccounts.reduce( + (sum, a) => sum + Math.min(0, a.balance), + 0 + ); + + // Sum positive balances on liability accounts as credits + const totalLiabilityCredits = liabilityAccounts.reduce( + (sum, a) => sum + Math.max(0, a.balance), + 0 + ); + + // Net worth = assets + liability credits - abs(liabilities) + // Since totalLiabilities is negative (or zero), we add it + const netWorth = totalAssets + totalLiabilityCredits + totalLiabilities; + + return JSON.stringify( + { + accounts_by_type: byType, + summary: { + total_accounts: accounts.length, + total_assets: formatCurrency(totalAssets), + // Display liabilities as a positive number for readability + total_liabilities: formatCurrency(Math.abs(totalLiabilities)), + // Show credits on liability accounts if any exist + ...(totalLiabilityCredits > 0 && { + liability_credits: formatCurrency(totalLiabilityCredits), + }), + net_worth: formatCurrency(netWorth), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/age-of-money.ts b/src/tools/analytics/age-of-money.ts new file mode 100644 index 0000000..66a3116 --- /dev/null +++ b/src/tools/analytics/age-of-money.ts @@ -0,0 +1,156 @@ +/** + * Age of Money Tool + * + * Explains and tracks the Age of Money metric. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const ageOfMoneyTool: Tool = { + name: 'ynab_age_of_money', + description: `Get the Age of Money metric with explanation and tips. + +Use when the user asks: +- "What's my age of money?" +- "How old is my money?" +- "Explain age of money" +- "Am I living on last month's income?" +- "How long does my money last?" + +Returns the current age of money with context and improvement tips.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_age_of_money tool. + */ +export async function handleAgeOfMoney( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Get budget details and accounts + const [budgetResponse, accountsResponse] = await Promise.all([ + client.getBudgetById(budgetId), + client.getAccounts(budgetId), + ]); + + // Sort months by date (descending) to get the most recent month first + // YNAB API doesn't guarantee months array order + const months = budgetResponse.data.budget.months ?? []; + const sortedMonths = [...months].sort((a, b) => b.month.localeCompare(a.month)); + const ageOfMoney = sortedMonths[0]?.age_of_money ?? null; + + // Calculate cash on hand (budget accounts only) + const budgetAccounts = accountsResponse.data.accounts.filter( + (a) => a.on_budget && !a.deleted && !a.closed + ); + const cashOnHand = sumMilliunits(budgetAccounts.map((a) => a.balance)); + + // Determine status and message + let status: 'excellent' | 'good' | 'fair' | 'needs_work' | 'unknown'; + let message: string; + let target: string; + + if (ageOfMoney === null) { + status = 'unknown'; + message = 'Age of Money is not yet calculated. It requires at least 10 outflow transactions.'; + target = 'N/A'; + } else if (ageOfMoney >= 30) { + status = 'excellent'; + message = `Your money is ${ageOfMoney} days old - you're living on last month's income!`; + target = 'Maintain 30+ days'; + } else if (ageOfMoney >= 21) { + status = 'good'; + message = `Your money is ${ageOfMoney} days old - getting close to the 30-day goal!`; + target = 'Reach 30 days'; + } else if (ageOfMoney >= 14) { + status = 'fair'; + message = `Your money is ${ageOfMoney} days old - making progress!`; + target = 'Reach 21 days'; + } else { + status = 'needs_work'; + message = `Your money is ${ageOfMoney} days old - room for improvement.`; + target = 'Reach 14 days'; + } + + // Estimate days of buffer + // This is a rough estimate based on cash on hand and implied spending rate + let estimatedBuffer = 'Unknown'; + if (ageOfMoney !== null && ageOfMoney > 0) { + // If we have X days of age of money with Y cash, the daily rate is roughly Y / X + // But this is simplified - actual calculation is more complex + estimatedBuffer = `~${ageOfMoney} days`; + } + + return JSON.stringify( + { + status, + message, + age_of_money: ageOfMoney !== null ? `${ageOfMoney} days` : 'Not calculated yet', + age_of_money_raw: ageOfMoney, + target, + context: { + cash_on_hand: formatCurrency(cashOnHand), + budget_accounts: budgetAccounts.length, + estimated_buffer: estimatedBuffer, + }, + explanation: { + what_is_it: + 'Age of Money measures the average age of the dollars you spend. It shows how long money sits in your accounts before being spent.', + why_it_matters: + 'A higher Age of Money means you have more buffer between earning and spending. At 30+ days, you\'re spending last month\'s income, not this month\'s.', + how_calculated: + 'YNAB looks at the last 10 cash outflows and calculates how old those dollars were when spent, then averages them.', + }, + milestones: [ + { days: 7, meaning: 'One week buffer' }, + { days: 14, meaning: 'Two week buffer' }, + { days: 21, meaning: 'Three week buffer' }, + { days: 30, meaning: 'Living on last month\'s income - YNAB\'s goal!' }, + { days: 60, meaning: 'Two month buffer - excellent financial health' }, + { days: 90, meaning: 'Three month buffer - very secure' }, + ], + tips_to_improve: + ageOfMoney !== null && ageOfMoney < 30 + ? [ + 'Spend less than you earn each month', + 'Build up Ready to Assign instead of immediately budgeting everything', + 'Avoid using credit cards for cash-flow management', + 'Focus on reducing expenses in discretionary categories', + 'Consider a no-spend challenge to accelerate progress', + ] + : [ + 'Great job! Maintain your buffer by continuing to spend less than you earn', + 'Consider building additional savings goals', + 'Your buffer protects you from unexpected expenses', + ], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/budget-health.ts b/src/tools/analytics/budget-health.ts new file mode 100644 index 0000000..c981c4f --- /dev/null +++ b/src/tools/analytics/budget-health.ts @@ -0,0 +1,290 @@ +/** + * Budget Health Tool + * + * Provides an overall budget health assessment with key metrics and alerts. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const budgetHealthTool: Tool = { + name: 'ynab_budget_health', + description: `Get an overall budget health assessment. + +Use when the user asks: +- "How is my budget doing?" +- "What's my budget status?" +- "Am I on track this month?" +- "Budget health check" +- "Any budget problems?" + +Provides key metrics, alerts, and recommendations.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +interface HealthAlert { + severity: 'critical' | 'warning' | 'info'; + type: string; + message: string; + category?: string; + amount?: string; +} + +interface CategoryHealth { + name: string; + budgeted: string; + budgeted_milliunits: number; + spent: string; + spent_milliunits: number; + available: string; + available_milliunits: number; + status: 'on_track' | 'overspent' | 'underfunded' | 'warning'; + percent_used: number; +} + +// Handler function +/** + * Handler for the ynab_budget_health tool. + */ +export async function handleBudgetHealth( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Get current month (UTC-based for YNAB API consistency) + const currentMonth = getCurrentMonth(); + const now = new Date(); + + // Get budget data + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getCategories(budgetId), + ]); + + const month = monthResponse.data.month; + const alerts: HealthAlert[] = []; + const categoryHealth: CategoryHealth[] = []; + + // Key metrics + const toBeBudgeted = month.to_be_budgeted; + const totalBudgeted = month.budgeted; + const totalActivity = month.activity; + const totalIncome = month.income; + + // Alert: Money to be budgeted + if (toBeBudgeted > 0) { + alerts.push({ + severity: 'info', + type: 'unbudgeted_funds', + message: `You have ${formatCurrency(toBeBudgeted)} to be budgeted`, + amount: formatCurrency(toBeBudgeted), + }); + } else if (toBeBudgeted < 0) { + alerts.push({ + severity: 'critical', + type: 'overbudgeted', + message: `You've budgeted ${formatCurrency(Math.abs(toBeBudgeted))} more than you have available`, + amount: formatCurrency(Math.abs(toBeBudgeted)), + }); + } + + // Analyze categories + let totalOverspent = 0; + let overspentCount = 0; + let underfundedGoals = 0; + + for (const group of categoriesResponse.data.category_groups) { + // Skip internal categories + if (group.hidden || group.name === 'Internal Master Category') continue; + + for (const cat of group.categories) { + if (cat.hidden || cat.deleted) continue; + + const budgeted = cat.budgeted; + const activity = cat.activity; + const balance = cat.balance; + + // Determine status + let status: CategoryHealth['status'] = 'on_track'; + // Use absolute value of budgeted to handle negative budgets correctly + const percentUsed = + budgeted !== 0 ? Math.round((Math.abs(activity) / Math.abs(budgeted)) * 100) : 0; + + if (balance < 0) { + status = 'overspent'; + totalOverspent += Math.abs(balance); + overspentCount++; + + const safeCatName = sanitizeName(cat.name); + alerts.push({ + severity: 'warning', + type: 'overspent_category', + message: `${safeCatName} is overspent by ${formatCurrency(Math.abs(balance))}`, + category: safeCatName, + amount: formatCurrency(Math.abs(balance)), + }); + } else if (cat.goal_under_funded != null && cat.goal_under_funded > 0) { + status = 'underfunded'; + underfundedGoals++; + const underFunded = cat.goal_under_funded; + + const safeGoalName = sanitizeName(cat.name); + alerts.push({ + severity: 'info', + type: 'underfunded_goal', + message: `${safeGoalName} needs ${formatCurrency(underFunded)} more to meet goal`, + category: safeGoalName, + amount: formatCurrency(underFunded), + }); + } else if (percentUsed > 80 && balance > 0) { + status = 'warning'; + } + + // Add significant categories to health report + if (budgeted > 0 || Math.abs(activity) > 0) { + categoryHealth.push({ + name: sanitizeName(cat.name), + budgeted: formatCurrency(budgeted), + budgeted_milliunits: budgeted, + spent: formatCurrency(Math.abs(activity)), + spent_milliunits: Math.abs(activity), + available: formatCurrency(balance), + available_milliunits: balance, + status, + percent_used: percentUsed, + }); + } + } + } + + // Sort categories by status (problems first), then by amount spent (using raw milliunits) + const statusPriority = { overspent: 0, underfunded: 1, warning: 2, on_track: 3 }; + categoryHealth.sort((a, b) => { + const priorityDiff = statusPriority[a.status] - statusPriority[b.status]; + if (priorityDiff !== 0) return priorityDiff; + // Use raw milliunits for accurate numeric sorting + return b.spent_milliunits - a.spent_milliunits; + }); + + // Calculate overall health score (0-100) + let healthScore = 100; + + // Deductions + if (toBeBudgeted < 0) healthScore -= 30; // Overbudgeted + if (overspentCount > 0) healthScore -= Math.min(overspentCount * 10, 30); + if (underfundedGoals > 0) healthScore -= Math.min(underfundedGoals * 2, 10); + + healthScore = Math.max(0, healthScore); + + // Determine health status + let healthStatus: 'excellent' | 'good' | 'fair' | 'poor'; + if (healthScore >= 90) healthStatus = 'excellent'; + else if (healthScore >= 70) healthStatus = 'good'; + else if (healthScore >= 50) healthStatus = 'fair'; + else healthStatus = 'poor'; + + // Sort alerts by severity + const severityOrder = { critical: 0, warning: 1, info: 2 }; + alerts.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]); + + // Calculate days left in month + const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate(); + const dayOfMonth = now.getDate(); + const daysRemaining = daysInMonth - dayOfMonth; + const percentMonthComplete = Math.round((dayOfMonth / daysInMonth) * 100); + + return JSON.stringify( + { + health_score: healthScore, + health_status: healthStatus, + month: currentMonth, + alerts: alerts.slice(0, 10), // Top 10 alerts + key_metrics: { + to_be_budgeted: formatCurrency(toBeBudgeted), + total_budgeted: formatCurrency(totalBudgeted), + total_spent: formatCurrency(Math.abs(totalActivity)), + total_income: formatCurrency(totalIncome), + total_overspent: formatCurrency(totalOverspent), + overspent_category_count: overspentCount, + underfunded_goals_count: underfundedGoals, + }, + month_progress: { + days_remaining: daysRemaining, + percent_complete: percentMonthComplete, + daily_budget_remaining: + daysRemaining > 0 + ? formatCurrency(Math.round((totalBudgeted + totalActivity) / daysRemaining)) + : formatCurrency(totalBudgeted + totalActivity), // Last day: show remaining budget + daily_budget_remaining_milliunits: + daysRemaining > 0 + ? Math.round((totalBudgeted + totalActivity) / daysRemaining) + : totalBudgeted + totalActivity, + }, + category_health: categoryHealth.slice(0, 15), // Top 15 categories + recommendations: generateRecommendations(alerts, healthScore, toBeBudgeted), + }, + null, + 2 + ); +} + +function generateRecommendations( + alerts: HealthAlert[], + healthScore: number, + toBeBudgeted: number +): string[] { + const recommendations: string[] = []; + + const criticalAlerts = alerts.filter((a) => a.severity === 'critical'); + const overspentAlerts = alerts.filter((a) => a.type === 'overspent_category'); + + if (criticalAlerts.length > 0) { + recommendations.push( + 'Address critical issues first: reduce category budgets to fix overbudgeting' + ); + } + + if (overspentAlerts.length > 0) { + recommendations.push( + `Cover ${overspentAlerts.length} overspent categor${overspentAlerts.length === 1 ? 'y' : 'ies'} by moving money from other categories` + ); + } + + if (toBeBudgeted > 0) { + recommendations.push('Assign your available funds to categories or goals'); + } + + if (healthScore < 70) { + recommendations.push('Review your budget and spending to get back on track'); + } + + if (healthScore >= 90) { + recommendations.push('Great job! Your budget is in excellent shape'); + } + + return recommendations; +} diff --git a/src/tools/analytics/budget-suggestions.ts b/src/tools/analytics/budget-suggestions.ts new file mode 100644 index 0000000..a536881 --- /dev/null +++ b/src/tools/analytics/budget-suggestions.ts @@ -0,0 +1,314 @@ +/** + * Budget Suggestions Tool + * + * Suggests budget amounts based on historical spending patterns. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(1) + .max(12) + .optional() + .describe('Number of months of history to analyze (default 3)'), +}); + +// Tool definition +export const budgetSuggestionsTool: Tool = { + name: 'ynab_budget_suggestions', + description: `Suggest budget amounts based on historical spending. + +Use when the user asks: +- "How much should I budget for [category]?" +- "Suggest budget amounts" +- "What's a realistic budget?" +- "Help me set my budget" +- "Based on my spending, what should I budget?" + +Returns suggested monthly budget amounts for each category based on actual spending patterns.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'integer', + minimum: 1, + maximum: 12, + description: 'Number of months of history to analyze (1-12, default 3)', + }, + }, + required: [], + }, +}; + +interface CategorySuggestion { + category_name: string; + group_name: string; + current_budget: number; + suggested_budget: number; + average_spending: number; + max_spending: number; + min_spending: number; + recommendation: 'increase' | 'decrease' | 'maintain'; + confidence: 'high' | 'medium' | 'low'; +} + +// Handler function +/** + * Handler for the ynab_budget_suggestions tool. + */ +export async function handleBudgetSuggestions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const monthCount = validated.months ?? 3; + + // Generate list of months to analyze (excluding current month) + // Use UTC methods to avoid timezone drift when converting to ISO strings + const months: string[] = []; + const now = new Date(); + for (let i = 1; i <= monthCount; i++) { + const date = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1)); + const year = date.getUTCFullYear(); + const month = String(date.getUTCMonth() + 1).padStart(2, '0'); + months.push(`${year}-${month}-01`); + } + + // Get current month for current budget values (use UTC for consistency) + const currentMonth = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}-01`; + + // Fetch all data in parallel + // Note: For new budgets with insufficient history, some month fetches may fail. + // We use Promise.allSettled for historical months to gracefully handle this, + // allowing the tool to work with whatever history is available. + // Each promise result is paired with its month string to ensure correct alignment. + const [categoriesResponse, currentMonthResponse, ...historicalMonthResults] = + await Promise.all([ + client.getCategories(budgetId), + client.getBudgetMonth(budgetId, currentMonth), + ...months.map((m) => + client.getBudgetMonth(budgetId, m).then( + (response) => ({ status: 'fulfilled' as const, month: m, value: response }), + (error) => ({ status: 'rejected' as const, month: m, reason: error }) + ) + ), + ]); + + // Filter to only successful month fetches, extracting both values and months in single pass + const fulfilledResults = historicalMonthResults.filter( + (result): result is { status: 'fulfilled'; month: string; value: Awaited> } => + result.status === 'fulfilled' + ); + const historicalMonthResponses = fulfilledResults.map((result) => result.value); + const successfulMonths = fulfilledResults.map((result) => result.month); + + // If no historical data available, return early with helpful message + if (historicalMonthResponses.length === 0) { + return JSON.stringify( + { + error: false, + message: 'Insufficient budget history for suggestions. This tool requires at least one month of historical data.', + analysis_period: { + months_requested: monthCount, + months_available: 0, + months: [], + }, + tips: [ + 'Budget suggestions require historical spending data', + 'Try again after using YNAB for at least one full month', + 'You can also manually review your spending patterns in YNAB', + ], + }, + null, + 2 + ); + } + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Build current budget lookup + const currentBudgetLookup = new Map(); + for (const cat of currentMonthResponse.data.month.categories) { + currentBudgetLookup.set(cat.id, cat.budgeted); + } + + // Collect spending data by category + const spendingData = new Map< + string, + { name: string; group: string; spending: number[] } + >(); + + for (const monthResponse of historicalMonthResponses) { + for (const cat of monthResponse.data.month.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + // Only count outflows (spending) + const spending = cat.activity < 0 ? Math.abs(cat.activity) : 0; + + if (!spendingData.has(cat.id)) { + spendingData.set(cat.id, { + name: cat.name, + group: groupName, + spending: [], + }); + } + + spendingData.get(cat.id)!.spending.push(spending); + } + } + + // Calculate suggestions + const suggestions: CategorySuggestion[] = []; + + for (const [catId, data] of spendingData) { + // Skip categories with no spending history + if (data.spending.length === 0) continue; + + const avgSpending = sumMilliunits(data.spending) / data.spending.length; + const maxSpending = Math.max(...data.spending); + const minSpending = Math.min(...data.spending); + const currentBudget = currentBudgetLookup.get(catId) ?? 0; + + // Skip categories with no activity + if (avgSpending === 0 && currentBudget === 0) continue; + + // Calculate suggested budget: + // - Add 10% buffer to average spending for cushion + // - Round up to nearest $5 (5000 milliunits) for clean budget amounts + const BUFFER_MULTIPLIER = 1.1; // 10% buffer + const ROUND_TO_MILLIS = 5000; // $5.00 in milliunits (1000 milliunits = $1) + const suggestedRaw = avgSpending * BUFFER_MULTIPLIER; + const suggestedBudget = Math.ceil(suggestedRaw / ROUND_TO_MILLIS) * ROUND_TO_MILLIS; + + // Determine recommendation + let recommendation: 'increase' | 'decrease' | 'maintain'; + const difference = suggestedBudget - currentBudget; + const percentDiff = currentBudget > 0 ? (difference / currentBudget) * 100 : 100; + + if (percentDiff > 15) { + recommendation = 'increase'; + } else if (percentDiff < -15) { + recommendation = 'decrease'; + } else { + recommendation = 'maintain'; + } + + // Determine confidence based on spending consistency + const range = maxSpending - minSpending; + const rangePercent = avgSpending > 0 ? (range / avgSpending) * 100 : 0; + + let confidence: 'high' | 'medium' | 'low'; + if (data.spending.length >= 3 && rangePercent < 30) { + confidence = 'high'; + } else if (data.spending.length >= 2 && rangePercent < 60) { + confidence = 'medium'; + } else { + confidence = 'low'; + } + + suggestions.push({ + category_name: sanitizeName(data.name), + group_name: sanitizeName(data.group), + current_budget: currentBudget, + suggested_budget: suggestedBudget, + average_spending: avgSpending, + max_spending: maxSpending, + min_spending: minSpending, + recommendation, + confidence, + }); + } + + // Sort by difference (biggest gaps first) + suggestions.sort((a, b) => { + const aDiff = Math.abs(a.suggested_budget - a.current_budget); + const bDiff = Math.abs(b.suggested_budget - b.current_budget); + return bDiff - aDiff; + }); + + // Group by recommendation + const needsIncrease = suggestions.filter((s) => s.recommendation === 'increase'); + const canDecrease = suggestions.filter((s) => s.recommendation === 'decrease'); + const onTarget = suggestions.filter((s) => s.recommendation === 'maintain'); + + // Calculate total adjustments + const totalIncrease = sumMilliunits( + needsIncrease.map((s) => s.suggested_budget - s.current_budget) + ); + const totalDecrease = sumMilliunits( + canDecrease.map((s) => s.current_budget - s.suggested_budget) + ); + + return JSON.stringify( + { + analysis_period: { + months_requested: monthCount, + months_available: historicalMonthResponses.length, + months: successfulMonths, + }, + summary: { + categories_analyzed: suggestions.length, + needs_increase: needsIncrease.length, + can_decrease: canDecrease.length, + on_target: onTarget.length, + net_adjustment_needed: formatCurrency(totalIncrease - totalDecrease), + }, + needs_increase: needsIncrease.slice(0, 10).map((s) => ({ + category: s.category_name, + group: s.group_name, + current: formatCurrency(s.current_budget), + suggested: formatCurrency(s.suggested_budget), + average_spending: formatCurrency(s.average_spending), + increase_by: formatCurrency(s.suggested_budget - s.current_budget), + confidence: s.confidence, + })), + can_decrease: canDecrease.slice(0, 10).map((s) => ({ + category: s.category_name, + group: s.group_name, + current: formatCurrency(s.current_budget), + suggested: formatCurrency(s.suggested_budget), + average_spending: formatCurrency(s.average_spending), + decrease_by: formatCurrency(s.current_budget - s.suggested_budget), + confidence: s.confidence, + })), + on_target: onTarget.slice(0, 5).map((s) => ({ + category: s.category_name, + group: s.group_name, + current: formatCurrency(s.current_budget), + average_spending: formatCurrency(s.average_spending), + })), + tips: [ + 'Suggestions include a 10% buffer above average spending', + 'High confidence means consistent spending patterns', + 'Review low confidence suggestions more carefully', + 'Consider seasonal variations not captured in recent months', + ], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/budget-vs-actuals.ts b/src/tools/analytics/budget-vs-actuals.ts new file mode 100644 index 0000000..48aaea2 --- /dev/null +++ b/src/tools/analytics/budget-vs-actuals.ts @@ -0,0 +1,306 @@ +/** + * Budget vs Actuals Report Tool + * + * Compares budgeted amounts against actual spending for each category. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + month: z + .string() + .regex(/^\d{4}-(0[1-9]|1[0-2])-01$/, 'Month must be first-of-month format (YYYY-MM-01) with valid month (01-12)') + .optional() + .describe('Month to analyze in YYYY-MM-01 format (first of month). Defaults to current month'), + include_previous: z + .boolean() + .optional() + .describe('Include previous month for comparison (default false)'), +}); + +// Tool definition +export const budgetVsActualsTool: Tool = { + name: 'ynab_budget_vs_actuals', + description: `Compare budgeted amounts against actual spending for each category. + +Use when the user asks: +- "How am I doing on my budget?" +- "Am I over budget anywhere?" +- "Compare budget vs actual" +- "Which categories are overspent?" +- "Show my budget performance" + +Returns detailed budget vs actuals for all categories with variance analysis.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + month: { + type: 'string', + pattern: '^\\d{4}-(0[1-9]|1[0-2])-01$', + description: 'Month to analyze in YYYY-MM-01 format (first of month, 01-12). Defaults to current month', + }, + include_previous: { + type: 'boolean', + description: 'Include previous month for comparison', + }, + }, + required: [], + }, +}; + +interface CategoryReport { + category_name: string; + group_name: string; + budgeted: string; + activity: string; + available: string; + budgeted_raw: number; + activity_raw: number; + available_raw: number; + variance: string; + variance_percent: number | null; + status: 'on_track' | 'warning' | 'overspent' | 'underspent'; +} + +interface GroupReport { + group_name: string; + total_budgeted: string; + total_activity: string; + total_available: string; + categories: CategoryReport[]; +} + +// Handler function +/** + * Handler for the ynab_budget_vs_actuals tool. + */ +export async function handleBudgetVsActuals( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const month = validated.month ?? getCurrentMonth(); + + // Get month data and categories in parallel + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, month), + client.getCategories(budgetId), + ]); + + const monthData = monthResponse.data.month; + + // Build category group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Build reports by category group + const groupReports = new Map(); + const allCategories: CategoryReport[] = []; + + // Stats tracking + let totalBudgeted = 0; + let totalActivity = 0; + let overspentCount = 0; + let underspentCount = 0; + let onTrackCount = 0; + let warningCount = 0; + + for (const category of monthData.categories) { + const groupName = groupLookup.get(category.id) ?? 'Other'; + + // Skip hidden categories and internal master category + if (category.hidden || groupName === 'Internal Master Category') { + continue; + } + + const budgeted = category.budgeted; + // Only count negative activity (actual spending), ignore refunds + const activity = category.activity < 0 ? Math.abs(category.activity) : 0; + const available = category.balance; + + totalBudgeted += budgeted; + totalActivity += activity; + + // Calculate variance + const variance = budgeted - activity; + const variancePercent = budgeted !== 0 ? ((variance / budgeted) * 100) : null; + + // Determine status + let status: CategoryReport['status']; + if (available < 0) { + status = 'overspent'; + overspentCount++; + } else if (activity === 0 && budgeted > 0) { + status = 'underspent'; + underspentCount++; + } else if (variancePercent !== null && variancePercent > 50) { + status = 'underspent'; + underspentCount++; + } else if (variancePercent !== null && variancePercent < -10) { + status = 'warning'; + warningCount++; + } else { + status = 'on_track'; + onTrackCount++; + } + + const categoryReport: CategoryReport = { + category_name: sanitizeName(category.name), + group_name: sanitizeName(groupName), + budgeted: formatCurrency(budgeted), + activity: formatCurrency(activity), + available: formatCurrency(available), + budgeted_raw: budgeted, + activity_raw: activity, + available_raw: available, + variance: formatCurrency(variance), + variance_percent: variancePercent !== null ? Math.round(variancePercent) : null, + status, + }; + + allCategories.push(categoryReport); + + // Add to group + if (!groupReports.has(groupName)) { + groupReports.set(groupName, { + group_name: sanitizeName(groupName), + total_budgeted: formatCurrency(0), + total_activity: formatCurrency(0), + total_available: formatCurrency(0), + categories: [], + }); + } + + groupReports.get(groupName)!.categories.push(categoryReport); + } + + // Calculate group totals + for (const [, group] of groupReports) { + const groupBudgeted = group.categories.reduce((sum, c) => sum + c.budgeted_raw, 0); + const groupActivity = group.categories.reduce((sum, c) => sum + c.activity_raw, 0); + const groupAvailable = group.categories.reduce((sum, c) => sum + c.available_raw, 0); + + group.total_budgeted = formatCurrency(groupBudgeted); + group.total_activity = formatCurrency(groupActivity); + group.total_available = formatCurrency(groupAvailable); + + // Sort categories by activity (highest spending first) + group.categories.sort((a, b) => b.activity_raw - a.activity_raw); + } + + // Get overspent categories + const overspentCategories = allCategories + .filter((c) => c.status === 'overspent') + .sort((a, b) => a.available_raw - b.available_raw); + + // Get warning categories + const warningCategories = allCategories + .filter((c) => c.status === 'warning') + .sort((a, b) => a.available_raw - b.available_raw); + + // Optionally get previous month for comparison + let previousMonthComparison: { + month: string; + total_budgeted: string; + total_activity: string; + activity_change: string; + activity_change_percent: number; + } | null = null; + + if (validated.include_previous) { + // Calculate previous month relative to the input month, not today + const [yearStr, monthStr] = month.split('-'); + const inputYear = parseInt(yearStr ?? '2024', 10); + const inputMonth = parseInt(monthStr ?? '1', 10); + const prevYear = inputMonth === 1 ? inputYear - 1 : inputYear; + const prevMonthNum = inputMonth === 1 ? 12 : inputMonth - 1; + const prevMonth = `${prevYear}-${String(prevMonthNum).padStart(2, '0')}-01`; + const prevResponse = await client.getBudgetMonth(budgetId, prevMonth); + const prevData = prevResponse.data.month; + + let prevTotalBudgeted = 0; + let prevTotalActivity = 0; + + for (const category of prevData.categories) { + const prevGroupName = groupLookup.get(category.id) ?? 'Other'; + if (category.hidden || prevGroupName === 'Internal Master Category') { + continue; + } + prevTotalBudgeted += category.budgeted; + if (category.activity < 0) { + prevTotalActivity += Math.abs(category.activity); + } + } + + const activityChange = totalActivity - prevTotalActivity; + const activityChangePercent = prevTotalActivity !== 0 + ? ((activityChange / prevTotalActivity) * 100) + : 0; + + previousMonthComparison = { + month: prevMonth, + total_budgeted: formatCurrency(prevTotalBudgeted), + total_activity: formatCurrency(prevTotalActivity), + activity_change: formatCurrency(activityChange), + activity_change_percent: Math.round(activityChangePercent), + }; + } + + // Calculate overall budget health + const budgetUsagePercent = totalBudgeted !== 0 + ? Math.round((totalActivity / totalBudgeted) * 100) + : 0; + + return JSON.stringify( + { + month, + summary: { + total_budgeted: formatCurrency(totalBudgeted), + total_activity: formatCurrency(totalActivity), + budget_usage_percent: budgetUsagePercent, + overspent_categories: overspentCount, + warning_categories: warningCount, + on_track_categories: onTrackCount, + underspent_categories: underspentCount, + }, + alerts: { + overspent: overspentCategories.slice(0, 5).map((c) => ({ + category: c.category_name, + group: c.group_name, + overspent_by: formatCurrency(Math.abs(c.available_raw)), + })), + warnings: warningCategories.slice(0, 5).map((c) => ({ + category: c.category_name, + group: c.group_name, + remaining: c.available, + percent_used: c.variance_percent !== null ? 100 - c.variance_percent : null, + })), + }, + by_group: Array.from(groupReports.values()).sort((a, b) => + a.group_name.localeCompare(b.group_name) + ), + previous_month_comparison: previousMonthComparison, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/cash-flow-forecast.ts b/src/tools/analytics/cash-flow-forecast.ts new file mode 100644 index 0000000..fb6fc78 --- /dev/null +++ b/src/tools/analytics/cash-flow-forecast.ts @@ -0,0 +1,388 @@ +/** + * Cash Flow Forecast Tool + * + * Projects future cash flow based on scheduled transactions and spending patterns. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + days: z + .number() + .int() + .min(7) + .max(90) + .optional() + .describe('Number of days to forecast (default 30)'), +}); + +// Tool definition +export const cashFlowForecastTool: Tool = { + name: 'ynab_cash_flow_forecast', + description: `Project future cash flow based on scheduled transactions. + +Use when the user asks: +- "What's my cash flow forecast?" +- "Will I have enough money next month?" +- "What bills are coming up?" +- "Project my account balance" +- "When will I run low on money?" + +Returns projected cash flow including scheduled income and expenses.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + days: { + type: 'number', + description: 'Number of days to forecast (default 30)', + }, + }, + required: [], + }, +}; + +interface ScheduledItem { + date: string; + payee: string; + amount: number; + formatted_amount: string; + type: 'income' | 'expense'; + frequency: string; +} + +interface DailyForecast { + date: string; + scheduled_income: number; + scheduled_expenses: number; + net_change: number; + running_balance: number; +} + +// Handler function +/** + * Handler for the ynab_cash_flow_forecast tool. + */ +export async function handleCashFlowForecast( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const forecastDays = validated.days ?? 30; + + // Get accounts and scheduled transactions + const [accountsResponse, scheduledResponse] = await Promise.all([ + client.getAccounts(budgetId), + client.getScheduledTransactions(budgetId), + ]); + + // Calculate current cash position (budget accounts only) + const budgetAccounts = accountsResponse.data.accounts.filter( + (a) => a.on_budget && !a.deleted && !a.closed + ); + const currentCash = sumMilliunits(budgetAccounts.map((a) => a.balance)); + + // Set up date range using local dates to avoid UTC offset issues + // Normalize today to midnight to ensure same-day scheduled items are included + const today = new Date(); + today.setHours(0, 0, 0, 0); + const endDate = new Date(today); + endDate.setDate(endDate.getDate() + forecastDays); + + // Format as local date strings (YYYY-MM-DD) + const formatLocalDate = (d: Date): string => { + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; + }; + + const todayStr = formatLocalDate(today); + const endDateStr = formatLocalDate(endDate); + + // Process scheduled transactions + const scheduledItems: ScheduledItem[] = []; + const scheduled = scheduledResponse.data.scheduled_transactions.filter( + (st) => !st.deleted + ); + + // Frequency mapping + const frequencyLabels: Record = { + never: 'One-time', + daily: 'Daily', + weekly: 'Weekly', + everyOtherWeek: 'Bi-weekly', + twiceAMonth: 'Twice monthly', + every4Weeks: 'Every 4 weeks', + monthly: 'Monthly', + everyOtherMonth: 'Every 2 months', + every3Months: 'Quarterly', + every4Months: 'Every 4 months', + twiceAYear: 'Twice yearly', + yearly: 'Yearly', + everyOtherYear: 'Every 2 years', + }; + + // Helper to parse YYYY-MM-DD as local date + const parseLocalDate = (dateStr: string): Date => { + // Validate format before parsing + if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) { + throw new Error('Invalid date format in scheduled transaction'); + } + const parts = dateStr.split('-').map(Number) as [number, number, number]; + const [year, month, day] = parts; + if (isNaN(year) || isNaN(month) || isNaN(day)) { + throw new Error('Invalid date values in scheduled transaction'); + } + const date = new Date(year, month - 1, day); + // Verify date components match input (catches rollover from invalid values like month 99) + if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) { + throw new Error('Invalid date values in scheduled transaction'); + } + return date; + }; + + // Generate occurrences for each scheduled transaction + for (const st of scheduled) { + const nextDate = parseLocalDate(st.date_next); + if (nextDate > endDate) continue; + + // Add first occurrence if in range + if (nextDate >= today && nextDate <= endDate) { + const freqStr = String(st.frequency); + scheduledItems.push({ + date: st.date_next, + payee: sanitizeName(st.payee_name), + amount: st.amount, + formatted_amount: formatCurrency(st.amount), + type: st.amount >= 0 ? 'income' : 'expense', + frequency: frequencyLabels[freqStr] ?? freqStr, + }); + } + + // For recurring transactions, calculate additional occurrences + if (String(st.frequency) !== 'never') { + let currentDate = parseLocalDate(st.date_next); + const intervalDays = getIntervalDays(String(st.frequency)); + + if (intervalDays > 0) { + // Calculate max possible occurrences based on forecast period and interval + const maxOccurrences = Math.ceil(forecastDays / intervalDays) + 1; + for (let i = 0; i < maxOccurrences; i++) { + currentDate = new Date(currentDate); + currentDate.setDate(currentDate.getDate() + intervalDays); + + if (currentDate > endDate) break; + if (currentDate < today) continue; + + const freqStr = String(st.frequency); + scheduledItems.push({ + date: formatLocalDate(currentDate), + payee: sanitizeName(st.payee_name), + amount: st.amount, + formatted_amount: formatCurrency(st.amount), + type: st.amount >= 0 ? 'income' : 'expense', + frequency: frequencyLabels[freqStr] ?? freqStr, + }); + } + } + } + } + + // Sort by date + scheduledItems.sort((a, b) => a.date.localeCompare(b.date)); + + // Build daily forecast + const dailyForecasts: DailyForecast[] = []; + let runningBalance = currentCash; + + // Group scheduled items by date + const itemsByDate = new Map(); + for (const item of scheduledItems) { + if (!itemsByDate.has(item.date)) { + itemsByDate.set(item.date, []); + } + itemsByDate.get(item.date)!.push(item); + } + + // Generate daily forecast + const currentDate = new Date(today); + while (currentDate <= endDate) { + const dateStr = formatLocalDate(currentDate); + const items = itemsByDate.get(dateStr) ?? []; + + const scheduledIncome = sumMilliunits( + items.filter((i) => i.type === 'income').map((i) => i.amount) + ); + const scheduledExpenses = sumMilliunits( + items.filter((i) => i.type === 'expense').map((i) => Math.abs(i.amount)) + ); + const netChange = scheduledIncome - scheduledExpenses; + + runningBalance += netChange; + + // Only include days with activity or key milestone days + if (items.length > 0 || currentDate.getDate() === 1 || currentDate.getDate() === 15) { + dailyForecasts.push({ + date: dateStr, + scheduled_income: scheduledIncome, + scheduled_expenses: scheduledExpenses, + net_change: netChange, + running_balance: runningBalance, + }); + } + + currentDate.setDate(currentDate.getDate() + 1); + } + + // Calculate totals + const totalScheduledIncome = sumMilliunits( + scheduledItems.filter((i) => i.type === 'income').map((i) => i.amount) + ); + const totalScheduledExpenses = sumMilliunits( + scheduledItems.filter((i) => i.type === 'expense').map((i) => Math.abs(i.amount)) + ); + const netProjectedChange = totalScheduledIncome - totalScheduledExpenses; + const projectedEndBalance = currentCash + netProjectedChange; + + // Find low point + let lowestBalance = currentCash; + let lowestBalanceDate = todayStr; + let tempBalance = currentCash; + + for (const forecast of dailyForecasts) { + tempBalance = forecast.running_balance; + if (tempBalance < lowestBalance) { + lowestBalance = tempBalance; + lowestBalanceDate = forecast.date; + } + } + + // Determine status + let status: 'healthy' | 'caution' | 'warning'; + let message: string; + + if (lowestBalance < 0) { + status = 'warning'; + message = `Projected to go negative (${formatCurrency(lowestBalance)}) on ${lowestBalanceDate}`; + } else if (lowestBalance < currentCash * 0.2) { + status = 'caution'; + message = `Balance may drop to ${formatCurrency(lowestBalance)} on ${lowestBalanceDate}`; + } else { + status = 'healthy'; + message = 'Cash flow looks healthy for the forecast period'; + } + + // Upcoming expenses (next 7 days) + const upcomingDate = new Date(today); + upcomingDate.setDate(upcomingDate.getDate() + 7); + const upcomingExpenses = scheduledItems + .filter((i) => i.type === 'expense' && i.date <= formatLocalDate(upcomingDate)) + .slice(0, 10); + + // Upcoming income + const upcomingIncome = scheduledItems + .filter((i) => i.type === 'income') + .slice(0, 5); + + return JSON.stringify( + { + status, + message, + forecast_period: { + start: todayStr, + end: endDateStr, + days: forecastDays, + }, + current_position: { + cash_balance: formatCurrency(currentCash), + budget_accounts: budgetAccounts.length, + }, + projected: { + end_balance: formatCurrency(projectedEndBalance), + total_income: formatCurrency(totalScheduledIncome), + total_expenses: formatCurrency(totalScheduledExpenses), + net_change: formatCurrency(netProjectedChange), + lowest_balance: formatCurrency(lowestBalance), + lowest_balance_date: lowestBalanceDate, + }, + upcoming_expenses: upcomingExpenses.map((e) => ({ + date: e.date, + payee: e.payee, + amount: e.formatted_amount, + frequency: e.frequency, + })), + upcoming_income: upcomingIncome.map((i) => ({ + date: i.date, + payee: i.payee, + amount: i.formatted_amount, + frequency: i.frequency, + })), + daily_forecast: dailyForecasts.slice(0, 15).map((d) => ({ + date: d.date, + income: formatCurrency(d.scheduled_income), + expenses: formatCurrency(d.scheduled_expenses), + balance: formatCurrency(d.running_balance), + })), + scheduled_transaction_count: scheduledItems.length, + }, + null, + 2 + ); +} + +/** + * Get approximate interval in days for a recurring frequency. + * + * Note: These are approximations using fixed day counts. For example: + * - "monthly" uses 30 days, which causes slight drift over time + * - "twiceAMonth" uses 15 days, which doesn't match actual 1st/15th patterns + * - "yearly" uses 365 days, which doesn't account for leap years + * + * For short forecast periods (30-90 days), this approximation is acceptable. + * For longer periods, the actual scheduled transaction dates from YNAB + * should be used instead. + */ +function getIntervalDays(frequency: string): number { + switch (frequency) { + case 'daily': + return 1; + case 'weekly': + return 7; + case 'everyOtherWeek': + return 14; + case 'twiceAMonth': + return 15; + case 'every4Weeks': + return 28; + case 'monthly': + return 30; + case 'everyOtherMonth': + return 60; + case 'every3Months': + return 90; + case 'every4Months': + return 120; + case 'twiceAYear': + return 180; + case 'yearly': + return 365; + case 'everyOtherYear': + return 730; + default: + return 0; + } +} diff --git a/src/tools/analytics/category-balances.ts b/src/tools/analytics/category-balances.ts new file mode 100644 index 0000000..2b78321 --- /dev/null +++ b/src/tools/analytics/category-balances.ts @@ -0,0 +1,230 @@ +/** + * Category Balances Tool + * + * Quick check on category balances with optional filtering. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName, sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + filter: z + .enum(['all', 'funded', 'unfunded', 'negative', 'positive']) + .optional() + .describe('Filter categories by balance status (default: all)'), + group: z + .string() + .optional() + .describe('Filter by category group name (partial match)'), + search: z + .string() + .optional() + .describe('Search category names (partial match)'), +}); + +// Tool definition +export const categoryBalancesTool: Tool = { + name: 'ynab_category_balances', + description: `Check category balances with optional filtering. + +Use when the user asks: +- "What's my balance in [category]?" +- "How much do I have for groceries?" +- "Show category balances" +- "Which categories have money?" +- "What categories are negative?" + +Returns current category balances with filtering options.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + filter: { + type: 'string', + enum: ['all', 'funded', 'unfunded', 'negative', 'positive'], + description: 'Filter categories by balance status', + }, + group: { + type: 'string', + description: 'Filter by category group name (partial match)', + }, + search: { + type: 'string', + description: 'Search category names (partial match)', + }, + }, + required: [], + }, +}; + +interface CategoryBalance { + category_name: string; + group_name: string; + balance: number; + budgeted: number; + activity: number; + goal_target: number | null; +} + +// Handler function +/** + * Handler for the ynab_category_balances tool. + */ +export async function handleCategoryBalances( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const filter = validated.filter ?? 'all'; + const currentMonth = getCurrentMonth(); + + // Get month data and categories + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getCategories(budgetId), + ]); + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Process categories + let categories: CategoryBalance[] = []; + + for (const cat of monthResponse.data.month.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + categories.push({ + category_name: sanitizeName(cat.name), + group_name: sanitizeName(groupName), + balance: cat.balance, + budgeted: cat.budgeted, + activity: cat.activity, + goal_target: cat.goal_target ?? null, + }); + } + + // Apply group filter + if (validated.group) { + const groupSearch = validated.group.toLowerCase(); + categories = categories.filter((c) => + c.group_name.toLowerCase().includes(groupSearch) + ); + } + + // Apply name search + if (validated.search) { + const nameSearch = validated.search.toLowerCase(); + categories = categories.filter((c) => + c.category_name.toLowerCase().includes(nameSearch) + ); + } + + // Apply balance filter + switch (filter) { + case 'funded': + // Categories that have been budgeted this month (regardless of current balance) + categories = categories.filter((c) => c.budgeted > 0); + break; + case 'unfunded': + categories = categories.filter((c) => c.balance === 0 && c.budgeted === 0); + break; + case 'negative': + categories = categories.filter((c) => c.balance < 0); + break; + case 'positive': + // Categories with positive available balance + categories = categories.filter((c) => c.balance > 0); + break; + } + + // Sort by balance (highest first) + categories.sort((a, b) => b.balance - a.balance); + + // Calculate totals + const totalBalance = sumMilliunits(categories.map((c) => c.balance)); + const totalBudgeted = sumMilliunits(categories.map((c) => c.budgeted)); + const totalActivity = sumMilliunits(categories.map((c) => c.activity)); + + // Group by category group + const byGroup = new Map(); + for (const cat of categories) { + if (!byGroup.has(cat.group_name)) { + byGroup.set(cat.group_name, []); + } + byGroup.get(cat.group_name)!.push(cat); + } + + // Build group summaries with raw balance for sorting + const groupSummaries = Array.from(byGroup.entries()).map(([group, cats]) => { + const totalBalanceRaw = sumMilliunits(cats.map((c) => c.balance)); + return { + group, + category_count: cats.length, + total_balance: formatCurrency(totalBalanceRaw), + _rawBalance: totalBalanceRaw, + categories: cats.map((c) => ({ + name: c.category_name, + balance: formatCurrency(c.balance), + budgeted: formatCurrency(c.budgeted), + activity: formatCurrency(c.activity), + })), + }; + }); + + // Sort groups by total balance (using raw numeric value) + groupSummaries.sort((a, b) => b._rawBalance - a._rawBalance); + + // Build search description (sanitize user input) + const filterDesc: string[] = []; + if (filter !== 'all') filterDesc.push(`filter: ${filter}`); + if (validated.group) filterDesc.push(`group: "${sanitizeString(validated.group, 100) ?? ''}"`); + if (validated.search) filterDesc.push(`search: "${sanitizeString(validated.search, 100) ?? ''}"`); + + return JSON.stringify( + { + month: currentMonth, + filter: filterDesc.length > 0 ? filterDesc.join(', ') : 'none', + summary: { + categories_shown: categories.length, + total_balance: formatCurrency(totalBalance), + total_budgeted: formatCurrency(totalBudgeted), + total_activity: formatCurrency(totalActivity), + }, + by_group: groupSummaries.map(({ _rawBalance, ...rest }) => rest), + top_balances: categories.slice(0, 10).map((c) => ({ + category: c.category_name, + group: c.group_name, + balance: formatCurrency(c.balance), + budgeted: formatCurrency(c.budgeted), + })), + negative_balances: categories + .filter((c) => c.balance < 0) + .map((c) => ({ + category: c.category_name, + group: c.group_name, + balance: formatCurrency(c.balance), + })), + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/credit-card-status.ts b/src/tools/analytics/credit-card-status.ts new file mode 100644 index 0000000..29ed853 --- /dev/null +++ b/src/tools/analytics/credit-card-status.ts @@ -0,0 +1,218 @@ +/** + * Credit Card Status Tool + * + * Shows credit card account status and payment category balances. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import * as ynab from 'ynab'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const creditCardStatusTool: Tool = { + name: 'ynab_credit_card_status', + description: `Check credit card balances and payment category status. + +Use when the user asks: +- "What's my credit card balance?" +- "How much do I owe on credit cards?" +- "Credit card payment status" +- "Do I have enough to pay my credit cards?" +- "Show credit card accounts" + +Returns credit card balances with corresponding payment category balances.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +interface CreditCardInfo { + account_name: string; + balance: number; + cleared_balance: number; + uncleared_balance: number; + payment_category_balance: number; + payment_shortfall: number; + status: 'covered' | 'partial' | 'underfunded'; +} + +// Handler function +/** + * Handler for the ynab_credit_card_status tool. + */ +export async function handleCreditCardStatus( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const currentMonth = getCurrentMonth(); + + // Get accounts, categories, and month data + const [accountsResponse, categoriesResponse, monthResponse] = await Promise.all([ + client.getAccounts(budgetId), + client.getCategories(budgetId), + client.getBudgetMonth(budgetId, currentMonth), + ]); + + // Find credit card accounts + const creditCards = accountsResponse.data.accounts.filter( + (a) => a.type === ynab.AccountType.CreditCard && !a.deleted && !a.closed + ); + + if (creditCards.length === 0) { + return JSON.stringify( + { + status: 'no_credit_cards', + message: 'No active credit card accounts found', + credit_cards: [], + }, + null, + 2 + ); + } + + // Find Credit Card Payments category group + const ccPaymentGroup = categoriesResponse.data.category_groups.find( + (g) => g.name === 'Credit Card Payments' + ); + + // Build payment category lookup by name (YNAB names them after accounts) + const paymentCategoryLookup = new Map(); + + if (ccPaymentGroup) { + for (const cat of ccPaymentGroup.categories) { + paymentCategoryLookup.set(cat.name, { + id: cat.id, + balance: cat.balance, + }); + } + } + + // Also get balances from month data for current month values + const monthCategoryBalances = new Map(); + for (const cat of monthResponse.data.month.categories) { + monthCategoryBalances.set(cat.id, cat.balance); + } + + // Process credit cards + const cardInfos: CreditCardInfo[] = []; + + for (const card of creditCards) { + // Credit card balances are negative when you owe money, positive if overpaid + // Only treat negative balances as debt + const amountOwed = card.balance < 0 ? -card.balance : 0; + const clearedOwed = card.cleared_balance < 0 ? -card.cleared_balance : 0; + const unclearedOwed = card.uncleared_balance < 0 ? -card.uncleared_balance : 0; + + // Find corresponding payment category + const paymentCat = paymentCategoryLookup.get(card.name); + const paymentCategoryBalance = paymentCat + ? (monthCategoryBalances.get(paymentCat.id) ?? paymentCat.balance) + : 0; + + // Calculate shortfall (only if there's debt) + const shortfall = amountOwed - paymentCategoryBalance; + + // Determine status + let status: CreditCardInfo['status']; + if (amountOwed === 0 || paymentCategoryBalance >= amountOwed) { + status = 'covered'; + } else if (paymentCategoryBalance > 0) { + status = 'partial'; + } else { + status = 'underfunded'; + } + + cardInfos.push({ + account_name: sanitizeName(card.name), + balance: amountOwed, + cleared_balance: clearedOwed, + uncleared_balance: unclearedOwed, + payment_category_balance: paymentCategoryBalance, + payment_shortfall: shortfall > 0 ? shortfall : 0, + status, + }); + } + + // Sort by balance (highest first) + cardInfos.sort((a, b) => b.balance - a.balance); + + // Calculate totals + const totalBalance = sumMilliunits(cardInfos.map((c) => c.balance)); + const totalPaymentAvailable = sumMilliunits(cardInfos.map((c) => c.payment_category_balance)); + const totalShortfall = sumMilliunits(cardInfos.map((c) => c.payment_shortfall)); + + // Determine overall status + let overallStatus: 'all_covered' | 'some_covered' | 'underfunded'; + let overallMessage: string; + + const coveredCount = cardInfos.filter((c) => c.status === 'covered').length; + const underfundedCount = cardInfos.filter((c) => c.status === 'underfunded').length; + + if (coveredCount === cardInfos.length) { + overallStatus = 'all_covered'; + overallMessage = 'All credit card balances are covered by payment categories'; + } else if (underfundedCount === cardInfos.length) { + overallStatus = 'underfunded'; + overallMessage = `Need ${formatCurrency(totalShortfall)} more to cover all credit cards`; + } else { + overallStatus = 'some_covered'; + overallMessage = `${coveredCount} of ${cardInfos.length} cards fully covered`; + } + + return JSON.stringify( + { + status: overallStatus, + message: overallMessage, + month: currentMonth, + summary: { + total_cards: cardInfos.length, + total_balance: formatCurrency(totalBalance), + total_payment_available: formatCurrency(totalPaymentAvailable), + total_shortfall: formatCurrency(totalShortfall), + cards_covered: coveredCount, + cards_partial: cardInfos.filter((c) => c.status === 'partial').length, + cards_underfunded: underfundedCount, + }, + credit_cards: cardInfos.map((c) => ({ + account: c.account_name, + balance: formatCurrency(c.balance), + cleared: formatCurrency(c.cleared_balance), + pending: formatCurrency(c.uncleared_balance), + payment_available: formatCurrency(c.payment_category_balance), + shortfall: c.payment_shortfall > 0 ? formatCurrency(c.payment_shortfall) : null, + status: c.status, + })), + tips: + totalShortfall > 0 + ? [ + 'Assign funds to credit card payment categories to cover balances', + 'Payment categories auto-fill when you budget for credit card spending', + 'Pay at least the cleared balance to avoid interest', + ] + : ['All credit cards are covered - great job!'], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/detect-recurring.ts b/src/tools/analytics/detect-recurring.ts new file mode 100644 index 0000000..d333d53 --- /dev/null +++ b/src/tools/analytics/detect-recurring.ts @@ -0,0 +1,330 @@ +/** + * Detect Recurring Transactions Tool + * + * Identifies recurring payments/subscriptions by analyzing transaction patterns. + * Finds potential subscriptions that aren't in scheduled transactions. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; +import DecimalJS from 'decimal.js'; + +const Decimal = DecimalJS.default ?? DecimalJS; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(3) + .max(12) + .optional() + .describe('Number of months to analyze (default 6, min 3, max 12)'), + min_occurrences: z + .number() + .int() + .min(2) + .max(10) + .optional() + .describe('Minimum occurrences to consider recurring (default 3)'), +}); + +// Tool definition +export const detectRecurringTool: Tool = { + name: 'ynab_detect_recurring', + description: `Detect recurring transactions (subscriptions, bills) by analyzing transaction patterns. + +Use when the user asks: +- "What subscriptions do I have?" +- "Find my recurring bills" +- "What do I pay every month?" +- "Detect my regular payments" + +Analyzes transaction history to find patterns and estimates monthly costs.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'number', + description: 'Number of months to analyze (default 6)', + }, + min_occurrences: { + type: 'number', + description: 'Minimum occurrences to consider recurring (default 3)', + }, + }, + required: [], + }, +}; + +interface RecurringTransaction { + payee_name: string; + category_name: string | null; + frequency: 'weekly' | 'biweekly' | 'monthly' | 'quarterly' | 'annual' | 'irregular'; + average_amount: string; + last_date: string; + next_expected: string | null; + occurrence_count: number; + total_spent: string; + monthly_cost: string; + confidence: 'high' | 'medium' | 'low'; +} + +// Handler function +/** + * Handler for the ynab_detect_recurring tool. + */ +export async function handleDetectRecurring( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const months = validated.months ?? 6; + const minOccurrences = validated.min_occurrences ?? 3; + + // Calculate since_date using UTC to avoid timezone drift + const now = new Date(); + const sinceDate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - months, now.getUTCDate())); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + + // Get all transactions + const options: { sinceDate: string } = { sinceDate: sinceDateStr }; + const transactionsResponse = await client.getTransactions(budgetId, options); + + const transactions = transactionsResponse.data.transactions.filter( + (t) => t.amount < 0 && !t.deleted && !t.transfer_account_id // Only outflows, exclude transfers + ); + + // Group by payee + const byPayee = new Map< + string, + { + payee_name: string; + payee_id: string; + category_name: string | null; + transactions: { date: string; amount: number }[]; + } + >(); + + for (const txn of transactions) { + // Skip transactions without a payee_id - they can't be reliably grouped + // and would create false recurring detections if merged under a single key + if (!txn.payee_id) continue; + + const payeeId = txn.payee_id; + const payeeName = txn.payee_name ?? 'Unknown'; + + if (!byPayee.has(payeeId)) { + byPayee.set(payeeId, { + payee_name: payeeName, + payee_id: payeeId, + category_name: txn.category_name ?? null, + transactions: [], + }); + } + + byPayee.get(payeeId)!.transactions.push({ + date: txn.date, + amount: txn.amount, + }); + } + + // Analyze each payee for recurring patterns + const recurring: RecurringTransaction[] = []; + + for (const [, data] of byPayee) { + if (data.transactions.length < minOccurrences) continue; + + // Sort by date + data.transactions.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()); + + // Calculate intervals between transactions + const intervals: number[] = []; + for (let i = 1; i < data.transactions.length; i++) { + const current = data.transactions[i]; + const previous = data.transactions[i - 1]; + if (!current || !previous) continue; + const diff = + new Date(current.date).getTime() - + new Date(previous.date).getTime(); + intervals.push(Math.round(diff / (1000 * 60 * 60 * 24))); // Days + } + + if (intervals.length === 0) continue; + + // Calculate average interval and standard deviation + const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length; + const variance = + intervals.reduce((sum, val) => sum + Math.pow(val - avgInterval, 2), 0) / intervals.length; + const stdDev = Math.sqrt(variance); + + // Determine frequency and confidence + const { frequency, confidence } = classifyFrequency(avgInterval, stdDev); + + // Skip if too irregular + if (frequency === 'irregular' && confidence === 'low') continue; + + // Calculate amounts + const amounts = data.transactions.map((t) => Math.abs(t.amount)); + const totalSpent = sumMilliunits(amounts); + const avgAmount = new Decimal(totalSpent).dividedBy(data.transactions.length).toNumber(); + + // Calculate monthly cost + const monthlyCost = calculateMonthlyCost(avgAmount, frequency); + + // Predict next occurrence + const lastTxn = data.transactions[data.transactions.length - 1]; + if (!lastTxn) continue; + const lastDate = lastTxn.date; + const nextExpected = predictNextDate(lastDate, avgInterval); + + recurring.push({ + payee_name: sanitizeName(data.payee_name), + category_name: data.category_name ? sanitizeName(data.category_name) : null, + frequency, + average_amount: formatCurrency(avgAmount), + last_date: lastDate, + next_expected: nextExpected, + occurrence_count: data.transactions.length, + total_spent: formatCurrency(totalSpent), + monthly_cost: formatCurrency(monthlyCost), + confidence, + }); + } + + // Sort by monthly cost (highest first) + recurring.sort((a, b) => { + const costA = parseFloat(a.monthly_cost.replace(/[^0-9.-]/g, '')); + const costB = parseFloat(b.monthly_cost.replace(/[^0-9.-]/g, '')); + return costB - costA; + }); + + // Calculate totals + const totalMonthly = recurring.reduce((sum, r) => { + return sum + parseFloat(r.monthly_cost.replace(/[^0-9.-]/g, '')); + }, 0); + + const highConfidence = recurring.filter((r) => r.confidence === 'high'); + const mediumConfidence = recurring.filter((r) => r.confidence === 'medium'); + + return JSON.stringify( + { + recurring_transactions: recurring, + summary: { + total_recurring_found: recurring.length, + high_confidence_count: highConfidence.length, + medium_confidence_count: mediumConfidence.length, + estimated_monthly_total: formatCurrency(Math.round(totalMonthly * 1000)), + analysis_period: `${months} months`, + since_date: sinceDateStr, + }, + by_frequency: { + weekly: recurring.filter((r) => r.frequency === 'weekly').length, + biweekly: recurring.filter((r) => r.frequency === 'biweekly').length, + monthly: recurring.filter((r) => r.frequency === 'monthly').length, + quarterly: recurring.filter((r) => r.frequency === 'quarterly').length, + annual: recurring.filter((r) => r.frequency === 'annual').length, + irregular: recurring.filter((r) => r.frequency === 'irregular').length, + }, + }, + null, + 2 + ); +} + +function classifyFrequency( + avgInterval: number, + stdDev: number +): { frequency: RecurringTransaction['frequency']; confidence: RecurringTransaction['confidence'] } { + // Confidence based on consistency (lower stdDev = higher confidence) + // Guard against division by zero when avgInterval is 0 + const coefficientOfVariation = avgInterval > 0 ? stdDev / avgInterval : 0; + let confidence: RecurringTransaction['confidence']; + + if (coefficientOfVariation < 0.15) { + confidence = 'high'; + } else if (coefficientOfVariation < 0.35) { + confidence = 'medium'; + } else { + confidence = 'low'; + } + + // Classify frequency based on average interval + let frequency: RecurringTransaction['frequency']; + + if (avgInterval >= 5 && avgInterval <= 9) { + frequency = 'weekly'; + } else if (avgInterval >= 12 && avgInterval <= 17) { + frequency = 'biweekly'; + } else if (avgInterval >= 25 && avgInterval <= 35) { + frequency = 'monthly'; + } else if (avgInterval >= 80 && avgInterval <= 100) { + frequency = 'quarterly'; + } else if (avgInterval >= 340 && avgInterval <= 390) { + frequency = 'annual'; + } else { + frequency = 'irregular'; + } + + return { frequency, confidence }; +} + +function calculateMonthlyCost(avgAmount: number, frequency: RecurringTransaction['frequency']): number { + switch (frequency) { + case 'weekly': + return avgAmount * 4.33; // ~4.33 weeks per month + case 'biweekly': + return avgAmount * 2.17; + case 'monthly': + return avgAmount; + case 'quarterly': + return avgAmount / 3; + case 'annual': + return avgAmount / 12; + case 'irregular': + return avgAmount; // Assume monthly for irregular + default: + return avgAmount; + } +} + +function predictNextDate(lastDate: string, avgInterval: number): string | null { + // Parse lastDate as UTC to avoid timezone inconsistencies + // YNAB dates are in YYYY-MM-DD format + const [year, month, day] = lastDate.split('-').map(Number); + if (year === undefined || month === undefined || day === undefined) { + return null; + } + + const lastMs = Date.UTC(year, month - 1, day); + const intervalMs = avgInterval * 24 * 60 * 60 * 1000; + const nextMs = lastMs + intervalMs; + + const now = new Date(); + const todayMs = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()); + + // Only predict if in the future + if (nextMs > todayMs) { + return new Date(nextMs).toISOString().split('T')[0] ?? null; + } + + // If predicted date is in the past, add another interval + const nextNextMs = nextMs + intervalMs; + if (nextNextMs > todayMs) { + return new Date(nextNextMs).toISOString().split('T')[0] ?? null; + } + + return null; +} diff --git a/src/tools/analytics/goal-progress.ts b/src/tools/analytics/goal-progress.ts new file mode 100644 index 0000000..5c942b1 --- /dev/null +++ b/src/tools/analytics/goal-progress.ts @@ -0,0 +1,276 @@ +/** + * Goal Progress Tool + * + * Tracks progress on all category goals with projections. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"'), + filter: z + .enum(['all', 'on_track', 'behind', 'underfunded', 'complete']) + .optional() + .describe('Filter goals by status (default: all)'), +}); + +// Tool definition +export const goalProgressTool: Tool = { + name: 'ynab_goal_progress', + description: `Track progress on all category goals. + +Use when the user asks: +- "How are my goals doing?" +- "Show goal progress" +- "Which goals need more funding?" +- "Am I on track with my savings goals?" +- "What goals are behind?" + +Returns goal progress, funding status, and projections for each category with a goal.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + filter: { + type: 'string', + enum: ['all', 'on_track', 'behind', 'underfunded', 'complete'], + description: 'Filter goals by status', + }, + }, + required: [], + }, +}; + +interface GoalInfo { + category_name: string; + group_name: string; + goal_type: string; + goal_type_label: string; + target_amount: string | null; + target_date: string | null; + monthly_funding: string | null; + current_balance: string; + percent_complete: number | null; + underfunded: string; + underfunded_raw: number; + status: 'on_track' | 'behind' | 'underfunded' | 'complete'; + status_message: string; + days_until_target: number | null; +} + +// Goal type labels +const goalTypeLabels: Record = { + TB: 'Target Balance', + TBD: 'Target Balance by Date', + MF: 'Monthly Funding', + NEED: 'Spending Target', + DEBT: 'Debt Payoff', +}; + +// Handler function +/** + * Handler for the ynab_goal_progress tool. + */ +export async function handleGoalProgress( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const currentMonth = getCurrentMonth(); + const filter = validated.filter ?? 'all'; + + // Get month data and categories + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getCategories(budgetId), + ]); + + const monthData = monthResponse.data.month; + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Find categories with goals + const goalsInfo: GoalInfo[] = []; + + for (const category of monthData.categories) { + // Skip categories without goals or hidden categories + if (!category.goal_type || category.hidden) { + continue; + } + + const groupName = groupLookup.get(category.id) ?? 'Other'; + if (groupName === 'Internal Master Category') { + continue; + } + + const goalType = category.goal_type; + const targetAmount = category.goal_target ?? null; + const targetDate = category.goal_target_month ?? null; + const monthlyFunding = category.goal_cadence_frequency === 1 ? category.goal_target : null; + const underfunded = category.goal_under_funded ?? 0; + const balance = category.balance; + + // Calculate percent complete + let percentComplete: number | null = null; + if (targetAmount !== null && targetAmount > 0) { + percentComplete = Math.round((balance / targetAmount) * 100); + } + + // Calculate days until target (signed: positive = future, negative = past) + let daysUntilTarget: number | null = null; + if (targetDate) { + const todayDate = new Date(); + todayDate.setUTCHours(0, 0, 0, 0); + const targetDateObj = new Date(targetDate + 'T00:00:00Z'); + const diffMs = targetDateObj.getTime() - todayDate.getTime(); + daysUntilTarget = Math.round(diffMs / (1000 * 60 * 60 * 24)); + } + + // Determine status + let status: GoalInfo['status']; + let statusMessage: string; + + if (percentComplete !== null && percentComplete >= 100) { + status = 'complete'; + statusMessage = 'Goal fully funded'; + } else if (targetDate && daysUntilTarget !== null && daysUntilTarget <= 0) { + // Handle past-due goals explicitly + status = 'behind'; + if (daysUntilTarget === 0) { + statusMessage = `Due today, ${percentComplete ?? 0}% complete`; + } else { + const daysOverdue = Math.abs(daysUntilTarget); + statusMessage = `${daysOverdue} day${daysOverdue === 1 ? '' : 's'} overdue, ${percentComplete ?? 0}% complete`; + } + } else if (underfunded > 0) { + status = 'underfunded'; + statusMessage = `Needs ${formatCurrency(underfunded)} more this month`; + } else if (targetDate && daysUntilTarget !== null && daysUntilTarget < 30 && (percentComplete ?? 0) < 90) { + status = 'behind'; + statusMessage = `Only ${daysUntilTarget} days left, ${percentComplete ?? 0}% complete`; + } else { + status = 'on_track'; + statusMessage = 'On track'; + } + + const goalTypeStr = String(goalType); + goalsInfo.push({ + category_name: sanitizeName(category.name), + group_name: sanitizeName(groupName), + goal_type: goalTypeStr, + goal_type_label: goalTypeLabels[goalTypeStr] ?? goalTypeStr, + target_amount: targetAmount !== null ? formatCurrency(targetAmount) : null, + target_date: targetDate, + monthly_funding: monthlyFunding !== null && monthlyFunding !== undefined ? formatCurrency(monthlyFunding) : null, + current_balance: formatCurrency(balance), + percent_complete: percentComplete, + underfunded: formatCurrency(underfunded), + underfunded_raw: underfunded, + status, + status_message: statusMessage, + days_until_target: daysUntilTarget, + }); + } + + // Apply filter + let filteredGoals = goalsInfo; + if (filter !== 'all') { + filteredGoals = goalsInfo.filter((g) => g.status === filter); + } + + // Sort by status priority (underfunded first, then behind, then on_track, then complete) + const statusPriority: Record = { + underfunded: 0, + behind: 1, + on_track: 2, + complete: 3, + }; + filteredGoals.sort((a, b) => (statusPriority[a.status] ?? 99) - (statusPriority[b.status] ?? 99)); + + // Calculate summary stats + const totalUnderfunded = goalsInfo.reduce( + (sum, g) => sum + g.underfunded_raw, + 0 + ); + + const statusCounts = { complete: 0, on_track: 0, behind: 0, underfunded: 0 }; + for (const g of goalsInfo) { + statusCounts[g.status]++; + } + + // Determine overall status + let overallStatus: 'healthy' | 'attention_needed' | 'critical'; + let overallMessage: string; + + if (goalsInfo.length === 0) { + overallStatus = 'healthy'; + overallMessage = 'No goals configured'; + } else if (statusCounts.underfunded === 0 && statusCounts.behind === 0) { + overallStatus = 'healthy'; + overallMessage = 'All goals are on track or complete'; + } else if (statusCounts.underfunded > goalsInfo.length / 2) { + overallStatus = 'critical'; + overallMessage = `${statusCounts.underfunded} goals need funding`; + } else { + overallStatus = 'attention_needed'; + overallMessage = `${statusCounts.underfunded + statusCounts.behind} goals need attention`; + } + + return JSON.stringify( + { + status: overallStatus, + message: overallMessage, + month: currentMonth, + summary: { + total_goals: goalsInfo.length, + complete: statusCounts.complete, + on_track: statusCounts.on_track, + behind: statusCounts.behind, + underfunded: statusCounts.underfunded, + total_underfunded: formatCurrency(totalUnderfunded), + }, + goals: filteredGoals.map((g) => ({ + category: g.category_name, + group: g.group_name, + type: g.goal_type_label, + target: g.target_amount, + target_date: g.target_date, + balance: g.current_balance, + progress: g.percent_complete !== null ? `${g.percent_complete}%` : null, + underfunded: g.underfunded, + status: g.status, + status_message: g.status_message, + })), + filter_applied: filter, + tips: + statusCounts.underfunded > 0 + ? [ + `Fund ${statusCounts.underfunded} underfunded goals to stay on track`, + 'Consider adjusting goal targets if consistently underfunded', + 'Use Ready to Assign to cover underfunded goals', + ] + : [], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/income-expense.ts b/src/tools/analytics/income-expense.ts new file mode 100644 index 0000000..8a3cfc0 --- /dev/null +++ b/src/tools/analytics/income-expense.ts @@ -0,0 +1,252 @@ +/** + * Income vs Expense Tool + * + * Tracks income and expenses with month-over-month comparison. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(1) + .max(12) + .optional() + .describe('Number of months to analyze (default 6)'), +}); + +// Tool definition +export const incomeExpenseTool: Tool = { + name: 'ynab_income_expense', + description: `Track income vs expenses with monthly breakdown. + +Use when the user asks: +- "How much did I earn vs spend?" +- "What's my income vs expenses?" +- "Am I spending more than I make?" +- "Show my cash flow" +- "What's my savings rate?" + +Returns monthly income, expenses, net savings, and savings rate.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'integer', + description: 'Number of months to analyze (default 6)', + minimum: 1, + maximum: 12, + }, + }, + required: [], + }, +}; + +interface MonthData { + month: string; + income: string; + expenses: string; + net: string; + income_raw: number; + expenses_raw: number; + net_raw: number; + savings_rate: number | null; +} + +// Handler function +/** + * Handler for the ynab_income_expense tool. + */ +export async function handleIncomeExpense( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const monthsToAnalyze = validated.months ?? 6; + + // Calculate date range + const sinceDate = new Date(); + sinceDate.setDate(1); // Avoid overflow when subtracting months (e.g., Mar 31 - 1 month) + sinceDate.setMonth(sinceDate.getMonth() - monthsToAnalyze); + const sinceDateStr = sinceDate.toISOString().split('T')[0]; + if (!sinceDateStr) { + throw new Error('Failed to compute since date for income/expense analysis'); + } + + // Get transactions + const transactionsResponse = await client.getTransactions(budgetId, { + sinceDate: sinceDateStr, + }); + + const transactions = transactionsResponse.data.transactions.filter( + (t) => !t.deleted && !t.transfer_account_id + ); + + // Group by month + const byMonth = new Map(); + + for (const txn of transactions) { + const month = txn.date.substring(0, 7); // YYYY-MM + + if (!byMonth.has(month)) { + byMonth.set(month, { income: [], expenses: [] }); + } + + const monthData = byMonth.get(month)!; + + if (txn.amount > 0) { + monthData.income.push(txn.amount); + } else { + monthData.expenses.push(Math.abs(txn.amount)); + } + } + + // Build monthly data + const monthlyData: MonthData[] = []; + + for (const [month, data] of byMonth) { + const income = sumMilliunits(data.income); + const expenses = sumMilliunits(data.expenses); + const net = income - expenses; + const savingsRate = income > 0 ? ((income - expenses) / income) * 100 : null; + + monthlyData.push({ + month, + income: formatCurrency(income), + expenses: formatCurrency(expenses), + net: formatCurrency(net), + income_raw: income, + expenses_raw: expenses, + net_raw: net, + savings_rate: savingsRate !== null ? Math.round(savingsRate) : null, + }); + } + + // Sort by month + monthlyData.sort((a, b) => a.month.localeCompare(b.month)); + + // Calculate totals + const totalIncome = sumMilliunits(monthlyData.map((m) => m.income_raw)); + const totalExpenses = sumMilliunits(monthlyData.map((m) => m.expenses_raw)); + const totalNet = totalIncome - totalExpenses; + // When totalIncome is 0, savings_rate should be null (not 0%) + const overallSavingsRate = totalIncome > 0 ? ((totalIncome - totalExpenses) / totalIncome) * 100 : null; + + // Calculate averages + const avgIncome = monthlyData.length > 0 ? totalIncome / monthlyData.length : 0; + const avgExpenses = monthlyData.length > 0 ? totalExpenses / monthlyData.length : 0; + const avgNet = avgIncome - avgExpenses; + + // Calculate trend + let trend: 'improving' | 'declining' | 'stable' = 'stable'; + let trendMessage = 'Savings rate is stable'; + + if (monthlyData.length >= 2) { + const firstHalf = monthlyData.slice(0, Math.floor(monthlyData.length / 2)); + const secondHalf = monthlyData.slice(Math.floor(monthlyData.length / 2)); + + // Calculate savings rates, handling zero income explicitly + const firstHalfIncome = sumMilliunits(firstHalf.map((m) => m.income_raw)); + const secondHalfIncome = sumMilliunits(secondHalf.map((m) => m.income_raw)); + const firstHalfRate = firstHalfIncome > 0 + ? sumMilliunits(firstHalf.map((m) => m.net_raw)) / firstHalfIncome + : 0; + const secondHalfRate = secondHalfIncome > 0 + ? sumMilliunits(secondHalf.map((m) => m.net_raw)) / secondHalfIncome + : 0; + + // Only compare rates if both periods have income + if (firstHalfIncome > 0 && secondHalfIncome > 0) { + if (secondHalfRate > firstHalfRate + 0.05) { + trend = 'improving'; + trendMessage = 'Savings rate is improving'; + } else if (secondHalfRate < firstHalfRate - 0.05) { + trend = 'declining'; + trendMessage = 'Savings rate is declining'; + } + } + } + + // Determine status + let status: 'healthy' | 'warning' | 'concern'; + let statusMessage: string; + + // Handle zero-income case explicitly + if (overallSavingsRate === null) { + // No income in the period + if (totalExpenses > 0) { + status = 'concern'; + statusMessage = 'No income recorded, but expenses occurred'; + } else { + status = 'warning'; + statusMessage = 'No income or expenses recorded in this period'; + } + } else if (overallSavingsRate >= 20) { + status = 'healthy'; + statusMessage = 'Excellent savings rate (20%+)'; + } else if (overallSavingsRate >= 10) { + status = 'healthy'; + statusMessage = 'Good savings rate (10-20%)'; + } else if (overallSavingsRate >= 0) { + status = 'warning'; + statusMessage = 'Low savings rate (0-10%)'; + } else { + status = 'concern'; + statusMessage = 'Spending exceeds income'; + } + + return JSON.stringify( + { + status, + message: statusMessage, + trend, + trend_message: trendMessage, + period: { + months_analyzed: monthlyData.length, + since_date: sinceDateStr, + }, + totals: { + total_income: formatCurrency(totalIncome), + total_expenses: formatCurrency(totalExpenses), + net_savings: formatCurrency(totalNet), + savings_rate: overallSavingsRate !== null ? `${Math.round(overallSavingsRate)}%` : 'N/A', + }, + averages: { + avg_monthly_income: formatCurrency(avgIncome), + avg_monthly_expenses: formatCurrency(avgExpenses), + avg_monthly_net: formatCurrency(avgNet), + }, + monthly_breakdown: monthlyData.map((m) => ({ + month: m.month, + income: m.income, + expenses: m.expenses, + net: m.net, + savings_rate: m.savings_rate !== null ? `${m.savings_rate}%` : 'N/A', + })), + insights: { + best_month: monthlyData.length > 0 + ? monthlyData.reduce((best, m) => m.net_raw > best.net_raw ? m : best).month + : null, + worst_month: monthlyData.length > 0 + ? monthlyData.reduce((worst, m) => m.net_raw < worst.net_raw ? m : worst).month + : null, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/index.ts b/src/tools/analytics/index.ts new file mode 100644 index 0000000..22e8c9a --- /dev/null +++ b/src/tools/analytics/index.ts @@ -0,0 +1,28 @@ +/** + * Analytics Tools Index + * + * Exports all analytics-related tools. + */ + +export { detectRecurringTool, handleDetectRecurring } from './detect-recurring.js'; +export { spendingAnalysisTool, handleSpendingAnalysis } from './spending-analysis.js'; +export { budgetHealthTool, handleBudgetHealth } from './budget-health.js'; +export { savingsOpportunitiesTool, handleSavingsOpportunities } from './savings-opportunities.js'; +export { budgetVsActualsTool, handleBudgetVsActuals } from './budget-vs-actuals.js'; +export { quickSummaryTool, handleQuickSummary } from './quick-summary.js'; +export { incomeExpenseTool, handleIncomeExpense } from './income-expense.js'; +export { netWorthTool, handleNetWorth } from './net-worth.js'; +export { goalProgressTool, handleGoalProgress } from './goal-progress.js'; +export { spendingByPayeeTool, handleSpendingByPayee } from './spending-by-payee.js'; +export { unusedCategoriesTool, handleUnusedCategories } from './unused-categories.js'; +export { monthlyComparisonTool, handleMonthlyComparison } from './monthly-comparison.js'; +export { spendingTrendsTool, handleSpendingTrends } from './spending-trends.js'; +export { cashFlowForecastTool, handleCashFlowForecast } from './cash-flow-forecast.js'; +export { reconciliationHelperTool, handleReconciliationHelper } from './reconciliation-helper.js'; +export { budgetSuggestionsTool, handleBudgetSuggestions } from './budget-suggestions.js'; +export { overspendingAlertsTool, handleOverspendingAlerts } from './overspending-alerts.js'; +export { transactionSearchTool, handleTransactionSearch } from './transaction-search.js'; +export { spendingPaceTool, handleSpendingPace } from './spending-pace.js'; +export { categoryBalancesTool, handleCategoryBalances } from './category-balances.js'; +export { creditCardStatusTool, handleCreditCardStatus } from './credit-card-status.js'; +export { ageOfMoneyTool, handleAgeOfMoney } from './age-of-money.js'; diff --git a/src/tools/analytics/monthly-comparison.ts b/src/tools/analytics/monthly-comparison.ts new file mode 100644 index 0000000..f86e2bb --- /dev/null +++ b/src/tools/analytics/monthly-comparison.ts @@ -0,0 +1,312 @@ +/** + * Monthly Comparison Tool + * + * Compares this month vs previous month for key metrics. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth, getPreviousMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const monthlyComparisonTool: Tool = { + name: 'ynab_monthly_comparison', + description: `Compare this month vs last month for spending and budgeting. + +Use when the user asks: +- "How does this month compare to last month?" +- "Am I spending more or less?" +- "Month over month comparison" +- "Compare my spending" +- "What's changed since last month?" + +Returns side-by-side comparison of spending, income, and category performance.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +interface CategoryChange { + category: string; + group: string; + this_month: string; + last_month: string; + change: string; + change_percent: number | null; + direction: 'up' | 'down' | 'same' | 'new'; + rawChange: number; +} + +// Handler function +/** + * Handler for the ynab_monthly_comparison tool. + */ +export async function handleMonthlyComparison( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const currentMonth = getCurrentMonth(); + const previousMonth = getPreviousMonth(); + + // Get both months' data and categories + const [currentMonthResponse, previousMonthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getBudgetMonth(budgetId, previousMonth), + client.getCategories(budgetId), + ]); + + const currentData = currentMonthResponse.data.month; + const previousData = previousMonthResponse.data.month; + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Calculate overall metrics for current month + // Use the month's income field directly rather than summing category activity + const currentIncome = currentData.income ?? 0; + let currentSpending = 0; + let currentBudgeted = 0; + + for (const cat of currentData.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + currentBudgeted += cat.budgeted; + if (cat.activity < 0) { + currentSpending += Math.abs(cat.activity); + } + } + + // Calculate overall metrics for previous month + // Use the month's income field directly rather than summing category activity + const previousIncome = previousData.income ?? 0; + let previousSpending = 0; + let previousBudgeted = 0; + + for (const cat of previousData.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + previousBudgeted += cat.budgeted; + if (cat.activity < 0) { + previousSpending += Math.abs(cat.activity); + } + } + + // Build category comparison map + const categoryMap = new Map< + string, + { current: number; previous: number; name: string; group: string } + >(); + + for (const cat of currentData.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + categoryMap.set(cat.id, { + current: cat.activity < 0 ? Math.abs(cat.activity) : 0, + previous: 0, + name: sanitizeName(cat.name), + group: sanitizeName(groupName), + }); + } + + for (const cat of previousData.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + const existing = categoryMap.get(cat.id); + if (existing) { + existing.previous = cat.activity < 0 ? Math.abs(cat.activity) : 0; + } else { + categoryMap.set(cat.id, { + current: 0, + previous: cat.activity < 0 ? Math.abs(cat.activity) : 0, + name: sanitizeName(cat.name), + group: sanitizeName(groupName), + }); + } + } + + // Build category changes list + const categoryChanges: CategoryChange[] = []; + + for (const [, data] of categoryMap) { + if (data.current === 0 && data.previous === 0) continue; + + const change = data.current - data.previous; + + // Threshold of $10 (10000 milliunits) to avoid noise from minor fluctuations + const CHANGE_THRESHOLD = 10000; + let direction: 'up' | 'down' | 'same' | 'new'; + let changePercent: number | null; + + // Handle "new" category (no spending last month, spending this month) + if (data.previous === 0 && data.current > 0) { + direction = 'new'; + changePercent = null; + } else if (data.previous !== 0) { + changePercent = Math.round((change / data.previous) * 100); + if (change > CHANGE_THRESHOLD) { + direction = 'up'; + } else if (change < -CHANGE_THRESHOLD) { + direction = 'down'; + } else { + direction = 'same'; + } + } else { + // This branch handles: previous === 0 && current === 0 + // Due to the continue on line 163, this is unreachable, but included for completeness + direction = 'same'; + changePercent = null; + } + + categoryChanges.push({ + category: data.name, + group: data.group, + this_month: formatCurrency(data.current), + last_month: formatCurrency(data.previous), + change: direction === 'new' ? 'new' : formatCurrency(change), + change_percent: changePercent, + direction, + rawChange: change, + }); + } + + // Sort by absolute change (biggest changes first, using raw numeric value) + categoryChanges.sort((a, b) => Math.abs(b.rawChange) - Math.abs(a.rawChange)); + + // Calculate changes + const spendingChange = currentSpending - previousSpending; + // Handle previousSpending = 0 case: if current > 0, treat as 100% increase + const spendingChangePercent = + previousSpending !== 0 + ? ((spendingChange / previousSpending) * 100) + : currentSpending > 0 ? 100 : 0; + + const incomeChange = currentIncome - previousIncome; + // Guard against division by zero for income change percent + const incomeChangePercent = + previousIncome !== 0 + ? ((incomeChange / previousIncome) * 100) + : currentIncome > 0 ? 100 : 0; + const budgetedChange = currentBudgeted - previousBudgeted; + + // Determine overall status + let status: 'better' | 'worse' | 'similar'; + let message: string; + + // Special handling when previous month has no spending + if (previousSpending === 0) { + if (currentSpending === 0) { + status = 'similar'; + message = 'No spending in either month'; + } else { + status = 'worse'; + message = `Spending increased from $0 last month to ${formatCurrency(currentSpending)}`; + } + } else if (spendingChangePercent < -10) { + status = 'better'; + message = `Spending is down ${Math.abs(Math.round(spendingChangePercent))}% from last month`; + } else if (spendingChangePercent > 10) { + status = 'worse'; + message = `Spending is up ${Math.round(spendingChangePercent)}% from last month`; + } else { + status = 'similar'; + message = 'Spending is similar to last month'; + } + + // Get biggest increases and decreases (include 'new' in increases) + const biggestIncreases = categoryChanges + .filter((c) => c.direction === 'up' || c.direction === 'new') + .slice(0, 5); + const biggestDecreases = categoryChanges + .filter((c) => c.direction === 'down') + .slice(0, 5); + + return JSON.stringify( + { + status, + message, + months: { + current: currentMonth, + previous: previousMonth, + }, + comparison: { + spending: { + this_month: formatCurrency(currentSpending), + last_month: formatCurrency(previousSpending), + change: formatCurrency(spendingChange), + change_percent: Math.round(spendingChangePercent), + direction: spendingChange > 0 ? 'up' : spendingChange < 0 ? 'down' : 'same', + }, + income: { + this_month: formatCurrency(currentIncome), + last_month: formatCurrency(previousIncome), + change: formatCurrency(incomeChange), + change_percent: Math.round(incomeChangePercent), + direction: incomeChange > 0 ? 'up' : incomeChange < 0 ? 'down' : 'same', + }, + budgeted: { + this_month: formatCurrency(currentBudgeted), + last_month: formatCurrency(previousBudgeted), + change: formatCurrency(budgetedChange), + }, + }, + notable_changes: { + biggest_increases: biggestIncreases.map((c) => ({ + category: c.category, + group: c.group, + this_month: c.this_month, + last_month: c.last_month, + change: c.change, + change_percent: c.direction === 'new' ? 'new' : `+${c.change_percent}%`, + })), + biggest_decreases: biggestDecreases.map((c) => ({ + category: c.category, + group: c.group, + this_month: c.this_month, + last_month: c.last_month, + change: c.change, + change_percent: `${c.change_percent}%`, + })), + }, + insights: { + categories_with_increased_spending: categoryChanges.filter((c) => c.direction === 'up') + .length, + categories_with_decreased_spending: categoryChanges.filter((c) => c.direction === 'down') + .length, + categories_unchanged: categoryChanges.filter((c) => c.direction === 'same').length, + new_categories: categoryChanges.filter((c) => c.direction === 'new').length, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/net-worth.ts b/src/tools/analytics/net-worth.ts new file mode 100644 index 0000000..420e9f7 --- /dev/null +++ b/src/tools/analytics/net-worth.ts @@ -0,0 +1,228 @@ +/** + * Net Worth Tool + * + * Calculates net worth from all accounts including tracking accounts. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + include_closed: z + .boolean() + .optional() + .describe('Include closed accounts in calculation (default false)'), +}); + +// Tool definition +export const netWorthTool: Tool = { + name: 'ynab_net_worth', + description: `Calculate total net worth from all accounts. + +Use when the user asks: +- "What's my net worth?" +- "How much do I have in total?" +- "Show all my account balances" +- "What are my assets and liabilities?" + +Includes both budget accounts and tracking accounts (investments, property, etc.). +Returns breakdown by account type with total assets, liabilities, and net worth.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + include_closed: { + type: 'boolean', + description: 'Include closed accounts in calculation (default false)', + }, + }, + required: [], + }, +}; + +interface AccountSummary { + name: string; + type: string; + balance: string; + balance_raw: number; + on_budget: boolean; +} + +interface AccountTypeGroup { + type: string; + accounts: AccountSummary[]; + total: string; + total_raw: number; +} + +// Handler function +/** + * Handler for the ynab_net_worth tool. + */ +export async function handleNetWorth( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const includeClosed = validated.include_closed ?? false; + + // Get all accounts + const accountsResponse = await client.getAccounts(budgetId); + + // Filter accounts + let accounts = accountsResponse.data.accounts.filter((a) => !a.deleted); + if (!includeClosed) { + accounts = accounts.filter((a) => !a.closed); + } + + // Categorize account types + const assetTypes = new Set([ + 'checking', + 'savings', + 'cash', + 'otherAsset', + ]); + + const debtTypes = new Set([ + 'creditCard', + 'lineOfCredit', + 'mortgage', + 'autoLoan', + 'studentLoan', + 'personalLoan', + 'medicalDebt', + 'otherDebt', + 'otherLiability', + ]); + + // Group accounts by type + const byType = new Map(); + + for (const account of accounts) { + const typeStr = String(account.type); + + if (!byType.has(typeStr)) { + byType.set(typeStr, []); + } + + byType.get(typeStr)!.push({ + name: sanitizeName(account.name), + type: typeStr, + balance: formatCurrency(account.balance), + balance_raw: account.balance, + on_budget: account.on_budget, + }); + } + + // Build type groups + const typeGroups: AccountTypeGroup[] = []; + for (const [type, accts] of byType) { + const total = sumMilliunits(accts.map((a) => a.balance_raw)); + typeGroups.push({ + type, + accounts: accts.sort((a, b) => b.balance_raw - a.balance_raw), + total: formatCurrency(total), + total_raw: total, + }); + } + + // Sort by total (highest first for assets, lowest first for debts) + typeGroups.sort((a, b) => b.total_raw - a.total_raw); + + // Calculate totals + const budgetAccounts = accounts.filter((a) => a.on_budget); + const trackingAccounts = accounts.filter((a) => !a.on_budget); + + // Assets: Include all asset-type accounts (checking, savings, cash, otherAsset) + // plus tracking accounts with positive balances (investments, property, etc.) + // Note: Asset-type accounts with negative balances (overdrafts) are included + // in the filter but will have negative contribution to total assets. + // Tracking accounts with zero or negative balance are excluded from assets. + const assetAccounts = accounts.filter( + (a) => assetTypes.has(String(a.type)) || (!a.on_budget && a.balance > 0) + ); + // Sum all asset account balances (including negative overdrafts for accurate net worth) + const totalAssets = sumMilliunits( + assetAccounts.map((a) => a.balance) + ); + + // Liabilities (debt accounts + negative balances) + const debtAccounts = accounts.filter((a) => debtTypes.has(String(a.type))); + const totalLiabilities = sumMilliunits( + debtAccounts.map((a) => Math.abs(a.balance)) + ); + + // Net worth + const netWorth = sumMilliunits(accounts.map((a) => a.balance)); + + // Budget vs tracking breakdown + const budgetTotal = sumMilliunits(budgetAccounts.map((a) => a.balance)); + const trackingTotal = sumMilliunits(trackingAccounts.map((a) => a.balance)); + + // Determine status + let status: 'positive' | 'negative' | 'zero'; + let message: string; + + if (netWorth > 0) { + status = 'positive'; + message = 'Net worth is positive'; + } else if (netWorth < 0) { + status = 'negative'; + message = 'Net worth is negative - liabilities exceed assets'; + } else { + status = 'zero'; + message = 'Assets equal liabilities'; + } + + return JSON.stringify( + { + status, + message, + net_worth: formatCurrency(netWorth), + summary: { + total_assets: formatCurrency(totalAssets), + total_liabilities: formatCurrency(totalLiabilities), + net_worth: formatCurrency(netWorth), + }, + breakdown: { + budget_accounts: { + count: budgetAccounts.length, + total: formatCurrency(budgetTotal), + }, + tracking_accounts: { + count: trackingAccounts.length, + total: formatCurrency(trackingTotal), + }, + }, + by_account_type: typeGroups.map((g) => ({ + type: g.type, + total: g.total, + accounts: g.accounts.map((a) => ({ + name: a.name, + balance: a.balance, + on_budget: a.on_budget, + })), + })), + account_count: { + total: accounts.length, + budget: budgetAccounts.length, + tracking: trackingAccounts.length, + closed_excluded: includeClosed ? 0 : accountsResponse.data.accounts.filter((a) => a.closed && !a.deleted).length, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/overspending-alerts.ts b/src/tools/analytics/overspending-alerts.ts new file mode 100644 index 0000000..00ccf18 --- /dev/null +++ b/src/tools/analytics/overspending-alerts.ts @@ -0,0 +1,190 @@ +/** + * Overspending Alerts Tool + * + * Quick check for categories that are currently overspent. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Threshold for minor vs significant overspending (in milliunits, $50 = 50000) +const MINOR_OVERSPEND_THRESHOLD_MILLIS = 50000; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + threshold: z + .number() + .optional() + .describe('Minimum overspend amount to report in dollars (default 0)'), +}); + +// Tool definition +export const overspendingAlertsTool: Tool = { + name: 'ynab_overspending_alerts', + description: `Check for categories that are currently overspent. + +Use when the user asks: +- "Am I overspending?" +- "What categories are over budget?" +- "Any overspending alerts?" +- "Where am I in the red?" +- "Check my budget status" + +Returns a quick list of all overspent categories with amounts.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + threshold: { + type: 'number', + description: 'Minimum overspend amount to report in dollars (default 0)', + }, + }, + required: [], + }, +}; + +interface OverspentCategory { + category_name: string; + group_name: string; + budgeted: number; + activity: number; + overspent: number; + percent_over: number; +} + +// Handler function +/** + * Handler for the ynab_overspending_alerts tool. + */ +export async function handleOverspendingAlerts( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const thresholdMilliunits = toMilliunits(validated.threshold ?? 0); + + const currentMonth = getCurrentMonth(); + + // Get month data and categories + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getCategories(budgetId), + ]); + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Find overspent categories + const overspent: OverspentCategory[] = []; + + for (const cat of monthResponse.data.month.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + // Check for overspending using YNAB's available balance + // A negative balance means the category is overspent + if (cat.balance < 0 && Math.abs(cat.balance) >= thresholdMilliunits) { + const overspentAmount = Math.abs(cat.balance); + const budgeted = cat.budgeted; + const spending = cat.activity < 0 ? Math.abs(cat.activity) : 0; + const percentOver = budgeted > 0 ? (overspentAmount / budgeted) * 100 : 100; + + overspent.push({ + category_name: sanitizeName(cat.name), + group_name: sanitizeName(groupName), + budgeted: budgeted, + activity: spending, + overspent: overspentAmount, + percent_over: percentOver, + }); + } + } + + // Sort by overspent amount (highest first) + overspent.sort((a, b) => b.overspent - a.overspent); + + // Calculate totals + const totalOverspent = overspent.reduce((sum, c) => sum + c.overspent, 0); + const totalBudgeted = overspent.reduce((sum, c) => sum + c.budgeted, 0); + const totalSpending = overspent.reduce((sum, c) => sum + c.activity, 0); + + // Determine status + let status: 'all_clear' | 'minor_overspend' | 'significant_overspend'; + let message: string; + + if (overspent.length === 0) { + status = 'all_clear'; + message = 'No overspending detected this month'; + } else if (totalOverspent < MINOR_OVERSPEND_THRESHOLD_MILLIS) { + status = 'minor_overspend'; + message = `${overspent.length} category(ies) slightly over budget`; + } else { + status = 'significant_overspend'; + message = `${overspent.length} category(ies) over budget by ${formatCurrency(totalOverspent)} total`; + } + + // Group by category group + const byGroup = new Map(); + for (const cat of overspent) { + if (!byGroup.has(cat.group_name)) { + byGroup.set(cat.group_name, []); + } + byGroup.get(cat.group_name)!.push(cat); + } + + return JSON.stringify( + { + status, + message, + month: currentMonth, + summary: { + overspent_categories: overspent.length, + total_overspent: formatCurrency(totalOverspent), + total_budgeted_in_overspent: formatCurrency(totalBudgeted), + total_spent_in_overspent: formatCurrency(totalSpending), + }, + alerts: overspent.map((c) => ({ + category: c.category_name, + group: c.group_name, + budgeted: formatCurrency(c.budgeted), + spent: formatCurrency(c.activity), + over_by: formatCurrency(c.overspent), + percent_over: `${Math.round(c.percent_over)}%`, + })), + by_group: Array.from(byGroup.entries()).map(([group, cats]) => ({ + group, + count: cats.length, + total_over: formatCurrency(cats.reduce((sum, c) => sum + c.overspent, 0)), + categories: cats.map((c) => c.category_name), + })), + suggestions: + overspent.length > 0 + ? [ + 'Move funds from other categories to cover overspending', + 'Check if overspending can be offset by underspending elsewhere', + 'Consider adjusting future budgets based on actual needs', + ] + : [], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/quick-summary.ts b/src/tools/analytics/quick-summary.ts new file mode 100644 index 0000000..50fa799 --- /dev/null +++ b/src/tools/analytics/quick-summary.ts @@ -0,0 +1,184 @@ +/** + * Quick Summary Tool + * + * Provides an at-a-glance overview of budget status and key metrics. + */ + +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; +import { z } from 'zod'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const quickSummaryTool: Tool = { + name: 'ynab_quick_summary', + description: `Get a quick at-a-glance summary of the budget status. + +Use when the user asks: +- "How's my budget looking?" +- "Give me a quick overview" +- "What's my financial status?" +- "Summary of my finances" +- "How much money do I have?" + +Returns key metrics: available funds, spending this month, account balances, and alerts. +This is the best tool to use for general budget status questions.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_quick_summary tool. + */ +export async function handleQuickSummary( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const currentMonth = getCurrentMonth(); + + // Get all the data we need in parallel + const [monthResponse, accountsResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getAccounts(budgetId), + ]); + + const monthData = monthResponse.data.month; + const accounts = accountsResponse.data.accounts.filter((a) => !a.closed && !a.deleted); + + // Calculate total available (Ready to Assign) + const readyToAssign = monthData.to_be_budgeted; + + // Calculate account balances by type + const debtTypes = new Set(['mortgage', 'autoLoan', 'studentLoan', 'personalLoan', 'medicalDebt', 'otherDebt']); + const creditTypes = new Set(['creditCard', 'lineOfCredit']); + const cashTypes = new Set(['checking', 'savings', 'cash']); + + const budgetAccounts = accounts.filter( + (a) => a.on_budget && !debtTypes.has(String(a.type)) && !creditTypes.has(String(a.type)) + ); + const trackingAccounts = accounts.filter((a) => !a.on_budget); + const debtAccounts = accounts.filter( + (a) => a.on_budget && (creditTypes.has(String(a.type)) || debtTypes.has(String(a.type))) + ); + + const totalBudgetAccountBalance = sumMilliunits(budgetAccounts.map((a) => a.balance)); + const totalTrackingBalance = sumMilliunits(trackingAccounts.map((a) => a.balance)); + const totalDebt = sumMilliunits(debtAccounts.map((a) => Math.abs(a.balance))); + + // Calculate this month's spending (negative activity) + const thisMonthActivity = sumMilliunits( + monthData.categories + .filter((c) => c.activity < 0 && !c.hidden) + .map((c) => Math.abs(c.activity)) + ); + + // Get overspent categories + const overspentCategories = monthData.categories + .filter((c) => c.balance < 0 && !c.hidden) + .map((c) => ({ + name: sanitizeName(c.name), + overspent_by: formatCurrency(Math.abs(c.balance)), + })); + + // Get underfunded goals + const underfundedGoals = monthData.categories + .filter((c) => (c.goal_under_funded ?? 0) > 0 && !c.hidden) + .map((c) => ({ + name: sanitizeName(c.name), + needed: formatCurrency(c.goal_under_funded ?? 0), + })) + .slice(0, 5); + + // Check for low balance accounts + const lowBalanceAccounts = budgetAccounts + .filter((a) => a.balance < 10000 && a.balance >= 0) + .map((a) => ({ + name: sanitizeName(a.name), + balance: formatCurrency(a.balance), + })); + + // Determine overall status + let overallStatus: 'healthy' | 'warning' | 'attention_needed'; + let statusMessage: string; + + if (overspentCategories.length > 0) { + overallStatus = 'attention_needed'; + statusMessage = `${overspentCategories.length} categories are overspent`; + } else if (readyToAssign < 0) { + overallStatus = 'attention_needed'; + statusMessage = 'Ready to Assign is negative - need to cover overspending'; + } else if (underfundedGoals.length > 3) { + overallStatus = 'warning'; + statusMessage = 'Several goals need more funding'; + } else { + overallStatus = 'healthy'; + statusMessage = 'Budget is on track'; + } + + return JSON.stringify( + { + status: overallStatus, + message: statusMessage, + month: currentMonth, + key_metrics: { + ready_to_assign: formatCurrency(readyToAssign), + spent_this_month: formatCurrency(thisMonthActivity), + total_in_budget_accounts: formatCurrency(totalBudgetAccountBalance), + total_debt: formatCurrency(totalDebt), + total_in_tracking_accounts: formatCurrency(totalTrackingBalance), + age_of_money: monthData.age_of_money != null ? `${monthData.age_of_money} days` : null, + }, + alerts: { + overspent_categories: overspentCategories.length > 0 ? overspentCategories.slice(0, 5) : null, + underfunded_goals: underfundedGoals.length > 0 ? underfundedGoals : null, + low_balance_accounts: lowBalanceAccounts.length > 0 ? lowBalanceAccounts : null, + }, + account_summary: { + checking_savings: budgetAccounts + .filter((a) => cashTypes.has(String(a.type))) + .map((a) => ({ name: sanitizeName(a.name), balance: formatCurrency(a.balance) })), + debt_accounts: debtAccounts.map((a) => ({ + name: sanitizeName(a.name), + balance: formatCurrency(a.balance), + })), + }, + tips: + overallStatus !== 'healthy' + ? [ + overspentCategories.length > 0 + ? 'Move money from other categories to cover overspending' + : null, + readyToAssign < 0 + ? 'Unassign money from categories to fix negative Ready to Assign' + : null, + underfundedGoals.length > 0 + ? 'Consider adjusting goals or finding more money to fund them' + : null, + ].filter(Boolean) + : [], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/reconciliation-helper.ts b/src/tools/analytics/reconciliation-helper.ts new file mode 100644 index 0000000..d882715 --- /dev/null +++ b/src/tools/analytics/reconciliation-helper.ts @@ -0,0 +1,262 @@ +/** + * Reconciliation Helper Tool + * + * Shows uncleared transactions to help with account reconciliation. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"'), + account_id: z + .string() + .uuid() + .optional() + .describe('Specific account UUID to check (optional, shows all if not specified)'), +}).strict(); + +// Tool definition +export const reconciliationHelperTool: Tool = { + name: 'ynab_reconciliation_helper', + description: `Help with account reconciliation by showing uncleared transactions. + +Use when the user asks: +- "Help me reconcile my accounts" +- "What transactions haven't cleared?" +- "Show uncleared transactions" +- "Pending transactions" +- "Reconciliation status" + +Returns uncleared transactions organized by account with totals.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + account_id: { + type: 'string', + format: 'uuid', + description: 'Specific account ID to check (optional)', + }, + }, + required: [], + additionalProperties: false, + }, +}; + +interface UnclearedTransaction { + date: string; + payee: string; + category: string | null; + amount: string; + amount_raw: number; + memo: string | null; + days_pending: number; +} + +interface AccountReconciliation { + account_name: string; + account_type: string; + cleared_balance: string; + uncleared_balance: string; + working_balance: string; + uncleared_count: number; + uncleared_transactions: UnclearedTransaction[]; + oldest_uncleared: string | null; +} + +// Handler function +/** + * Handler for the ynab_reconciliation_helper tool. + */ +export async function handleReconciliationHelper( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Get accounts and transactions (limit to last 90 days for reconciliation) + const lookbackDays = 90; + const sinceDate = new Date(); + sinceDate.setDate(sinceDate.getDate() - lookbackDays); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + + const [accountsResponse, transactionsResponse, categoriesResponse] = await Promise.all([ + client.getAccounts(budgetId), + client.getTransactions(budgetId, { sinceDate: sinceDateStr }), + client.getCategories(budgetId), + ]); + + // Build category lookup + const categoryLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + categoryLookup.set(cat.id, cat.name); + } + } + + // Filter accounts + let accounts = accountsResponse.data.accounts.filter( + (a) => !a.deleted && !a.closed + ); + + if (validated.account_id) { + accounts = accounts.filter((a) => a.id === validated.account_id); + if (accounts.length === 0) { + throw new Error('Account not found for provided account_id'); + } + } + + // Get today for calculating days pending + const today = new Date(); + + // Group uncleared transactions by account + const accountData = new Map(); + + for (const account of accounts) { + accountData.set(account.id, { + account_name: sanitizeName(account.name), + account_type: String(account.type), + cleared_balance: formatCurrency(account.cleared_balance), + uncleared_balance: formatCurrency(account.uncleared_balance), + working_balance: formatCurrency(account.balance), + uncleared_count: 0, + uncleared_transactions: [], + oldest_uncleared: null, + }); + } + + // Process transactions + const transactions = transactionsResponse.data.transactions.filter( + (t) => !t.deleted && String(t.cleared) !== 'reconciled' && String(t.cleared) !== 'cleared' + ); + + for (const txn of transactions) { + const accountInfo = accountData.get(txn.account_id); + if (!accountInfo) continue; + + // Calculate days pending (clamp to 0 for future-dated transactions) + const txnDate = new Date(txn.date); + const daysPending = Math.max( + 0, + Math.floor((today.getTime() - txnDate.getTime()) / (1000 * 60 * 60 * 24)) + ); + + const unclearedTxn: UnclearedTransaction = { + date: txn.date, + payee: sanitizeName(txn.payee_name ?? ''), + category: txn.category_id + ? (categoryLookup.get(txn.category_id) + ? sanitizeName(categoryLookup.get(txn.category_id)!) + : null) + : null, + amount: formatCurrency(txn.amount), + amount_raw: txn.amount, + memo: sanitizeMemo(txn.memo), + days_pending: daysPending, + }; + + accountInfo.uncleared_transactions.push(unclearedTxn); + accountInfo.uncleared_count++; + + // Track oldest uncleared + if (!accountInfo.oldest_uncleared || txn.date < accountInfo.oldest_uncleared) { + accountInfo.oldest_uncleared = txn.date; + } + } + + // Sort transactions by date (oldest first) for each account + for (const [, info] of accountData) { + info.uncleared_transactions.sort((a, b) => a.date.localeCompare(b.date)); + } + + // Convert to array and filter out accounts with no uncleared transactions (unless specific account requested) + let accountResults = Array.from(accountData.values()); + if (!validated.account_id) { + accountResults = accountResults.filter((a) => a.uncleared_count > 0); + } + + // Sort by uncleared count (most first) + accountResults.sort((a, b) => b.uncleared_count - a.uncleared_count); + + // Calculate totals from all active accounts + const activeAccountIds = new Set(accountData.keys()); + const activeAccountTransactions = transactions.filter((t) => activeAccountIds.has(t.account_id)); + const totalUncleared = sumMilliunits(activeAccountTransactions.map((t) => t.amount)); + const totalUnclearedCount = activeAccountTransactions.length; + + // Find accounts needing attention (old uncleared transactions) + const needsAttention = accountResults.filter((a) => { + if (!a.oldest_uncleared) return false; + const oldestDate = new Date(a.oldest_uncleared); + const daysPending = Math.floor( + (today.getTime() - oldestDate.getTime()) / (1000 * 60 * 60 * 24) + ); + return daysPending > 7; + }); + + // Determine status + let status: 'up_to_date' | 'needs_attention' | 'overdue'; + let message: string; + + if (totalUnclearedCount === 0) { + status = 'up_to_date'; + message = 'All transactions are cleared or reconciled'; + } else if (needsAttention.length > 0) { + status = 'overdue'; + message = `${needsAttention.length} account(s) have transactions pending over a week`; + } else { + status = 'needs_attention'; + message = `${totalUnclearedCount} transaction(s) pending across ${accountResults.length} account(s)`; + } + + return JSON.stringify( + { + status, + message, + summary: { + lookback_days: lookbackDays, + since_date: sinceDateStr, + accounts_with_uncleared: accountResults.filter((a) => a.uncleared_count > 0).length, + total_uncleared_transactions: totalUnclearedCount, + total_uncleared_amount: formatCurrency(totalUncleared), + accounts_needing_attention: needsAttention.length, + }, + accounts: accountResults.map((a) => ({ + account: a.account_name, + type: a.account_type, + cleared_balance: a.cleared_balance, + uncleared_balance: a.uncleared_balance, + working_balance: a.working_balance, + uncleared_count: a.uncleared_count, + oldest_pending: a.oldest_uncleared, + transactions: a.uncleared_transactions.slice(0, 10).map((t) => ({ + date: t.date, + payee: t.payee, + category: t.category, + amount: t.amount, + days_pending: t.days_pending, + memo: t.memo, + })), + })), + tips: [ + 'Mark transactions as cleared when they appear on your bank statement', + 'Reconcile accounts regularly to catch discrepancies early', + 'Transactions pending over 7 days may need investigation', + ], + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/savings-opportunities.ts b/src/tools/analytics/savings-opportunities.ts new file mode 100644 index 0000000..175ae6c --- /dev/null +++ b/src/tools/analytics/savings-opportunities.ts @@ -0,0 +1,359 @@ +/** + * Savings Opportunities Tool + * + * Identifies potential areas where the user could save money. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; +import DecimalJS from 'decimal.js'; + +const Decimal = DecimalJS.default ?? DecimalJS; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(2) + .max(12) + .optional() + .describe('Number of months to analyze (default 3)'), +}); + +// Tool definition +export const savingsOpportunitiesTool: Tool = { + name: 'ynab_savings_opportunities', + description: `Find potential savings opportunities based on spending patterns. + +Use when the user asks: +- "How can I save money?" +- "Where can I cut back?" +- "What are my unnecessary expenses?" +- "Help me reduce spending" +- "Find savings opportunities" + +Analyzes spending to identify areas where cuts might be possible.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'number', + description: 'Number of months to analyze (2-12, default 3)', + minimum: 2, + maximum: 12, + }, + }, + required: [], + }, +}; + +interface SavingsOpportunity { + type: + | 'recurring_expense' + | 'high_variance' + | 'discretionary' + | 'underused_subscription' + | 'large_single'; + category: string; + description: string; + potential_monthly_savings: string; + potential_monthly_savings_milliunits: number; + current_monthly_spend: string; + current_monthly_spend_milliunits: number; + suggestion: string; + confidence: 'high' | 'medium' | 'low'; +} + +// Discretionary categories (common ones that can often be reduced) +const DISCRETIONARY_CATEGORIES = [ + 'dining', + 'restaurant', + 'eating out', + 'entertainment', + 'streaming', + 'subscriptions', + 'shopping', + 'clothes', + 'clothing', + 'coffee', + 'alcohol', + 'bars', + 'hobbies', + 'games', + 'personal care', + 'gifts', +]; + +// Handler function +/** + * Handler for the ynab_savings_opportunities tool. + */ +export async function handleSavingsOpportunities( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const months = validated.months ?? 3; + + // Calculate since_date - pin to day 1 to avoid month overflow on 29th-31st + const sinceDate = new Date(); + sinceDate.setDate(1); // Pin to first of month before subtracting + sinceDate.setMonth(sinceDate.getMonth() - months); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + const options: { sinceDate: string } = { sinceDate: sinceDateStr }; + + // Get data + const [transactionsResponse, categoriesResponse] = await Promise.all([ + client.getTransactions(budgetId, options), + client.getCategories(budgetId), + ]); + + // Build category lookup + const categoryLookup = new Map< + string, + { name: string; group: string; isDiscretionary: boolean } + >(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + const lowerName = cat.name.toLowerCase(); + const lowerGroup = group.name.toLowerCase(); + const isDiscretionary = DISCRETIONARY_CATEGORIES.some( + (d) => lowerName.includes(d) || lowerGroup.includes(d) + ); + categoryLookup.set(cat.id, { + name: cat.name, + group: group.name, + isDiscretionary, + }); + } + } + + // Filter outflows + const transactions = transactionsResponse.data.transactions.filter( + (t) => t.amount < 0 && !t.deleted && !t.transfer_account_id + ); + + const opportunities: SavingsOpportunity[] = []; + + // Group by category and payee + const byCategory = new Map< + string, + { + amounts: number[]; + byMonth: Map; + byPayee: Map; + } + >(); + + for (const txn of transactions) { + const categoryId = txn.category_id ?? 'uncategorized'; + const month = txn.date.substring(0, 7); + const payeeId = txn.payee_id ?? 'unknown'; + + if (!byCategory.has(categoryId)) { + byCategory.set(categoryId, { + amounts: [], + byMonth: new Map(), + byPayee: new Map(), + }); + } + + const catData = byCategory.get(categoryId)!; + catData.amounts.push(Math.abs(txn.amount)); + + if (!catData.byMonth.has(month)) { + catData.byMonth.set(month, []); + } + catData.byMonth.get(month)!.push(Math.abs(txn.amount)); + + if (!catData.byPayee.has(payeeId)) { + catData.byPayee.set(payeeId, []); + } + catData.byPayee.get(payeeId)!.push(Math.abs(txn.amount)); + } + + // Analyze each category + for (const [categoryId, data] of byCategory) { + const lookup = categoryLookup.get(categoryId) ?? { + name: 'Uncategorized', + group: 'Other', + isDiscretionary: false, + }; + const safeCategory = sanitizeName(lookup.name); + + const total = sumMilliunits(data.amounts); + const monthlyAvg = total / months; + + // 1. High discretionary spending + if (lookup.isDiscretionary && monthlyAvg > 5000) { + // More than $50/month + const potentialSavings = Math.round(monthlyAvg * 0.2); // Suggest 20% reduction + opportunities.push({ + type: 'discretionary', + category: safeCategory, + description: `Discretionary spending on ${safeCategory}`, + potential_monthly_savings: formatCurrency(potentialSavings), + potential_monthly_savings_milliunits: potentialSavings, + current_monthly_spend: formatCurrency(monthlyAvg), + current_monthly_spend_milliunits: Math.round(monthlyAvg), + suggestion: `Consider reducing ${safeCategory} spending by 20%`, + confidence: 'medium', + }); + } + + // 2. High variance - inconsistent spending might have waste + const monthlyTotals = Array.from(data.byMonth.values()).map((amounts) => + sumMilliunits(amounts) + ); + if (monthlyTotals.length >= 2) { + const avgMonthly = + monthlyTotals.reduce((a, b) => a + b, 0) / monthlyTotals.length; + const maxMonthly = Math.max(...monthlyTotals); + const variance = maxMonthly - avgMonthly; + + if (variance > avgMonthly * 0.5 && avgMonthly > 10000) { + // High variance and significant spend + const potentialSavings = Math.round(variance * 0.3); // Could save 30% of variance + opportunities.push({ + type: 'high_variance', + category: safeCategory, + description: `Inconsistent spending on ${safeCategory} - some months much higher`, + potential_monthly_savings: formatCurrency(potentialSavings), + potential_monthly_savings_milliunits: potentialSavings, + current_monthly_spend: formatCurrency(avgMonthly), + current_monthly_spend_milliunits: Math.round(avgMonthly), + suggestion: `Your ${safeCategory} spending varies significantly. Setting a fixed budget could help.`, + confidence: 'low', + }); + } + } + + // 3. Look for recurring small expenses (potential subscriptions) + for (const [payeeId, payeeAmounts] of data.byPayee) { + if (payeeAmounts.length >= 2) { + // Check if amounts are consistent (subscription-like) + const avg = new Decimal(sumMilliunits(payeeAmounts)) + .dividedBy(payeeAmounts.length) + .toNumber(); + const allSimilar = payeeAmounts.every( + (a) => Math.abs(a - avg) < avg * 0.1 // Within 10% of average + ); + + const firstAmount = payeeAmounts[0]; + if (allSimilar && avg > 500 && avg < 50000 && firstAmount !== undefined) { + // $5-$500 range (likely subscription) + // Find the payee name using the specific payeeId + const txn = transactions.find( + (t) => + t.category_id === categoryId && + (t.payee_id ?? 'unknown') === payeeId + ); + const payeeName = sanitizeName(txn?.payee_name ?? 'Unknown'); + if (payeeName === 'Unknown') continue; // Skip unknown payees - not actionable + const avgRounded = Math.round(avg); + + opportunities.push({ + type: 'recurring_expense', + category: safeCategory, + description: `Recurring charge: ${payeeName}`, + potential_monthly_savings: formatCurrency(avgRounded), + potential_monthly_savings_milliunits: avgRounded, + current_monthly_spend: formatCurrency(avgRounded), + current_monthly_spend_milliunits: avgRounded, + suggestion: `Review if you still need ${payeeName}. Cancel if unused.`, + confidence: 'high', + }); + } + } + } + + // 4. Large single transactions + const largeTransactions = data.amounts.filter((a) => a > 100000); // Over $100 + if (largeTransactions.length > 0) { + const monthlyImpact = sumMilliunits(largeTransactions) / months; + + if (monthlyImpact > 20000 && lookup.isDiscretionary) { + const potentialSavings = Math.round(monthlyImpact * 0.3); + opportunities.push({ + type: 'large_single', + category: safeCategory, + description: `Large purchases in ${safeCategory}`, + potential_monthly_savings: formatCurrency(potentialSavings), + potential_monthly_savings_milliunits: potentialSavings, + current_monthly_spend: formatCurrency(monthlyImpact), + current_monthly_spend_milliunits: Math.round(monthlyImpact), + suggestion: `Review large ${safeCategory} purchases. Consider waiting periods before big buys.`, + confidence: 'low', + }); + } + } + } + + // Deduplicate and sort by potential savings + const seen = new Set(); + const deduped = opportunities.filter((o) => { + const key = `${o.type}-${o.category}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + + // Sort by potential savings using raw milliunits for accurate numeric sorting + deduped.sort((a, b) => { + return b.potential_monthly_savings_milliunits - a.potential_monthly_savings_milliunits; + }); + + // Calculate totals using raw milliunits for accuracy + const totalPotentialSavingsMilliunits = deduped.reduce((sum, o) => { + return sum + o.potential_monthly_savings_milliunits; + }, 0); + + const totalCurrentSpend = sumMilliunits(transactions.map((t) => Math.abs(t.amount))) / months; + + const highConfidenceOpportunities = deduped.filter((o) => o.confidence === 'high'); + const highConfidenceSavingsMilliunits = highConfidenceOpportunities.reduce((sum, o) => { + return sum + o.potential_monthly_savings_milliunits; + }, 0); + + return JSON.stringify( + { + opportunities: deduped.slice(0, 15), // Top 15 opportunities + summary: { + total_opportunities_found: deduped.length, + total_potential_monthly_savings: formatCurrency(totalPotentialSavingsMilliunits), + total_potential_monthly_savings_milliunits: totalPotentialSavingsMilliunits, + high_confidence_savings: formatCurrency(highConfidenceSavingsMilliunits), + high_confidence_savings_milliunits: highConfidenceSavingsMilliunits, + current_monthly_spend: formatCurrency(totalCurrentSpend), + current_monthly_spend_milliunits: Math.round(totalCurrentSpend), + potential_savings_percent: + totalCurrentSpend > 0 + ? Math.round((totalPotentialSavingsMilliunits / totalCurrentSpend) * 100) + : 0, + analysis_period: `${months} months`, + }, + quick_wins: highConfidenceOpportunities.slice(0, 5).map((o) => ({ + category: o.category, + description: o.description, + potential_savings: o.potential_monthly_savings, + potential_savings_milliunits: o.potential_monthly_savings_milliunits, + action: o.suggestion, + })), + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/spending-analysis.ts b/src/tools/analytics/spending-analysis.ts new file mode 100644 index 0000000..c52a543 --- /dev/null +++ b/src/tools/analytics/spending-analysis.ts @@ -0,0 +1,302 @@ +/** + * Spending Analysis Tool + * + * Analyzes spending patterns across categories and time periods. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(1) + .max(12) + .optional() + .describe('Number of months to analyze (default 3)'), + category_id: z.string().optional().describe('Optional: Focus on a specific category'), +}); + +// Tool definition +export const spendingAnalysisTool: Tool = { + name: 'ynab_spending_analysis', + description: `Analyze spending patterns and trends. + +Use when the user asks: +- "How much am I spending?" +- "What are my biggest expenses?" +- "Show my spending trends" +- "Analyze my spending habits" +- "Where does my money go?" + +Provides category breakdowns, trends, and insights.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'number', + description: 'Number of months to analyze (default 3)', + }, + category_id: { + type: 'string', + description: 'Optional: Focus on a specific category', + }, + }, + required: [], + }, +}; + +interface CategorySpending { + category_name: string; + group_name: string; + total_spent: string; + total_spent_milliunits: number; // Raw value for sorting + transaction_count: number; + average_per_transaction: string; + percent_of_total: number; + monthly_average: string; + trend: 'increasing' | 'decreasing' | 'stable'; + trend_percent: number | null; +} + +interface MonthlySpending { + month: string; + total_spent: string; + category_breakdown: { name: string; amount: string }[]; +} + +// Handler function +/** + * Handler for the ynab_spending_analysis tool. + */ +export async function handleSpendingAnalysis( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const months = validated.months ?? 3; + + // Calculate since_date using UTC to avoid timezone drift + // Use day 1 to avoid month rollover issues (e.g., March 31 - 1 month = Feb 31 -> March 3) + const now = new Date(); + const sinceDate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - months, 1)); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + const options: { sinceDate: string } = { sinceDate: sinceDateStr }; + + // Get transactions and categories + const [transactionsResponse, categoriesResponse] = await Promise.all([ + client.getTransactions(budgetId, options), + client.getCategories(budgetId), + ]); + + // Build category lookup + const categoryLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + categoryLookup.set(cat.id, { name: sanitizeName(cat.name), group: sanitizeName(group.name) }); + } + } + + // Filter to outflows only (negative amounts) + let transactions = transactionsResponse.data.transactions.filter( + (t) => t.amount < 0 && !t.deleted && !t.transfer_account_id + ); + + // Filter by category if specified + if (validated.category_id) { + transactions = transactions.filter((t) => t.category_id === validated.category_id); + } + + // Group by category + const byCategoryRaw = new Map< + string, + { + amounts: number[]; + byMonth: Map; + } + >(); + + for (const txn of transactions) { + const categoryId = txn.category_id ?? 'uncategorized'; + const month = txn.date.substring(0, 7); // YYYY-MM + + if (!byCategoryRaw.has(categoryId)) { + byCategoryRaw.set(categoryId, { amounts: [], byMonth: new Map() }); + } + + const catData = byCategoryRaw.get(categoryId)!; + catData.amounts.push(Math.abs(txn.amount)); + + if (!catData.byMonth.has(month)) { + catData.byMonth.set(month, []); + } + catData.byMonth.get(month)!.push(Math.abs(txn.amount)); + } + + // Calculate total spending + const totalSpending = sumMilliunits(transactions.map((t) => Math.abs(t.amount))); + + // Build category analysis + const categorySpending: CategorySpending[] = []; + + for (const [categoryId, data] of byCategoryRaw) { + const lookup = categoryLookup.get(categoryId) ?? { name: sanitizeName('Uncategorized'), group: sanitizeName('Other') }; + const total = sumMilliunits(data.amounts); + const percentOfTotal = totalSpending > 0 ? (total / totalSpending) * 100 : 0; + + // Calculate monthly totals for trend + const monthlyTotals: { month: string; total: number }[] = []; + for (const [month, amounts] of data.byMonth) { + monthlyTotals.push({ month, total: sumMilliunits(amounts) }); + } + monthlyTotals.sort((a, b) => a.month.localeCompare(b.month)); + + // Calculate trend + const { trend, trendPercent } = calculateTrend(monthlyTotals); + + categorySpending.push({ + category_name: lookup.name, + group_name: lookup.group, + total_spent: formatCurrency(total), + total_spent_milliunits: total, // Store raw value for sorting + transaction_count: data.amounts.length, + average_per_transaction: formatCurrency(data.amounts.length > 0 ? total / data.amounts.length : 0), + percent_of_total: Math.round(percentOfTotal * 10) / 10, + monthly_average: formatCurrency(months > 0 ? total / months : 0), + trend, + trend_percent: trendPercent, + }); + } + + // Sort by total spent (highest first) using raw milliunits + categorySpending.sort((a, b) => b.total_spent_milliunits - a.total_spent_milliunits); + + // Group by month + const byMonth = new Map>(); + for (const txn of transactions) { + const month = txn.date.substring(0, 7); + const categoryId = txn.category_id ?? 'uncategorized'; + + if (!byMonth.has(month)) { + byMonth.set(month, new Map()); + } + + const monthData = byMonth.get(month)!; + monthData.set(categoryId, (monthData.get(categoryId) ?? 0) + Math.abs(txn.amount)); + } + + // Build monthly spending data + const monthlySpending: MonthlySpending[] = []; + for (const [month, categories] of byMonth) { + const total = sumMilliunits(Array.from(categories.values())); + // Use intermediate array with raw milliunits for sorting + const breakdownWithMilliunits: { name: string; amount: string; milliunits: number }[] = []; + + for (const [catId, amount] of categories) { + const lookup = categoryLookup.get(catId) ?? { name: sanitizeName('Uncategorized'), group: sanitizeName('Other') }; + breakdownWithMilliunits.push({ name: lookup.name, amount: formatCurrency(amount), milliunits: amount }); + } + + // Sort using raw milliunits (highest first) + breakdownWithMilliunits.sort((a, b) => b.milliunits - a.milliunits); + + // Convert to output format (drop milliunits) + const breakdown = breakdownWithMilliunits.slice(0, 5).map(({ name, amount }) => ({ name, amount })); + + monthlySpending.push({ + month, + total_spent: formatCurrency(total), + category_breakdown: breakdown, + }); + } + + monthlySpending.sort((a, b) => a.month.localeCompare(b.month)); + + // Calculate insights + const dailyAverage = totalSpending / (months * 30); + const topCategories = categorySpending.slice(0, 5); + const increasingCategories = categorySpending.filter((c) => c.trend === 'increasing'); + const decreasingCategories = categorySpending.filter((c) => c.trend === 'decreasing'); + + // Exclude internal milliunits field from output + const spendingByCategory = categorySpending.map(({ total_spent_milliunits: _unused, ...rest }) => rest); + + return JSON.stringify( + { + spending_by_category: spendingByCategory, + monthly_spending: monthlySpending, + summary: { + total_spent: formatCurrency(totalSpending), + monthly_average: formatCurrency(months > 0 ? totalSpending / months : 0), + daily_average: formatCurrency(dailyAverage), + transaction_count: transactions.length, + category_count: categorySpending.length, + analysis_period: `${months} months`, + since_date: sinceDateStr, + }, + insights: { + top_5_categories: topCategories.map((c) => ({ + name: c.category_name, + amount: c.total_spent, + percent: c.percent_of_total, + })), + increasing_spending: increasingCategories.slice(0, 3).map((c) => ({ + name: c.category_name, + trend_percent: c.trend_percent, + })), + decreasing_spending: decreasingCategories.slice(0, 3).map((c) => ({ + name: c.category_name, + trend_percent: c.trend_percent, + })), + }, + }, + null, + 2 + ); +} + +function calculateTrend( + monthlyTotals: { month: string; total: number }[] +): { trend: CategorySpending['trend']; trendPercent: number | null } { + if (monthlyTotals.length < 2) { + return { trend: 'stable', trendPercent: null }; + } + + // Compare first half to second half + const midpoint = Math.floor(monthlyTotals.length / 2); + const firstHalf = monthlyTotals.slice(0, midpoint); + const secondHalf = monthlyTotals.slice(midpoint); + + const firstAvg = + firstHalf.reduce((sum, m) => sum + m.total, 0) / (firstHalf.length || 1); + const secondAvg = + secondHalf.reduce((sum, m) => sum + m.total, 0) / (secondHalf.length || 1); + + if (firstAvg === 0) { + return { trend: secondAvg > 0 ? 'increasing' : 'stable', trendPercent: null }; + } + + const percentChange = ((secondAvg - firstAvg) / firstAvg) * 100; + + if (percentChange > 10) { + return { trend: 'increasing', trendPercent: Math.round(percentChange) }; + } else if (percentChange < -10) { + return { trend: 'decreasing', trendPercent: Math.round(percentChange) }; + } else { + return { trend: 'stable', trendPercent: Math.round(percentChange) }; + } +} diff --git a/src/tools/analytics/spending-by-payee.ts b/src/tools/analytics/spending-by-payee.ts new file mode 100644 index 0000000..2970a70 --- /dev/null +++ b/src/tools/analytics/spending-by-payee.ts @@ -0,0 +1,257 @@ +/** + * Spending by Payee Tool + * + * Analyzes spending patterns by merchant/payee. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(1) + .max(12) + .optional() + .describe('Number of months to analyze (default 3)'), + limit: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe('Maximum number of payees to return (default 20)'), + min_transactions: z + .number() + .int() + .min(1) + .optional() + .describe('Minimum transactions to include payee (default 1)'), +}); + +// Tool definition +export const spendingByPayeeTool: Tool = { + name: 'ynab_spending_by_payee', + description: `Analyze spending patterns by merchant/payee. + +Use when the user asks: +- "Where do I spend the most?" +- "Top merchants by spending" +- "Which stores do I shop at most?" +- "Show spending by payee" +- "Who gets most of my money?" + +Returns top payees ranked by total spending with transaction counts and averages.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'integer', + description: 'Number of months to analyze (1-12, default 3)', + minimum: 1, + maximum: 12, + }, + limit: { + type: 'integer', + description: 'Maximum number of payees to return (1-50, default 20)', + minimum: 1, + maximum: 50, + }, + min_transactions: { + type: 'integer', + description: 'Minimum transactions to include payee (default 1)', + minimum: 1, + }, + }, + required: [], + }, +}; + +interface PayeeSpending { + payee_name: string; + total_spent: string; + total_spent_raw: number; + transaction_count: number; + average_transaction: string; + percent_of_total: number; + most_common_category: string | null; + first_transaction: string; + last_transaction: string; +} + +// Handler function +/** + * Handler for the ynab_spending_by_payee tool. + */ +export async function handleSpendingByPayee( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const months = validated.months ?? 3; + const limit = validated.limit ?? 20; + const minTransactions = validated.min_transactions ?? 1; + + // Calculate since date (set day to 1 to avoid month overflow, e.g., Mar 31 - 1 month = Feb 31 = Mar 3) + const sinceDate = new Date(); + sinceDate.setDate(1); + sinceDate.setMonth(sinceDate.getMonth() - months); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + + // Get transactions + const transactionsResponse = await client.getTransactions(budgetId, { + sinceDate: sinceDateStr, + }); + + // Filter to outflows only (negative amounts), excluding transfers + const transactions = transactionsResponse.data.transactions.filter( + (t) => t.amount < 0 && !t.deleted && !t.transfer_account_id + ); + + // Calculate total spending + const totalSpending = sumMilliunits(transactions.map((t) => Math.abs(t.amount))); + + // Group by payee + const byPayee = new Map< + string, + { + amounts: number[]; + categories: string[]; + dates: string[]; + } + >(); + + for (const txn of transactions) { + const payeeName = sanitizeName(txn.payee_name); + + if (!byPayee.has(payeeName)) { + byPayee.set(payeeName, { + amounts: [], + categories: [], + dates: [], + }); + } + + const payeeData = byPayee.get(payeeName)!; + payeeData.amounts.push(Math.abs(txn.amount)); + if (txn.category_name) { + payeeData.categories.push(sanitizeName(txn.category_name)); + } + payeeData.dates.push(txn.date); + } + + // Build payee spending list + const payeeSpending: PayeeSpending[] = []; + + for (const [payeeName, data] of byPayee) { + // Skip if below minimum transactions + if (data.amounts.length < minTransactions) { + continue; + } + + const totalSpent = sumMilliunits(data.amounts); + const avgTransaction = totalSpent / data.amounts.length; + const percentOfTotal = totalSpending > 0 ? (totalSpent / totalSpending) * 100 : 0; + + // Find most common category + const categoryCounts = new Map(); + for (const cat of data.categories) { + categoryCounts.set(cat, (categoryCounts.get(cat) ?? 0) + 1); + } + let mostCommonCategory: string | null = null; + let maxCount = 0; + for (const [cat, count] of categoryCounts) { + if (count > maxCount) { + maxCount = count; + mostCommonCategory = cat; + } + } + + // Sort dates (copy to avoid mutating original array) + const sortedDates = [...data.dates].sort(); + const firstDate = sortedDates[0] ?? ''; + const lastDate = sortedDates[sortedDates.length - 1] ?? ''; + + payeeSpending.push({ + payee_name: payeeName, + total_spent: formatCurrency(totalSpent), + total_spent_raw: totalSpent, + transaction_count: data.amounts.length, + average_transaction: formatCurrency(avgTransaction), + percent_of_total: Math.round(percentOfTotal * 10) / 10, + most_common_category: mostCommonCategory, + first_transaction: firstDate, + last_transaction: lastDate, + }); + } + + // Sort by total spent (highest first) + payeeSpending.sort((a, b) => b.total_spent_raw - a.total_spent_raw); + + // Apply limit + const topPayees = payeeSpending.slice(0, limit); + + // Calculate stats + const top5Total = sumMilliunits(topPayees.slice(0, 5).map((p) => p.total_spent_raw)); + const top5Percent = totalSpending > 0 ? (top5Total / totalSpending) * 100 : 0; + + return JSON.stringify( + { + period: { + months_analyzed: months, + since_date: sinceDateStr, + }, + summary: { + total_spending: formatCurrency(totalSpending), + unique_payees: byPayee.size, + payees_shown: topPayees.length, + top_5_concentration: `${Math.round(top5Percent)}%`, + transaction_count: transactions.length, + }, + top_payees: topPayees.map((p) => ({ + payee: p.payee_name, + total: p.total_spent, + transactions: p.transaction_count, + average: p.average_transaction, + percent: `${p.percent_of_total}%`, + category: p.most_common_category, + last_transaction: p.last_transaction, + })), + insights: { + highest_spender: topPayees[0]?.payee_name ?? null, + most_frequent: payeeSpending.length > 0 + ? payeeSpending.reduce((max, p) => + p.transaction_count > max.transaction_count ? p : max + ).payee_name + : null, + highest_average: (() => { + const qualified = payeeSpending.filter((p) => p.transaction_count >= 3); + if (qualified.length === 0) return null; + return qualified.reduce( + (max, p) => + p.total_spent_raw / p.transaction_count > + max.total_spent_raw / max.transaction_count + ? p + : max + ).payee_name; + })(), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/spending-pace.ts b/src/tools/analytics/spending-pace.ts new file mode 100644 index 0000000..ad05e40 --- /dev/null +++ b/src/tools/analytics/spending-pace.ts @@ -0,0 +1,236 @@ +/** + * Spending Pace Tool + * + * Tracks daily spending rate and projects end-of-month status. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const spendingPaceTool: Tool = { + name: 'ynab_spending_pace', + description: `Track daily spending rate and project end-of-month status. + +Use when the user asks: +- "Am I on track this month?" +- "What's my spending pace?" +- "Will I stay within budget?" +- "How much can I spend per day?" +- "Daily spending rate" + +Returns current spending rate vs target rate with projections.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +interface CategoryPace { + category_name: string; + group_name: string; + budgeted: number; + spent: number; + remaining: number; + daily_target: number; + daily_actual: number; + projected_end: number; + status: 'on_track' | 'ahead' | 'behind' | 'overspent'; +} + +// Handler function +/** + * Handler for the ynab_spending_pace tool. + */ +export async function handleSpendingPace( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + // getCurrentMonth() uses UTC internally for consistency with date calculations below + const currentMonth = getCurrentMonth(); + + // Get month data and categories + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, currentMonth), + client.getCategories(budgetId), + ]); + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Calculate days in month and days elapsed using UTC to avoid timezone drift + const now = new Date(); + const year = now.getUTCFullYear(); + const month = now.getUTCMonth(); + const daysInMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + const dayOfMonth = now.getUTCDate(); + const daysRemaining = daysInMonth - dayOfMonth; + const percentMonthElapsed = (dayOfMonth / daysInMonth) * 100; + + // Process categories + const categoryPaces: CategoryPace[] = []; + let totalBudgeted = 0; + let totalSpent = 0; + + for (const cat of monthResponse.data.month.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + const budgeted = cat.budgeted; + // Use net activity so refunds reduce spent (matches YNAB's category balance) + const spent = -cat.activity; + const remaining = budgeted - spent; + + // Skip categories with no budget and no spending + if (budgeted === 0 && spent === 0) continue; + + totalBudgeted += budgeted; + totalSpent += spent; + + // Calculate rates + const dailyTarget = budgeted / daysInMonth; + const dailyActual = dayOfMonth > 0 ? spent / dayOfMonth : 0; + const projectedEnd = dailyActual * daysInMonth; + + // Determine status + let status: CategoryPace['status']; + if (spent > budgeted) { + status = 'overspent'; + } else if (dailyActual > dailyTarget * 1.1) { + status = 'behind'; + } else if (dailyActual < dailyTarget * 0.9) { + status = 'ahead'; + } else { + status = 'on_track'; + } + + categoryPaces.push({ + category_name: sanitizeName(cat.name), + group_name: sanitizeName(groupName), + budgeted, + spent, + remaining, + daily_target: dailyTarget, + daily_actual: dailyActual, + projected_end: projectedEnd, + status, + }); + } + + // Sort by status (overspent first, then behind, etc.) + const statusPriority: Record = { + overspent: 0, + behind: 1, + on_track: 2, + ahead: 3, + }; + categoryPaces.sort((a, b) => (statusPriority[a.status] ?? 99) - (statusPriority[b.status] ?? 99)); + + // Calculate overall metrics + const totalRemaining = totalBudgeted - totalSpent; + const overallDailyTarget = totalBudgeted / daysInMonth; + const overallDailyActual = dayOfMonth > 0 ? totalSpent / dayOfMonth : 0; + const projectedTotalSpend = overallDailyActual * daysInMonth; + const dailyAllowanceRemaining = daysRemaining > 0 ? totalRemaining / daysRemaining : 0; + + // Determine overall status + let overallStatus: 'on_track' | 'ahead' | 'behind' | 'overspent'; + let overallMessage: string; + + if (totalSpent > totalBudgeted) { + overallStatus = 'overspent'; + overallMessage = `Already over budget by ${formatCurrency(totalSpent - totalBudgeted)}`; + } else if (overallDailyActual > overallDailyTarget * 1.1) { + overallStatus = 'behind'; + const projectedOver = projectedTotalSpend - totalBudgeted; + overallMessage = `At current pace, will exceed budget by ${formatCurrency(projectedOver)}`; + } else if (overallDailyActual < overallDailyTarget * 0.9) { + overallStatus = 'ahead'; + overallMessage = 'Spending below target rate'; + } else { + overallStatus = 'on_track'; + overallMessage = 'Spending is on pace with budget'; + } + + // Count statuses (single-pass for efficiency) + const statusCounts = { overspent: 0, behind: 0, on_track: 0, ahead: 0 }; + for (const c of categoryPaces) { + statusCounts[c.status]++; + } + + return JSON.stringify( + { + status: overallStatus, + message: overallMessage, + month: currentMonth, + progress: { + day_of_month: dayOfMonth, + days_in_month: daysInMonth, + days_remaining: daysRemaining, + percent_elapsed: `${Math.round(percentMonthElapsed)}%`, + }, + overall: { + total_budgeted: formatCurrency(totalBudgeted), + total_spent: formatCurrency(totalSpent), + remaining: formatCurrency(totalRemaining), + percent_spent: totalBudgeted > 0 + ? `${Math.round((totalSpent / totalBudgeted) * 100)}%` + : (totalSpent > 0 ? 'N/A (no budget)' : '0%'), + daily_target: formatCurrency(overallDailyTarget), + daily_actual: formatCurrency(overallDailyActual), + daily_allowance_remaining: formatCurrency(dailyAllowanceRemaining), + projected_end_of_month: formatCurrency(projectedTotalSpend), + }, + category_status: statusCounts, + categories_needing_attention: categoryPaces + .filter((c) => c.status === 'overspent' || c.status === 'behind') + .slice(0, 10) + .map((c) => ({ + category: c.category_name, + group: c.group_name, + budgeted: formatCurrency(c.budgeted), + spent: formatCurrency(c.spent), + remaining: formatCurrency(c.remaining), + daily_target: formatCurrency(c.daily_target), + daily_actual: formatCurrency(c.daily_actual), + status: c.status, + })), + categories_ahead: categoryPaces + .filter((c) => c.status === 'ahead') + .slice(0, 5) + .map((c) => ({ + category: c.category_name, + group: c.group_name, + remaining: formatCurrency(c.remaining), + status: c.status, + })), + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/spending-trends.ts b/src/tools/analytics/spending-trends.ts new file mode 100644 index 0000000..71eb015 --- /dev/null +++ b/src/tools/analytics/spending-trends.ts @@ -0,0 +1,310 @@ +/** + * Spending Trends Tool + * + * Analyzes multi-month spending trends by category. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(2) + .max(12) + .optional() + .describe('Number of months to analyze (default 6)'), + category_id: z + .string() + .uuid() + .optional() + .describe('Specific category UUID to analyze (optional)'), +}); + +// Tool definition +export const spendingTrendsTool: Tool = { + name: 'ynab_spending_trends', + description: `Analyze spending trends over multiple months. + +Use when the user asks: +- "What are my spending trends?" +- "How has my spending changed over time?" +- "Show me category trends" +- "Which categories are increasing?" +- "Am I spending more or less over time?" + +Returns month-by-month spending data with trend analysis.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'number', + description: 'Number of months to analyze (default 6)', + }, + category_id: { + type: 'string', + description: 'Specific category UUID to analyze (optional)', + }, + }, + required: [], + }, +}; + +interface MonthData { + month: string; + spending: number; + formatted: string; +} + +interface CategoryTrend { + category_name: string; + group_name: string; + monthly_data: MonthData[]; + average: string; + trend: 'increasing' | 'decreasing' | 'stable'; + trend_percent: number; + total: string; + total_raw: number; +} + +// Handler function +/** + * Handler for the ynab_spending_trends tool. + */ +export async function handleSpendingTrends( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const monthCount = validated.months ?? 6; + + // Generate list of months to fetch + // Use UTC methods to avoid timezone drift when converting to ISO strings + const months: string[] = []; + const now = new Date(); + for (let i = 0; i < monthCount; i++) { + const date = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1)); + const year = date.getUTCFullYear(); + const month = String(date.getUTCMonth() + 1).padStart(2, '0'); + months.push(`${year}-${month}-01`); + } + months.reverse(); // Oldest first + + // Fetch all months and categories in parallel + const [categoriesResponse, ...monthResponses] = await Promise.all([ + client.getCategories(budgetId), + ...months.map((m) => client.getBudgetMonth(budgetId, m)), + ]); + + // Build group lookup + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + groupLookup.set(cat.id, group.name); + } + } + + // Build category spending by month + const categoryData = new Map< + string, + { name: string; group: string; months: MonthData[] } + >(); + + for (let i = 0; i < monthResponses.length; i++) { + const monthData = monthResponses[i]!.data.month; + const monthStr = months[i]!; + + for (const cat of monthData.categories) { + const groupName = groupLookup.get(cat.id) ?? 'Other'; + if (groupName === 'Internal Master Category' || cat.hidden) continue; + + // Filter by category if specified + if (validated.category_id && cat.id !== validated.category_id) continue; + + // Only count outflows (spending) + const spending = cat.activity < 0 ? Math.abs(cat.activity) : 0; + + if (!categoryData.has(cat.id)) { + categoryData.set(cat.id, { + name: sanitizeName(cat.name), + group: sanitizeName(groupName), + months: [], + }); + } + + categoryData.get(cat.id)!.months.push({ + month: monthStr, + spending, + formatted: formatCurrency(spending), + }); + } + } + + // Calculate trends for each category + const trends: CategoryTrend[] = []; + + for (const [, data] of categoryData) { + // Ensure we have data for all months + if (data.months.length < 2) continue; + + const total = data.months.reduce((sum, m) => sum + m.spending, 0); + const average = total / data.months.length; + + // Skip categories with no spending + if (total === 0) continue; + + // Calculate trend using simple linear regression + const n = data.months.length; + let sumX = 0; + let sumY = 0; + let sumXY = 0; + let sumX2 = 0; + + for (let i = 0; i < n; i++) { + const x = i; + const y = data.months[i]!.spending; + sumX += x; + sumY += y; + sumXY += x * y; + sumX2 += x * x; + } + + // Guard against division by zero in linear regression + const denominator = n * sumX2 - sumX * sumX; + const slope = denominator !== 0 ? (n * sumXY - sumX * sumY) / denominator : 0; + + // Calculate trend percentage (slope as % of average) + const trendPercent = average > 0 ? (slope / average) * 100 : 0; + + let trend: 'increasing' | 'decreasing' | 'stable'; + if (trendPercent > 10) { + trend = 'increasing'; + } else if (trendPercent < -10) { + trend = 'decreasing'; + } else { + trend = 'stable'; + } + + trends.push({ + category_name: data.name, + group_name: data.group, + monthly_data: data.months, + average: formatCurrency(average), + trend, + trend_percent: Math.round(trendPercent), + total: formatCurrency(total), + total_raw: total, + }); + } + + // Sort by total spending (highest first) using raw value + trends.sort((a, b) => b.total_raw - a.total_raw); + + // Calculate overall trends + const increasing = trends.filter((t) => t.trend === 'increasing'); + const decreasing = trends.filter((t) => t.trend === 'decreasing'); + const stable = trends.filter((t) => t.trend === 'stable'); + + // Calculate total spending by month + const monthlyTotals = months.map((month) => { + let total = 0; + for (const [, data] of categoryData) { + const monthData = data.months.find((m) => m.month === month); + if (monthData) total += monthData.spending; + } + return { + month, + total: formatCurrency(total), + total_raw: total, + }; + }); + + // Determine overall spending trend + const firstHalf = monthlyTotals.slice(0, Math.floor(monthlyTotals.length / 2)); + const secondHalf = monthlyTotals.slice(Math.floor(monthlyTotals.length / 2)); + const firstHalfAvg = + firstHalf.reduce((sum, m) => sum + m.total_raw, 0) / firstHalf.length; + const secondHalfAvg = + secondHalf.reduce((sum, m) => sum + m.total_raw, 0) / secondHalf.length; + const overallChange = + firstHalfAvg > 0 ? ((secondHalfAvg - firstHalfAvg) / firstHalfAvg) * 100 : 0; + + let overallTrend: 'increasing' | 'decreasing' | 'stable'; + let overallMessage: string; + + if (overallChange > 10) { + overallTrend = 'increasing'; + overallMessage = `Overall spending is up ${Math.round(overallChange)}% in recent months`; + } else if (overallChange < -10) { + overallTrend = 'decreasing'; + overallMessage = `Overall spending is down ${Math.abs(Math.round(overallChange))}% in recent months`; + } else { + overallTrend = 'stable'; + overallMessage = 'Overall spending has been relatively stable'; + } + + return JSON.stringify( + { + period: { + months_analyzed: monthCount, + date_range: `${months[0]} to ${months[months.length - 1]}`, + }, + overall: { + trend: overallTrend, + message: overallMessage, + change_percent: Math.round(overallChange), + }, + monthly_totals: monthlyTotals.map((m) => ({ + month: m.month, + total: m.total, + })), + summary: { + categories_analyzed: trends.length, + increasing: increasing.length, + decreasing: decreasing.length, + stable: stable.length, + }, + notable_increases: increasing.slice(0, 5).map((t) => ({ + category: t.category_name, + group: t.group_name, + average: t.average, + trend_percent: `+${t.trend_percent}%`, + })), + notable_decreases: decreasing.slice(0, 5).map((t) => ({ + category: t.category_name, + group: t.group_name, + average: t.average, + trend_percent: `${t.trend_percent}%`, + })), + all_trends: validated.category_id + ? trends + : trends.slice(0, 15).map((t) => ({ + category: t.category_name, + group: t.group_name, + monthly_spending: t.monthly_data.map((m) => ({ + month: m.month, + amount: m.formatted, + })), + average: t.average, + trend: t.trend, + trend_percent: `${t.trend_percent > 0 ? '+' : ''}${t.trend_percent}%`, + })), + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/transaction-search.ts b/src/tools/analytics/transaction-search.ts new file mode 100644 index 0000000..2fe8b76 --- /dev/null +++ b/src/tools/analytics/transaction-search.ts @@ -0,0 +1,311 @@ +/** + * Transaction Search Tool + * + * Powerful search across transactions with multiple filters. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { parseNaturalDate } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + query: z + .string() + .max(500) + .optional() + .describe('Search text to match in payee name, memo, or category'), + payee: z.string().max(200).optional().describe('Filter by payee name (partial match)'), + category: z.string().max(200).optional().describe('Filter by category name (partial match)'), + min_amount: z + .number() + .finite() + .optional() + .describe('Minimum transaction amount in dollars (absolute value)'), + max_amount: z + .number() + .finite() + .optional() + .describe('Maximum transaction amount in dollars (absolute value)'), + since_date: z + .string() + .optional() + .describe('Start date (YYYY-MM-DD or natural language like "last month")'), + until_date: z + .string() + .optional() + .describe('End date (YYYY-MM-DD or natural language)'), + type: z + .enum(['all', 'inflow', 'outflow']) + .optional() + .describe('Filter by transaction type (default: all)'), + limit: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Maximum results to return (default 25)'), +}); + +// Tool definition +export const transactionSearchTool: Tool = { + name: 'ynab_transaction_search', + description: `Search transactions with powerful filtering options. + +Use when the user asks: +- "Find transactions at [store]" +- "Search for [keyword] in my transactions" +- "Transactions over $100" +- "What did I spend on [category]?" +- "Find large purchases" +- "Search my expenses" + +Supports filtering by payee, category, amount range, date range, and text search.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + query: { + type: 'string', + maxLength: 500, + description: 'Search text to match in payee name, memo, or category', + }, + payee: { + type: 'string', + maxLength: 200, + description: 'Filter by payee name (partial match)', + }, + category: { + type: 'string', + maxLength: 200, + description: 'Filter by category name (partial match)', + }, + min_amount: { + type: 'number', + description: 'Minimum transaction amount in dollars (absolute value)', + }, + max_amount: { + type: 'number', + description: 'Maximum transaction amount in dollars (absolute value)', + }, + since_date: { + type: 'string', + description: 'Start date (YYYY-MM-DD or natural language)', + }, + until_date: { + type: 'string', + description: 'End date (YYYY-MM-DD or natural language)', + }, + type: { + type: 'string', + enum: ['all', 'inflow', 'outflow'], + description: 'Filter by transaction type', + }, + limit: { + type: 'integer', + description: 'Maximum results to return (default 25)', + minimum: 1, + maximum: 100, + }, + }, + required: [], + }, +}; + +interface SearchResult { + date: string; + payee: string; + category: string | null; + amount: string; + amount_raw: number; + memo: string | null; + account: string; + cleared: string; +} + +// Handler function +/** + * Handler for the ynab_transaction_search tool. + */ +export async function handleTransactionSearch( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const limit = validated.limit ?? 25; + const type = validated.type ?? 'all'; + + // Parse dates + const sinceDate = validated.since_date + ? parseNaturalDate(validated.since_date) + : undefined; + const untilDate = validated.until_date + ? parseNaturalDate(validated.until_date) + : undefined; + + // Fetch data + const transactionOptions: { sinceDate?: string } = {}; + if (sinceDate) { + transactionOptions.sinceDate = sinceDate; + } + + const [transactionsResponse, categoriesResponse, accountsResponse] = await Promise.all([ + client.getTransactions(budgetId, transactionOptions), + client.getCategories(budgetId), + client.getAccounts(budgetId), + ]); + + // Build lookups + const categoryLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + for (const cat of group.categories) { + categoryLookup.set(cat.id, cat.name); + } + } + + const accountLookup = new Map(); + for (const account of accountsResponse.data.accounts) { + accountLookup.set(account.id, account.name); + } + + // Filter transactions + let transactions = transactionsResponse.data.transactions.filter((t) => !t.deleted); + + // Apply date filter for until_date + if (untilDate) { + transactions = transactions.filter((t) => t.date <= untilDate); + } + + // Apply type filter + if (type === 'inflow') { + transactions = transactions.filter((t) => t.amount > 0); + } else if (type === 'outflow') { + transactions = transactions.filter((t) => t.amount < 0); + } + + // Apply amount filters + if (validated.min_amount !== undefined) { + const minMilliunits = validated.min_amount * 1000; + transactions = transactions.filter((t) => Math.abs(t.amount) >= minMilliunits); + } + + if (validated.max_amount !== undefined) { + const maxMilliunits = validated.max_amount * 1000; + transactions = transactions.filter((t) => Math.abs(t.amount) <= maxMilliunits); + } + + // Apply payee filter + if (validated.payee) { + const payeeSearch = validated.payee.toLowerCase(); + transactions = transactions.filter( + (t) => t.payee_name?.toLowerCase().includes(payeeSearch) + ); + } + + // Apply category filter + if (validated.category) { + const categorySearch = validated.category.toLowerCase(); + transactions = transactions.filter((t) => { + if (!t.category_id) return false; + const categoryName = categoryLookup.get(t.category_id); + return categoryName?.toLowerCase().includes(categorySearch); + }); + } + + // Apply general query search + if (validated.query) { + const queryLower = validated.query.toLowerCase(); + transactions = transactions.filter((t) => { + const payeeMatch = t.payee_name?.toLowerCase().includes(queryLower); + const memoMatch = t.memo?.toLowerCase().includes(queryLower); + const categoryName = t.category_id ? categoryLookup.get(t.category_id) : null; + const categoryMatch = categoryName?.toLowerCase().includes(queryLower); + return payeeMatch || memoMatch || categoryMatch; + }); + } + + // Sort by date (most recent first) + transactions.sort((a, b) => b.date.localeCompare(a.date)); + + // Apply limit + const limitedTransactions = transactions.slice(0, limit); + + // Format results + const results: SearchResult[] = limitedTransactions.map((t) => { + // Return null for category if lookup fails (category not found) rather than 'Unknown' + const categoryName = t.category_id ? categoryLookup.get(t.category_id) : undefined; + return { + date: t.date, + payee: sanitizeName(t.payee_name), + category: categoryName !== undefined ? sanitizeName(categoryName) : null, + amount: formatCurrency(t.amount), + amount_raw: t.amount, + memo: sanitizeMemo(t.memo), + account: sanitizeName(accountLookup.get(t.account_id) ?? 'Unknown'), + cleared: String(t.cleared), + }; + }); + + // Calculate summary stats + const totalAmount = sumMilliunits(transactions.map((t) => t.amount)); + const totalOutflow = sumMilliunits( + transactions.filter((t) => t.amount < 0).map((t) => Math.abs(t.amount)) + ); + const totalInflow = sumMilliunits( + transactions.filter((t) => t.amount > 0).map((t) => t.amount) + ); + + // Build search description + const searchCriteria: string[] = []; + if (validated.query) searchCriteria.push(`text: "${sanitizeName(validated.query)}"`); + if (validated.payee) searchCriteria.push(`payee: "${sanitizeName(validated.payee)}"`); + if (validated.category) searchCriteria.push(`category: "${sanitizeName(validated.category)}"`); + if (validated.min_amount) searchCriteria.push(`min: $${validated.min_amount}`); + if (validated.max_amount) searchCriteria.push(`max: $${validated.max_amount}`); + if (sinceDate) searchCriteria.push(`from: ${sinceDate}`); + if (untilDate) searchCriteria.push(`to: ${untilDate}`); + if (type !== 'all') searchCriteria.push(`type: ${type}`); + + return JSON.stringify( + { + search: { + criteria: searchCriteria.length > 0 ? searchCriteria.join(', ') : 'all transactions', + date_range: { + from: sinceDate ?? 'beginning', + to: untilDate ?? 'now', + }, + }, + summary: { + total_matches: transactions.length, + showing: results.length, + total_amount: formatCurrency(totalAmount), + total_outflow: formatCurrency(totalOutflow), + total_inflow: formatCurrency(totalInflow), + }, + transactions: results.map((r) => ({ + date: r.date, + payee: r.payee, + category: r.category, + amount: r.amount, + memo: r.memo, + account: r.account, + cleared: r.cleared, + })), + has_more: transactions.length > limit, + }, + null, + 2 + ); +} diff --git a/src/tools/analytics/unused-categories.ts b/src/tools/analytics/unused-categories.ts new file mode 100644 index 0000000..3481a04 --- /dev/null +++ b/src/tools/analytics/unused-categories.ts @@ -0,0 +1,256 @@ +/** + * Unused Categories Tool + * + * Identifies categories with no activity that could be cleaned up. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + months: z + .number() + .int() + .min(1) + .max(12) + .optional() + .describe('Number of months to check for activity (default 6)'), + include_funded: z + .boolean() + .optional() + .describe('Include categories that have funds but no spending (default false)'), +}); + +// Tool definition +export const unusedCategoriesTool: Tool = { + name: 'ynab_unused_categories', + description: `Find categories with no recent activity. + +Use when the user asks: +- "Which categories am I not using?" +- "Find unused categories" +- "Clean up my budget categories" +- "Categories with no activity" +- "What categories can I delete?" + +Helps identify categories that could be removed or consolidated.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + months: { + type: 'number', + description: 'Number of months to check for activity (default 6)', + }, + include_funded: { + type: 'boolean', + description: 'Include categories that have funds but no spending (default false)', + }, + }, + required: [], + }, +}; + +interface UnusedCategory { + category_name: string; + group_name: string; + balance: string; + balance_raw: number; + budgeted_this_month: string; + budgeted_raw: number; + has_goal: boolean; + last_activity: string | null; + suggestion: string; +} + +// Handler function +/** + * Handler for the ynab_unused_categories tool. + */ +export async function handleUnusedCategories( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const months = validated.months ?? 6; + const includeFunded = validated.include_funded ?? false; + + // Calculate since date + const sinceDate = new Date(); + sinceDate.setMonth(sinceDate.getMonth() - months); + const sinceDateStr = sinceDate.toISOString().split('T')[0] ?? ''; + + // Get transactions and categories + const [transactionsResponse, categoriesResponse] = await Promise.all([ + client.getTransactions(budgetId, { sinceDate: sinceDateStr }), + client.getCategories(budgetId), + ]); + + // Build set of active category IDs + const activeCategoryIds = new Set(); + const lastActivityMap = new Map(); + + for (const txn of transactionsResponse.data.transactions) { + if (txn.deleted) continue; + const txnDate = txn.date; + + // Check main transaction category + if (txn.category_id) { + activeCategoryIds.add(txn.category_id); + const existing = lastActivityMap.get(txn.category_id); + if (!existing || txnDate > existing) { + lastActivityMap.set(txn.category_id, txnDate); + } + } + + // Check subtransactions (for split transactions) + for (const sub of txn.subtransactions ?? []) { + if (!sub.category_id) continue; + activeCategoryIds.add(sub.category_id); + const existing = lastActivityMap.get(sub.category_id); + if (!existing || txnDate > existing) { + lastActivityMap.set(sub.category_id, txnDate); + } + } + } + + // Find unused categories + const unusedCategories: UnusedCategory[] = []; + + for (const group of categoriesResponse.data.category_groups) { + // Skip internal categories + if (group.name === 'Internal Master Category' || group.hidden) { + continue; + } + + for (const category of group.categories) { + // Skip hidden categories + if (category.hidden) { + continue; + } + + const isActive = activeCategoryIds.has(category.id); + const balance = category.balance; + const budgeted = category.budgeted; + const hasGoal = category.goal_type !== null && category.goal_type !== undefined; + + // Determine if category is "unused" + const isUnused = !isActive; + const hasFunds = balance > 0 || budgeted > 0; + const isOverspent = balance < 0; + + // Skip if has funds and we're not including funded categories + // But always include overspent categories as they need attention + if (isUnused && hasFunds && !includeFunded && !isOverspent) { + continue; + } + + if (isUnused) { + // Determine suggestion + let suggestion: string; + if (isOverspent) { + suggestion = 'Overspent with no recent activity - cover overspending or investigate'; + } else if (hasGoal) { + suggestion = 'Has a goal - verify if still needed'; + } else if (balance > 0) { + suggestion = 'Has funds but no activity - consider moving funds elsewhere'; + } else if (budgeted > 0) { + suggestion = 'Has budget but no spending - may not need funding'; + } else { + suggestion = 'No activity or funds - safe to hide or delete'; + } + + unusedCategories.push({ + category_name: sanitizeName(category.name), + group_name: sanitizeName(group.name), + balance: formatCurrency(balance), + balance_raw: balance, + budgeted_this_month: formatCurrency(budgeted), + budgeted_raw: budgeted, + has_goal: hasGoal, + last_activity: lastActivityMap.get(category.id) ?? null, + suggestion, + }); + } + } + } + + // Group by category group + const byGroup = new Map(); + for (const cat of unusedCategories) { + if (!byGroup.has(cat.group_name)) { + byGroup.set(cat.group_name, []); + } + byGroup.get(cat.group_name)!.push(cat); + } + + // Calculate total categories + let totalCategories = 0; + for (const group of categoriesResponse.data.category_groups) { + if (group.name !== 'Internal Master Category' && !group.hidden) { + totalCategories += group.categories.filter((c) => !c.hidden).length; + } + } + + // Categorize by cleanup potential + const safeToRemove = unusedCategories.filter( + (c) => c.balance_raw === 0 && c.budgeted_raw === 0 && !c.has_goal + ); + const needsReview = unusedCategories.filter( + (c) => c.balance_raw !== 0 || c.budgeted_raw !== 0 || c.has_goal + ); + + return JSON.stringify( + { + period: { + months_checked: months, + since_date: sinceDateStr, + }, + summary: { + total_categories: totalCategories, + unused_categories: unusedCategories.length, + percent_unused: totalCategories > 0 ? Math.round((unusedCategories.length / totalCategories) * 100) : 0, + safe_to_remove: safeToRemove.length, + needs_review: needsReview.length, + }, + categories: { + safe_to_remove: safeToRemove.map((c) => ({ + category: c.category_name, + group: c.group_name, + suggestion: c.suggestion, + })), + needs_review: needsReview.map((c) => ({ + category: c.category_name, + group: c.group_name, + balance: c.balance, + has_goal: c.has_goal, + suggestion: c.suggestion, + })), + }, + by_group: Array.from(byGroup.entries()).map(([group, cats]) => ({ + group, + count: cats.length, + categories: cats.map((c) => c.category_name), + })), + tips: [ + 'Review categories before deleting to avoid losing historical data', + 'Consider hiding categories instead of deleting to preserve history', + 'Move any remaining funds to other categories before cleanup', + ], + }, + null, + 2 + ); +} diff --git a/src/tools/budgets/get-budget-settings.ts b/src/tools/budgets/get-budget-settings.ts new file mode 100644 index 0000000..61411f7 --- /dev/null +++ b/src/tools/budgets/get-budget-settings.ts @@ -0,0 +1,77 @@ +/** + * Get Budget Settings Tool + * + * Returns budget settings including currency format and date format. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const getBudgetSettingsTool: Tool = { + name: 'ynab_get_budget_settings', + description: `Get settings for a budget including currency format, date format, and other preferences. + +Use when the user asks: +- "What currency is my budget in?" +- "Show my budget settings" +- "What's my budget date format?" +- "What are my YNAB preferences?" + +Returns currency format, date format, and currency ISO code.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_get_budget_settings tool. + */ +export async function handleGetBudgetSettings( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getBudgetSettingsById(budgetId); + const settings = response.data.settings; + + return JSON.stringify( + { + budget_id: sanitizeString(budgetId) ?? '', + settings: { + date_format: sanitizeString(settings.date_format.format) ?? '', + currency_format: { + iso_code: sanitizeString(settings.currency_format.iso_code) ?? '', + example_format: sanitizeString(settings.currency_format.example_format) ?? '', + decimal_digits: settings.currency_format.decimal_digits, + decimal_separator: sanitizeString(settings.currency_format.decimal_separator) ?? '', + symbol_first: settings.currency_format.symbol_first, + group_separator: sanitizeString(settings.currency_format.group_separator) ?? '', + currency_symbol: sanitizeString(settings.currency_format.currency_symbol) ?? '', + display_symbol: settings.currency_format.display_symbol, + }, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/budgets/get-budget.ts b/src/tools/budgets/get-budget.ts new file mode 100644 index 0000000..d4b02fc --- /dev/null +++ b/src/tools/budgets/get-budget.ts @@ -0,0 +1,164 @@ +/** + * Get Budget Tool + * + * Returns detailed information about a specific budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, formatCurrencyWithFormat } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const getBudgetTool: Tool = { + name: 'ynab_get_budget', + description: `Get detailed information about a specific budget including accounts, categories, and payees. + +Use when the user asks: +- "Show me my budget details" +- "What's in my budget?" +- "Give me an overview of my budget" +- "Tell me about my main budget" + +Returns comprehensive budget data including all accounts, category groups, categories, and payees.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_get_budget tool. + */ +export async function handleGetBudget( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Use delta sync if we have prior knowledge + const lastKnowledge = client.getServerKnowledge(budgetId); + const response = await client.getBudgetById(budgetId, lastKnowledge); + const budget = response.data.budget; + + // Persist server_knowledge for subsequent delta sync calls + if (response.data.server_knowledge !== undefined) { + client.updateServerKnowledge(budgetId, response.data.server_knowledge); + } + + // Helper to format currency using budget's format if available + // Sanitize currency_format fields with defensive defaults + const sanitizedCurrencyFormat = budget.currency_format + ? { + iso_code: typeof budget.currency_format.iso_code === 'string' + ? budget.currency_format.iso_code : 'USD', + example_format: typeof budget.currency_format.example_format === 'string' + ? budget.currency_format.example_format : '$1,234.56', + decimal_digits: typeof budget.currency_format.decimal_digits === 'number' + ? budget.currency_format.decimal_digits : 2, + decimal_separator: typeof budget.currency_format.decimal_separator === 'string' + ? budget.currency_format.decimal_separator : '.', + symbol_first: typeof budget.currency_format.symbol_first === 'boolean' + ? budget.currency_format.symbol_first : true, + group_separator: typeof budget.currency_format.group_separator === 'string' + ? budget.currency_format.group_separator : ',', + currency_symbol: typeof budget.currency_format.currency_symbol === 'string' + ? budget.currency_format.currency_symbol : '$', + display_symbol: typeof budget.currency_format.display_symbol === 'boolean' + ? budget.currency_format.display_symbol : true, + } + : null; + + const fmt = (milliunits: number): string => + sanitizedCurrencyFormat + ? formatCurrencyWithFormat(milliunits, sanitizedCurrencyFormat) + : formatCurrency(milliunits); + + // Summarize accounts by type + const accountsByType: Record> = {}; + for (const account of budget.accounts ?? []) { + if (account.closed) continue; + const type = account.type; + if (accountsByType[type] === undefined) { + accountsByType[type] = []; + } + accountsByType[type].push({ + name: sanitizeName(account.name), + balance: fmt(account.balance), + }); + } + + // Calculate totals + const assetTypes = ['checking', 'savings', 'cash', 'otherAsset']; + const liabilityTypes = [ + 'creditCard', + 'lineOfCredit', + 'otherLiability', + 'mortgage', + 'autoLoan', + 'studentLoan', + 'personalLoan', + 'medicalDebt', + 'otherDebt', + ]; + + const totalAssets = (budget.accounts ?? []) + .filter((a) => !a.closed && assetTypes.includes(String(a.type))) + .reduce((sum, a) => sum + a.balance, 0); + + const totalLiabilities = (budget.accounts ?? []) + .filter((a) => !a.closed && liabilityTypes.includes(String(a.type))) + .reduce((sum, a) => sum + Math.abs(a.balance), 0); + + // Summarize categories + const categoryGroups = (budget.category_groups ?? []) + .filter((g) => !g.hidden && g.name !== 'Internal Master Category') + .map((group) => ({ + name: sanitizeName(group.name), + categories: (budget.categories ?? []) + .filter((c) => c.category_group_id === group.id && !c.hidden) + .map((c) => ({ + name: sanitizeName(c.name), + budgeted: fmt(c.budgeted), + activity: fmt(c.activity), + balance: fmt(c.balance), + })), + })); + + return JSON.stringify( + { + budget_id: budget.id, + name: sanitizeName(budget.name), + last_modified: budget.last_modified_on, + summary: { + total_assets: fmt(totalAssets), + total_liabilities: fmt(totalLiabilities), + net_worth: fmt(totalAssets - totalLiabilities), + account_count: (budget.accounts ?? []).filter((a) => !a.closed).length, + category_count: (budget.categories ?? []).filter((c) => !c.hidden).length, + payee_count: (budget.payees ?? []).length, + }, + accounts_by_type: accountsByType, + category_groups: categoryGroups, + server_knowledge: response.data.server_knowledge, + }, + null, + 2 + ); +} diff --git a/src/tools/budgets/list-budgets.ts b/src/tools/budgets/list-budgets.ts new file mode 100644 index 0000000..e49030b --- /dev/null +++ b/src/tools/budgets/list-budgets.ts @@ -0,0 +1,104 @@ +/** + * List Budgets Tool + * + * Returns all budgets the user has access to. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, formatCurrencyWithFormat } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + include_accounts: z + .boolean() + .optional() + .describe('Whether to include account summaries for each budget'), +}); + +// Tool definition +export const listBudgetsTool: Tool = { + name: 'ynab_list_budgets', + description: `List all budgets the user has access to in YNAB. + +Use when the user asks: +- "What budgets do I have?" +- "Show me my YNAB budgets" +- "List my budgets" +- "Which budget should I use?" + +Returns budget names, IDs, and last modified dates. Optionally includes account summaries.`, + inputSchema: { + type: 'object', + properties: { + include_accounts: { + type: 'boolean', + description: 'Whether to include account summaries for each budget', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_budgets tool. + */ +export async function handleListBudgets( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + + const response = await client.getBudgets(validated.include_accounts ?? false); + const budgets = response.data.budgets; + + const result = budgets.map((budget) => { + // Sanitize currency_format fields if present + const sanitizedCurrencyFormat = budget.currency_format + ? { + iso_code: sanitizeString(budget.currency_format.iso_code) ?? '', + example_format: sanitizeString(budget.currency_format.example_format) ?? '', + decimal_digits: budget.currency_format.decimal_digits, + decimal_separator: sanitizeString(budget.currency_format.decimal_separator) ?? '', + symbol_first: budget.currency_format.symbol_first, + group_separator: sanitizeString(budget.currency_format.group_separator) ?? '', + currency_symbol: sanitizeString(budget.currency_format.currency_symbol) ?? '', + display_symbol: budget.currency_format.display_symbol, + } + : undefined; + + const budgetInfo: Record = { + id: budget.id, + name: sanitizeName(budget.name), + last_modified: budget.last_modified_on, + currency_format: sanitizedCurrencyFormat, + }; + + if (budget.accounts != null && budget.accounts.length > 0) { + // Use budget's currency format if available, otherwise fall back to default formatting + const currencyFormat = budget.currency_format; + budgetInfo['accounts'] = budget.accounts.map((acc) => ({ + name: sanitizeName(acc.name), + type: acc.type, + balance: currencyFormat + ? formatCurrencyWithFormat(acc.balance, currencyFormat) + : formatCurrency(acc.balance), + closed: acc.closed, + })); + } + + return budgetInfo; + }); + + return JSON.stringify( + { + budgets: result, + count: budgets.length, + default_budget_id: client.getDefaultBudgetId(), + }, + null, + 2 + ); +} diff --git a/src/tools/categories/get-category.ts b/src/tools/categories/get-category.ts new file mode 100644 index 0000000..20d3134 --- /dev/null +++ b/src/tools/categories/get-category.ts @@ -0,0 +1,103 @@ +/** + * Get Category Tool + * + * Returns details about a specific category. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + category_id: z.string().uuid().describe('The category UUID to retrieve'), +}); + +// Tool definition +export const getCategoryTool: Tool = { + name: 'ynab_get_category', + description: `Get details about a specific budget category including budgeted amount, activity, and goal status. + +Use when the user asks: +- "Show me details for my Groceries category" +- "What's the balance in [category name]?" +- "How much is budgeted for [category]?" +- "What's my goal progress for [category]?" + +Requires a category_id. Use ynab_list_categories first to find the category ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + category_id: { + type: 'string', + description: 'The category UUID to retrieve', + }, + }, + required: ['category_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_category tool. + */ +export async function handleGetCategory( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getCategoryById(budgetId, validated.category_id); + const category = response.data.category; + + return JSON.stringify( + { + category: { + id: category.id, + category_group_id: category.category_group_id, + name: sanitizeName(category.name), + hidden: category.hidden, + note: sanitizeMemo(category.note), + budgeted: formatCurrency(category.budgeted), + activity: formatCurrency(category.activity), + balance: formatCurrency(category.balance), + goal: category.goal_type + ? { + type: category.goal_type, + target_month: category.goal_target_month, + target: category.goal_target != null ? formatCurrency(category.goal_target) : null, + percentage_complete: category.goal_percentage_complete, + months_to_budget: category.goal_months_to_budget, + under_funded: + category.goal_under_funded != null + ? formatCurrency(category.goal_under_funded) + : null, + overall_funded: + category.goal_overall_funded != null + ? formatCurrency(category.goal_overall_funded) + : null, + overall_left: + category.goal_overall_left != null + ? formatCurrency(category.goal_overall_left) + : null, + } + : null, + original_category_group_id: category.original_category_group_id, + deleted: category.deleted, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/categories/get-month-category.ts b/src/tools/categories/get-month-category.ts new file mode 100644 index 0000000..face5ce --- /dev/null +++ b/src/tools/categories/get-month-category.ts @@ -0,0 +1,117 @@ +/** + * Get Month Category Tool + * + * Returns category details for a specific month. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"'), + month: z + .string() + .regex(/^\d{4}-\d{2}-01$/, 'Month must be first-of-month format (YYYY-MM-01)') + .describe('The budget month in YYYY-MM-01 format (first of month, e.g., 2024-01-01)'), + category_id: z.string().uuid().describe('The category UUID to retrieve'), +}); + +// Tool definition +export const getMonthCategoryTool: Tool = { + name: 'ynab_get_month_category', + description: `Get category details for a specific month, including that month's budgeted amount, activity, and balance. + +Use when the user asks: +- "How much did I budget for Groceries in January?" +- "What was my spending in [category] last month?" +- "Show me [category] for [month]" +- "What was my [category] balance in [month]?" + +Use first-of-month format for the month parameter (e.g., 2024-01-01 for January 2024). +Requires a category_id. Use ynab_list_categories first to find the category ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID or "last-used". Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + month: { + type: 'string', + pattern: '^\\d{4}-\\d{2}-01$', + description: 'The budget month in YYYY-MM-01 format (first of month)', + }, + category_id: { + type: 'string', + format: 'uuid', + description: 'The category UUID to retrieve', + }, + }, + required: ['month', 'category_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_month_category tool. + */ +export async function handleGetMonthCategory( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getMonthCategoryById( + budgetId, + validated.month, + validated.category_id + ); + const category = response.data.category; + + return JSON.stringify( + { + month: validated.month, + category: { + id: category.id, + category_group_id: category.category_group_id, + name: sanitizeName(category.name), + hidden: category.hidden, + note: sanitizeMemo(category.note), + budgeted: formatCurrency(category.budgeted), + activity: formatCurrency(category.activity), + balance: formatCurrency(category.balance), + goal: category.goal_type + ? { + type: category.goal_type, + target_month: category.goal_target_month, + target: category.goal_target != null ? formatCurrency(category.goal_target) : null, + percentage_complete: category.goal_percentage_complete, + months_to_budget: category.goal_months_to_budget, + under_funded: + category.goal_under_funded != null + ? formatCurrency(category.goal_under_funded) + : null, + overall_funded: + category.goal_overall_funded != null + ? formatCurrency(category.goal_overall_funded) + : null, + overall_left: + category.goal_overall_left != null + ? formatCurrency(category.goal_overall_left) + : null, + } + : null, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/categories/list-categories.ts b/src/tools/categories/list-categories.ts new file mode 100644 index 0000000..4317267 --- /dev/null +++ b/src/tools/categories/list-categories.ts @@ -0,0 +1,141 @@ +/** + * List Categories Tool + * + * Returns all category groups and categories in a budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + include_hidden: z + .boolean() + .optional() + .describe('Whether to include hidden categories'), +}); + +// Tool definition +export const listCategoriesTool: Tool = { + name: 'ynab_list_categories', + description: `List all category groups and categories in a budget with budgeted amounts and balances. + +Use when the user asks: +- "What categories do I have?" +- "Show my budget categories" +- "How is my budget organized?" +- "What are my spending categories?" +- "List my budget breakdown" + +Returns category groups with their categories, including budgeted amounts, activity, and remaining balances.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + include_hidden: { + type: 'boolean', + description: 'Whether to include hidden categories', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_categories tool. + */ +export async function handleListCategories( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const includeHidden = validated.include_hidden ?? false; + + const response = await client.getCategories(budgetId); + let groups = response.data.category_groups; + + // Filter out internal category group unless explicitly including hidden + if (!includeHidden) { + groups = groups.filter((g) => !g.hidden && g.name !== 'Internal Master Category'); + } + + // Build response with categories grouped + const categoryGroups = groups.map((group) => { + let categories = group.categories; + + if (!includeHidden) { + categories = categories.filter((c) => !c.hidden); + } + + return { + id: group.id, + name: sanitizeName(group.name), + hidden: group.hidden, + categories: categories.map((cat) => ({ + id: cat.id, + name: sanitizeName(cat.name), + budgeted: formatCurrency(cat.budgeted), + activity: formatCurrency(cat.activity), + balance: formatCurrency(cat.balance), + balance_raw: cat.balance, + goal_type: cat.goal_type ?? null, + goal_percentage_complete: cat.goal_percentage_complete ?? null, + goal_under_funded: + cat.goal_under_funded != null ? formatCurrency(cat.goal_under_funded) : null, + goal_under_funded_raw: cat.goal_under_funded ?? null, + hidden: cat.hidden, + })), + }; + }); + + // Calculate summary stats from the same filtered data used in detail + // Use the filtered groups and apply the same category filter for consistency + const allCategories = categoryGroups.flatMap((g) => g.categories); + const filteredCategoriesRaw = groups + .flatMap((g) => includeHidden ? g.categories : g.categories.filter((c) => !c.hidden)); + const totalBudgeted = filteredCategoriesRaw.reduce((sum, c) => sum + c.budgeted, 0); + const totalActivity = filteredCategoriesRaw.reduce((sum, c) => sum + c.activity, 0); + const totalBalance = filteredCategoriesRaw.reduce((sum, c) => sum + c.balance, 0); + + // Find categories with issues (using raw values for accurate filtering) + const overspent = allCategories.filter((c) => c.balance_raw < 0); + + const underfunded = allCategories.filter((c) => + c.goal_under_funded_raw !== null && c.goal_under_funded_raw > 0 + ); + + return JSON.stringify( + { + category_groups: categoryGroups, + summary: { + group_count: categoryGroups.length, + category_count: allCategories.length, + total_budgeted: formatCurrency(totalBudgeted), + total_activity: formatCurrency(totalActivity), + total_balance: formatCurrency(totalBalance), + overspent_count: overspent.length, + underfunded_count: underfunded.length, + }, + alerts: { + overspent_categories: overspent.map((c) => ({ name: c.name, balance: c.balance })), + underfunded_goals: underfunded.map((c) => ({ + name: c.name, + under_funded: c.goal_under_funded + })), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/categories/update-category.ts b/src/tools/categories/update-category.ts new file mode 100644 index 0000000..845c9b2 --- /dev/null +++ b/src/tools/categories/update-category.ts @@ -0,0 +1,111 @@ +/** + * Update Category Tool + * + * Updates the budgeted amount for a category in a specific month. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + month: z + .string() + .regex(/^\d{4}-\d{2}-01$/, 'Month must be first-of-month format (YYYY-MM-01)') + .describe('The budget month in YYYY-MM-01 format (first of month, e.g., 2024-01-01)'), + category_id: z.string().describe('The category UUID to update'), + budgeted: z + .number() + .finite() + .describe('The new budgeted amount in dollars (e.g., 500.00 for $500)'), +}); + +// Tool definition +export const updateCategoryTool: Tool = { + name: 'ynab_update_category', + description: `Update the budgeted amount for a category in a specific month. + +Use when the user asks: +- "Budget $500 for Groceries this month" +- "Set my dining out budget to $200" +- "Increase my entertainment budget" +- "Change the budget for [category] to [amount]" + +Use first-of-month format for the month parameter (e.g., 2024-01-01 for January 2024). +The budgeted amount is in dollars (e.g., 500.00 for $500). +Requires a category_id. Use ynab_list_categories first to find the category ID. + +**Note:** This is a write operation. Requires YNAB_READ_ONLY=false.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + month: { + type: 'string', + description: 'The budget month in YYYY-MM-01 format (first of month)', + }, + category_id: { + type: 'string', + description: 'The category UUID to update', + }, + budgeted: { + type: 'number', + description: 'The new budgeted amount in dollars', + }, + }, + required: ['month', 'category_id', 'budgeted'], + }, +}; + +// Handler function +/** + * Handler for the ynab_update_category tool. + */ +export async function handleUpdateCategory( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.updateMonthCategory( + budgetId, + validated.month, + validated.category_id, + { + category: { + budgeted: toMilliunits(validated.budgeted), + }, + } + ); + + const category = response.data.category; + + const categoryName = sanitizeName(category.name); + return JSON.stringify( + { + success: true, + message: `Budget for "${categoryName}" updated to ${formatCurrency(category.budgeted)}`, + month: validated.month, + category: { + id: category.id, + name: categoryName, + budgeted: formatCurrency(category.budgeted), + activity: formatCurrency(category.activity), + balance: formatCurrency(category.balance), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..9fd79fb --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,324 @@ +/** + * Tool Registry + * + * Central registry for all MCP tools. Each tool module exports: + * - A Tool definition object + * - A handler function + */ + +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../services/ynab-client.js'; + +// User tools +import { getUserTool, handleGetUser } from './user/get-user.js'; + +// Budget tools +import { listBudgetsTool, handleListBudgets } from './budgets/list-budgets.js'; +import { getBudgetTool, handleGetBudget } from './budgets/get-budget.js'; +import { + getBudgetSettingsTool, + handleGetBudgetSettings, +} from './budgets/get-budget-settings.js'; + +// Account tools +import { listAccountsTool, handleListAccounts } from './accounts/list-accounts.js'; +import { getAccountTool, handleGetAccount } from './accounts/get-account.js'; +import { createAccountTool, handleCreateAccount } from './accounts/create-account.js'; + +// Category tools +import { listCategoriesTool, handleListCategories } from './categories/list-categories.js'; +import { getCategoryTool, handleGetCategory } from './categories/get-category.js'; +import { + getMonthCategoryTool, + handleGetMonthCategory, +} from './categories/get-month-category.js'; +import { updateCategoryTool, handleUpdateCategory } from './categories/update-category.js'; + +// Payee tools +import { listPayeesTool, handleListPayees } from './payees/list-payees.js'; +import { getPayeeTool, handleGetPayee } from './payees/get-payee.js'; +import { + listPayeeLocationsTool, + handleListPayeeLocations, +} from './payees/list-payee-locations.js'; +import { + getPayeeLocationTool, + handleGetPayeeLocation, +} from './payees/get-payee-location.js'; +import { + listPayeeLocationsByPayeeTool, + handleListPayeeLocationsByPayee, +} from './payees/list-payee-locations-by-payee.js'; + +// Month tools +import { listMonthsTool, handleListMonths } from './months/list-months.js'; +import { getMonthTool, handleGetMonth } from './months/get-month.js'; + +// Transaction tools +import { + listTransactionsTool, + handleListTransactions, +} from './transactions/list-transactions.js'; +import { + getTransactionTool, + handleGetTransaction, +} from './transactions/get-transaction.js'; +import { + createTransactionTool, + handleCreateTransaction, +} from './transactions/create-transaction.js'; +import { + updateTransactionTool, + handleUpdateTransaction, +} from './transactions/update-transaction.js'; +import { + deleteTransactionTool, + handleDeleteTransaction, +} from './transactions/delete-transaction.js'; +import { + createTransactionsTool, + handleCreateTransactions, +} from './transactions/create-transactions.js'; +import { + listAccountTransactionsTool, + handleListAccountTransactions, +} from './transactions/list-account-transactions.js'; +import { + listCategoryTransactionsTool, + handleListCategoryTransactions, +} from './transactions/list-category-transactions.js'; +import { + listPayeeTransactionsTool, + handleListPayeeTransactions, +} from './transactions/list-payee-transactions.js'; +import { + importTransactionsTool, + handleImportTransactions, +} from './transactions/import-transactions.js'; + +// Scheduled transaction tools +import { + listScheduledTransactionsTool, + handleListScheduledTransactions, +} from './scheduled-transactions/list-scheduled.js'; +import { + getScheduledTransactionTool, + handleGetScheduledTransaction, +} from './scheduled-transactions/get-scheduled.js'; + +// Analytics tools +import { + detectRecurringTool, + handleDetectRecurring, + spendingAnalysisTool, + handleSpendingAnalysis, + budgetHealthTool, + handleBudgetHealth, + savingsOpportunitiesTool, + handleSavingsOpportunities, + budgetVsActualsTool, + handleBudgetVsActuals, + quickSummaryTool, + handleQuickSummary, + incomeExpenseTool, + handleIncomeExpense, + netWorthTool, + handleNetWorth, + goalProgressTool, + handleGoalProgress, + spendingByPayeeTool, + handleSpendingByPayee, + unusedCategoriesTool, + handleUnusedCategories, + monthlyComparisonTool, + handleMonthlyComparison, + spendingTrendsTool, + handleSpendingTrends, + cashFlowForecastTool, + handleCashFlowForecast, + reconciliationHelperTool, + handleReconciliationHelper, + budgetSuggestionsTool, + handleBudgetSuggestions, + overspendingAlertsTool, + handleOverspendingAlerts, + transactionSearchTool, + handleTransactionSearch, + spendingPaceTool, + handleSpendingPace, + categoryBalancesTool, + handleCategoryBalances, + creditCardStatusTool, + handleCreditCardStatus, + ageOfMoneyTool, + handleAgeOfMoney, +} from './analytics/index.js'; + +// System tools +import { + rateLimitStatusTool, + handleRateLimitStatus, + auditLogTool, + handleAuditLog, + healthCheckTool, + handleHealthCheck, +} from './system/index.js'; + +// Export all tool definitions +export const tools: Tool[] = [ + // User + getUserTool, + // Budgets + listBudgetsTool, + getBudgetTool, + getBudgetSettingsTool, + // Accounts + listAccountsTool, + getAccountTool, + createAccountTool, + // Categories + listCategoriesTool, + getCategoryTool, + getMonthCategoryTool, + updateCategoryTool, + // Payees + listPayeesTool, + getPayeeTool, + listPayeeLocationsTool, + getPayeeLocationTool, + listPayeeLocationsByPayeeTool, + // Months + listMonthsTool, + getMonthTool, + // Transactions + listTransactionsTool, + getTransactionTool, + createTransactionTool, + updateTransactionTool, + deleteTransactionTool, + createTransactionsTool, + listAccountTransactionsTool, + listCategoryTransactionsTool, + listPayeeTransactionsTool, + importTransactionsTool, + // Scheduled Transactions + listScheduledTransactionsTool, + getScheduledTransactionTool, + // Analytics + detectRecurringTool, + spendingAnalysisTool, + budgetHealthTool, + savingsOpportunitiesTool, + budgetVsActualsTool, + quickSummaryTool, + incomeExpenseTool, + netWorthTool, + goalProgressTool, + spendingByPayeeTool, + unusedCategoriesTool, + monthlyComparisonTool, + spendingTrendsTool, + cashFlowForecastTool, + reconciliationHelperTool, + budgetSuggestionsTool, + overspendingAlertsTool, + transactionSearchTool, + spendingPaceTool, + categoryBalancesTool, + creditCardStatusTool, + ageOfMoneyTool, + // System + rateLimitStatusTool, + auditLogTool, + healthCheckTool, +]; + +// Tool handler mapping +type ToolHandler = (args: Record, client: YnabClient) => Promise; + +const handlers: Record = { + // User + ynab_get_user: handleGetUser, + // Budgets + ynab_list_budgets: handleListBudgets, + ynab_get_budget: handleGetBudget, + ynab_get_budget_settings: handleGetBudgetSettings, + // Accounts + ynab_list_accounts: handleListAccounts, + ynab_get_account: handleGetAccount, + ynab_create_account: handleCreateAccount, + // Categories + ynab_list_categories: handleListCategories, + ynab_get_category: handleGetCategory, + ynab_get_month_category: handleGetMonthCategory, + ynab_update_category: handleUpdateCategory, + // Payees + ynab_list_payees: handleListPayees, + ynab_get_payee: handleGetPayee, + ynab_list_payee_locations: handleListPayeeLocations, + ynab_get_payee_location: handleGetPayeeLocation, + ynab_list_payee_locations_by_payee: handleListPayeeLocationsByPayee, + // Months + ynab_list_months: handleListMonths, + ynab_get_month: handleGetMonth, + // Transactions + ynab_list_transactions: handleListTransactions, + ynab_get_transaction: handleGetTransaction, + ynab_create_transaction: handleCreateTransaction, + ynab_update_transaction: handleUpdateTransaction, + ynab_delete_transaction: handleDeleteTransaction, + ynab_create_transactions: handleCreateTransactions, + ynab_list_account_transactions: handleListAccountTransactions, + ynab_list_category_transactions: handleListCategoryTransactions, + ynab_list_payee_transactions: handleListPayeeTransactions, + ynab_import_transactions: handleImportTransactions, + // Scheduled Transactions + ynab_list_scheduled_transactions: handleListScheduledTransactions, + ynab_get_scheduled_transaction: handleGetScheduledTransaction, + // Analytics + ynab_detect_recurring: handleDetectRecurring, + ynab_spending_analysis: handleSpendingAnalysis, + ynab_budget_health: handleBudgetHealth, + ynab_savings_opportunities: handleSavingsOpportunities, + ynab_budget_vs_actuals: handleBudgetVsActuals, + ynab_quick_summary: handleQuickSummary, + ynab_income_expense: handleIncomeExpense, + ynab_net_worth: handleNetWorth, + ynab_goal_progress: handleGoalProgress, + ynab_spending_by_payee: handleSpendingByPayee, + ynab_unused_categories: handleUnusedCategories, + ynab_monthly_comparison: handleMonthlyComparison, + ynab_spending_trends: handleSpendingTrends, + ynab_cash_flow_forecast: handleCashFlowForecast, + ynab_reconciliation_helper: handleReconciliationHelper, + ynab_budget_suggestions: handleBudgetSuggestions, + ynab_overspending_alerts: handleOverspendingAlerts, + ynab_transaction_search: handleTransactionSearch, + ynab_spending_pace: handleSpendingPace, + ynab_category_balances: handleCategoryBalances, + ynab_credit_card_status: handleCreditCardStatus, + ynab_age_of_money: handleAgeOfMoney, + // System + ynab_rate_limit_status: handleRateLimitStatus, + ynab_audit_log: handleAuditLog, + ynab_health_check: handleHealthCheck, +}; + +/** + * Route a tool call to the appropriate handler. + */ +export async function handleToolCall( + toolName: string, + args: Record, + client: YnabClient +): Promise { + // Guard against prototype pollution - only allow own properties + if (!Object.prototype.hasOwnProperty.call(handlers, toolName)) { + const safeName = toolName.slice(0, 100).replace(/[\r\n]/g, ''); + throw new Error(`Unknown tool: ${safeName}`); + } + + // Safe to access after hasOwnProperty check + const handler = handlers[toolName] as ToolHandler; + return handler(args, client); +} diff --git a/src/tools/months/get-month.ts b/src/tools/months/get-month.ts new file mode 100644 index 0000000..39517cf --- /dev/null +++ b/src/tools/months/get-month.ts @@ -0,0 +1,144 @@ +/** + * Get Month Tool + * + * Returns detailed information about a specific budget month. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { getCurrentMonth } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema - accepts YYYY-MM-DD format or "current" +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + month: z + .string() + .refine( + (val) => val === 'current' || /^\d{4}-\d{2}-\d{2}$/.test(val), + { message: 'Month must be in YYYY-MM-DD format or "current"' } + ) + .describe('The budget month in YYYY-MM-DD format (use first of month) or "current"'), +}); + +// Tool definition +export const getMonthTool: Tool = { + name: 'ynab_get_month', + description: `Get detailed information about a specific budget month including all categories. + +Use when the user asks: +- "Show me January's budget" +- "What did I budget last month?" +- "Give me details for [month]" +- "How much did I have to budget in [month]?" + +Use first-of-month format for the month parameter (e.g., 2024-01-01 for January 2024). +Use "current" for the current month.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + month: { + type: 'string', + description: + 'The budget month in YYYY-MM-DD format (use first of month, or "current")', + }, + }, + required: ['month'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_month tool. + */ +export async function handleGetMonth( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Convert "current" to actual month date + const monthParam = validated.month === 'current' ? getCurrentMonth() : validated.month; + + // Fetch month data and categories in parallel + const [monthResponse, categoriesResponse] = await Promise.all([ + client.getBudgetMonth(budgetId, monthParam), + client.getCategories(budgetId), + ]); + + const month = monthResponse.data.month; + + // Build category group lookup (id -> {id, name}) + const groupLookup = new Map(); + for (const group of categoriesResponse.data.category_groups) { + groupLookup.set(group.id, { id: group.id, name: group.name }); + } + + // Category type for group entries + type CategoryInfo = { + name: string; + budgeted: string; + activity: string; + balance: string; + }; + + // Group categories using Map keyed by group_id (safe internal key) + const groupMap = new Map(); + + for (const category of month.categories) { + if (category.hidden) continue; + + const groupId = category.category_group_id; + const groupInfo = groupLookup.get(groupId); + const groupName = sanitizeName(groupInfo?.name ?? 'Other'); + + let groupEntry = groupMap.get(groupId); + if (groupEntry === undefined) { + groupEntry = { + group_id: groupId, + group_name: groupName, + categories: [], + }; + groupMap.set(groupId, groupEntry); + } + groupEntry.categories.push({ + name: sanitizeName(category.name), + budgeted: formatCurrency(category.budgeted), + activity: formatCurrency(category.activity), + balance: formatCurrency(category.balance), + }); + } + + // Convert to array and sort alphabetically by group name + const categoriesByGroup = Array.from(groupMap.values()).sort((a, b) => + a.group_name.localeCompare(b.group_name) + ); + + return JSON.stringify( + { + month: month.month, + summary: { + note: sanitizeMemo(month.note), + income: formatCurrency(month.income), + budgeted: formatCurrency(month.budgeted), + activity: formatCurrency(month.activity), + to_be_budgeted: formatCurrency(month.to_be_budgeted), + age_of_money: month.age_of_money, + }, + category_count: month.categories.filter((c) => !c.hidden).length, + categories_by_group: categoriesByGroup, + }, + null, + 2 + ); +} diff --git a/src/tools/months/list-months.ts b/src/tools/months/list-months.ts new file mode 100644 index 0000000..af440b0 --- /dev/null +++ b/src/tools/months/list-months.ts @@ -0,0 +1,79 @@ +/** + * List Months Tool + * + * Returns all budget months. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const listMonthsTool: Tool = { + name: 'ynab_list_months', + description: `List all budget months with summary information. + +Use when the user asks: +- "Show my budget months" +- "What months do I have budgeted?" +- "List my budget history" +- "Show me past months" + +Returns each month's income, budgeted, activity, and to-be-budgeted amounts.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_months tool. + */ +export async function handleListMonths( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getBudgetMonths(budgetId); + const months = response.data.months; + + // Use default USD formatting to preserve rate-limit budget + // (avoids extra getBudgetSettingsById API call) + const formattedMonths = months.map((month) => ({ + month: month.month, + note: sanitizeMemo(month.note), + income: formatCurrency(month.income), + budgeted: formatCurrency(month.budgeted), + activity: formatCurrency(month.activity), + to_be_budgeted: formatCurrency(month.to_be_budgeted), + age_of_money: month.age_of_money, + deleted: month.deleted, + })); + + return JSON.stringify( + { + months: formattedMonths, + count: months.length, + }, + null, + 2 + ); +} diff --git a/src/tools/payees/get-payee-location.ts b/src/tools/payees/get-payee-location.ts new file mode 100644 index 0000000..95fcf9a --- /dev/null +++ b/src/tools/payees/get-payee-location.ts @@ -0,0 +1,69 @@ +/** + * Get Payee Location Tool + * + * Gets a specific payee location by ID. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + payee_location_id: z.string().uuid().describe('The payee location UUID'), +}); + +// Tool definition +export const getPayeeLocationTool: Tool = { + name: 'ynab_get_payee_location', + description: `Get a specific payee location by ID. + +Returns the details of a single payee location including coordinates.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + payee_location_id: { + type: 'string', + description: 'The payee location UUID', + }, + }, + required: ['payee_location_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_payee_location tool. + */ +export async function handleGetPayeeLocation( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getPayeeLocationById(budgetId, validated.payee_location_id); + const loc = response.data.payee_location; + + return JSON.stringify( + { + payee_location: { + id: sanitizeString(loc.id) ?? '', + payee_id: sanitizeString(loc.payee_id) ?? '', + latitude: loc.latitude, + longitude: loc.longitude, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/payees/get-payee.ts b/src/tools/payees/get-payee.ts new file mode 100644 index 0000000..198fb32 --- /dev/null +++ b/src/tools/payees/get-payee.ts @@ -0,0 +1,73 @@ +/** + * Get Payee Tool + * + * Returns details about a specific payee. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeName, sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + payee_id: z.string().uuid().describe('The payee UUID to retrieve'), +}); + +// Tool definition +export const getPayeeTool: Tool = { + name: 'ynab_get_payee', + description: `Get details about a specific payee. + +Use when the user asks: +- "Show me details for [payee]" +- "Get info on a merchant" + +Requires a payee_id. Use ynab_list_payees first to find the payee ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + payee_id: { + type: 'string', + description: 'The payee UUID to retrieve', + }, + }, + required: ['payee_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_payee tool. + */ +export async function handleGetPayee( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getPayeeById(budgetId, validated.payee_id); + const payee = response.data.payee; + + return JSON.stringify( + { + payee: { + id: sanitizeString(payee.id) ?? '', + name: sanitizeName(payee.name), + transfer_account_id: payee.transfer_account_id ? sanitizeString(payee.transfer_account_id) : null, + deleted: payee.deleted, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/payees/list-payee-locations-by-payee.ts b/src/tools/payees/list-payee-locations-by-payee.ts new file mode 100644 index 0000000..91d8147 --- /dev/null +++ b/src/tools/payees/list-payee-locations-by-payee.ts @@ -0,0 +1,75 @@ +/** + * List Payee Locations By Payee Tool + * + * Lists all locations for a specific payee. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + payee_id: z.string().uuid('Invalid payee UUID format').describe('The payee UUID'), +}); + +// Tool definition +export const listPayeeLocationsByPayeeTool: Tool = { + name: 'ynab_list_payee_locations_by_payee', + description: `List all locations for a specific payee. + +Use when the user asks: +- "Where is [payee] located?" +- "Show locations for [store]" +- "Which [payee] locations have I visited?" + +Returns all recorded locations for a specific payee.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + payee_id: { + type: 'string', + description: 'The payee UUID', + }, + }, + required: ['payee_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_list_payee_locations_by_payee tool. + */ +export async function handleListPayeeLocationsByPayee( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getPayeeLocationsByPayee(budgetId, validated.payee_id); + const locations = response.data.payee_locations; + + return JSON.stringify( + { + payee_id: sanitizeString(validated.payee_id) ?? '', + location_count: locations.length, + payee_locations: locations.map((loc) => ({ + id: sanitizeString(loc.id) ?? '', + latitude: loc.latitude, + longitude: loc.longitude, + })), + }, + null, + 2 + ); +} diff --git a/src/tools/payees/list-payee-locations.ts b/src/tools/payees/list-payee-locations.ts new file mode 100644 index 0000000..634e6a1 --- /dev/null +++ b/src/tools/payees/list-payee-locations.ts @@ -0,0 +1,71 @@ +/** + * List Payee Locations Tool + * + * Lists all payee locations for a budget (used for map features). + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const listPayeeLocationsTool: Tool = { + name: 'ynab_list_payee_locations', + description: `List all payee locations for a budget. + +Use when the user asks: +- "Where are my payees located?" +- "Show payee locations" +- "Map of where I spend" +- "Payee geographic data" + +Returns payee locations with latitude/longitude for mapping purposes.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_list_payee_locations tool. + */ +export async function handleListPayeeLocations( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getPayeeLocations(budgetId); + const locations = response.data.payee_locations; + + return JSON.stringify( + { + location_count: locations.length, + payee_locations: locations.map((loc) => ({ + id: sanitizeString(loc.id) ?? '', + payee_id: sanitizeString(loc.payee_id) ?? '', + latitude: loc.latitude, + longitude: loc.longitude, + })), + }, + null, + 2 + ); +} diff --git a/src/tools/payees/list-payees.ts b/src/tools/payees/list-payees.ts new file mode 100644 index 0000000..dac766b --- /dev/null +++ b/src/tools/payees/list-payees.ts @@ -0,0 +1,85 @@ +/** + * List Payees Tool + * + * Returns all payees in a budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeName, sanitizeString } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const listPayeesTool: Tool = { + name: 'ynab_list_payees', + description: `List all payees in a budget. + +Use when the user asks: +- "Show my payees" +- "List all merchants" +- "Who have I paid?" +- "Find a payee" + +Returns payee names and IDs. Payees are merchants, people, or places you transact with.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_payees tool. + */ +export async function handleListPayees( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getPayees(budgetId); + const payees = response.data.payees; + + // Filter out deleted payees and sort by name + const activePayees = payees + .filter((p) => !p.deleted) + .sort((a, b) => a.name.localeCompare(b.name)); + + const formattedPayees = activePayees.map((payee) => ({ + id: sanitizeString(payee.id) ?? '', + name: sanitizeName(payee.name), + transfer_account_id: payee.transfer_account_id ? sanitizeString(payee.transfer_account_id) : null, + })); + + // Separate transfer payees from regular payees + const transferPayees = formattedPayees.filter((p) => p.transfer_account_id != null); + const regularPayees = formattedPayees.filter((p) => p.transfer_account_id == null); + + return JSON.stringify( + { + payees: regularPayees, + transfer_payees: transferPayees, + summary: { + total_payees: formattedPayees.length, + regular_payees: regularPayees.length, + transfer_payees: transferPayees.length, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/scheduled-transactions/get-scheduled.ts b/src/tools/scheduled-transactions/get-scheduled.ts new file mode 100644 index 0000000..add42f8 --- /dev/null +++ b/src/tools/scheduled-transactions/get-scheduled.ts @@ -0,0 +1,101 @@ +/** + * Get Scheduled Transaction Tool + * + * Returns details about a specific scheduled transaction. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + scheduled_transaction_id: z.string().uuid().describe('The scheduled transaction UUID to retrieve'), +}); + +// Tool definition +export const getScheduledTransactionTool: Tool = { + name: 'ynab_get_scheduled_transaction', + description: `Get details about a specific scheduled transaction. + +Use when the user asks: +- "Show me details for that scheduled transaction" +- "What's the info on my Netflix subscription?" + +Requires a scheduled_transaction_id. Use ynab_list_scheduled_transactions first to find the ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + scheduled_transaction_id: { + type: 'string', + description: 'The scheduled transaction UUID to retrieve', + }, + }, + required: ['scheduled_transaction_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_scheduled_transaction tool. + */ +export async function handleGetScheduledTransaction( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getScheduledTransactionById( + budgetId, + validated.scheduled_transaction_id + ); + const txn = response.data.scheduled_transaction; + + return JSON.stringify( + { + scheduled_transaction: { + id: txn.id, + date_first: txn.date_first, + date_next: txn.date_next, + frequency: txn.frequency, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + flag_color: txn.flag_color, + account_id: txn.account_id, + account_name: sanitizeName(txn.account_name), + payee_id: txn.payee_id, + payee_name: sanitizeName(txn.payee_name), + category_id: txn.category_id, + category_name: sanitizeName(txn.category_name), + transfer_account_id: txn.transfer_account_id, + deleted: txn.deleted, + subtransactions: (() => { + const subs = txn.subtransactions ?? []; + return subs.length > 0 + ? subs.map((sub) => ({ + id: sub.id, + amount: formatCurrency(sub.amount), + memo: sanitizeMemo(sub.memo), + payee_id: sub.payee_id, + category_id: sub.category_id, + transfer_account_id: sub.transfer_account_id, + })) + : []; + })(), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/scheduled-transactions/list-scheduled.ts b/src/tools/scheduled-transactions/list-scheduled.ts new file mode 100644 index 0000000..9a689b5 --- /dev/null +++ b/src/tools/scheduled-transactions/list-scheduled.ts @@ -0,0 +1,143 @@ +/** + * List Scheduled Transactions Tool + * + * Returns all scheduled transactions in a budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), +}); + +// Tool definition +export const listScheduledTransactionsTool: Tool = { + name: 'ynab_list_scheduled_transactions', + description: `List all scheduled transactions (recurring bills, subscriptions, etc.) in a budget. + +Use when the user asks: +- "Show my scheduled transactions" +- "What recurring bills do I have?" +- "List my subscriptions" +- "What payments are coming up?" + +Returns scheduled transaction details including frequency, next occurrence, and amounts.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_scheduled_transactions tool. + */ +export async function handleListScheduledTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getScheduledTransactions(budgetId); + const transactions = response.data.scheduled_transactions; + + // Filter out deleted and sort by next date + const activeTransactions = transactions + .filter((t) => !t.deleted) + .sort((a, b) => a.date_next.localeCompare(b.date_next)); + + const formattedTransactions = activeTransactions.map((txn) => { + const subs = txn.subtransactions ?? []; + return { + id: txn.id, + date_first: txn.date_first, + date_next: txn.date_next, + frequency: txn.frequency, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + flag_color: txn.flag_color, + subtransactions: + subs.length > 0 + ? subs.map((sub) => ({ + amount: formatCurrency(sub.amount), + memo: sanitizeMemo(sub.memo), + payee_id: sub.payee_id, + category_id: sub.category_id, + })) + : [], + }; + }); + + // Calculate monthly total (approximate) + const monthlyAmounts = activeTransactions.map((t) => { + const amount = Math.abs(t.amount); + const freq = String(t.frequency); + switch (freq) { + case 'daily': + return amount * 30; + case 'weekly': + return amount * 4; + case 'everyOtherWeek': + return amount * 2; + case 'twiceAMonth': + return amount * 2; + case 'every4Weeks': + return amount; + case 'monthly': + return amount; + case 'everyOtherMonth': + return amount / 2; + case 'every3Months': + return amount / 3; + case 'every4Months': + return amount / 4; + case 'twiceAYear': + return amount / 6; + case 'yearly': + return amount / 12; + case 'everyOtherYear': + return amount / 24; + default: + return amount; + } + }); + + const estimatedMonthlyTotal = sumMilliunits(monthlyAmounts); + + // Group by frequency + const byFrequency: Record = {}; + for (const txn of activeTransactions) { + const freq = txn.frequency; + byFrequency[freq] = (byFrequency[freq] ?? 0) + 1; + } + + return JSON.stringify( + { + scheduled_transactions: formattedTransactions, + summary: { + total_count: formattedTransactions.length, + estimated_monthly_total: formatCurrency(estimatedMonthlyTotal), + by_frequency: byFrequency, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/system/audit-log.ts b/src/tools/system/audit-log.ts new file mode 100644 index 0000000..b7cbb7b --- /dev/null +++ b/src/tools/system/audit-log.ts @@ -0,0 +1,170 @@ +/** + * Audit Log Tool + * + * View the audit log of write operations. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import { getAuditLog } from '../../services/audit-log.js'; + +// Input schema +const inputSchema = z.object({ + operation: z + .enum(['create', 'update', 'delete']) + .optional() + .describe('Filter by operation type'), + resource_type: z + .enum(['transaction', 'account', 'category']) + .optional() + .describe('Filter by resource type'), + success: z.boolean().optional().describe('Filter by success/failure'), + limit: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Maximum entries to return (default 20)'), + summary_only: z + .boolean() + .optional() + .describe('Return only summary statistics'), +}).strict(); + +// Tool definition +export const auditLogTool: Tool = { + name: 'ynab_audit_log', + description: `View the audit log of write operations. + +Use when the user asks: +- "What changes have been made?" +- "Show me the audit log" +- "What transactions were created?" +- "Were there any failed operations?" + +Shows all create, update, and delete operations with timestamps.`, + inputSchema: { + type: 'object', + properties: { + operation: { + type: 'string', + enum: ['create', 'update', 'delete'], + description: 'Filter by operation type', + }, + resource_type: { + type: 'string', + enum: ['transaction', 'account', 'category'], + description: 'Filter by resource type', + }, + success: { + type: 'boolean', + description: 'Filter by success/failure', + }, + limit: { + type: 'integer', + description: 'Maximum entries to return (default 20)', + minimum: 1, + maximum: 100, + default: 20, + }, + summary_only: { + type: 'boolean', + description: 'Return only summary statistics', + }, + }, + required: [], + additionalProperties: false, + }, +}; + +// Handler function +/** + * Handler for the ynab_audit_log tool. + * Note: client param intentionally omitted; this tool only uses the local AuditLog service. + */ +export async function handleAuditLog( + args: Record +): Promise { + const validated = inputSchema.parse(args); + const auditLog = getAuditLog(); + + // Build filter options (applies to both summary_only and full response) + const filterOptions: { + operation?: string; + resourceType?: string; + success?: boolean; + limit?: number; + } = {}; + + if (validated.operation !== undefined) filterOptions.operation = validated.operation; + if (validated.resource_type !== undefined) filterOptions.resourceType = validated.resource_type; + if (validated.success !== undefined) filterOptions.success = validated.success; + + // Check if any filters are applied + const hasFilters = validated.operation !== undefined || + validated.resource_type !== undefined || + validated.success !== undefined; + + if (validated.summary_only) { + // Get filtered entries (without limit) to compute accurate summary + const filteredEntries = auditLog.getFiltered(filterOptions); + + // Compute summary from filtered entries + let successCount = 0; + let failureCount = 0; + for (const entry of filteredEntries) { + if (entry.success) { + successCount++; + } else { + failureCount++; + } + } + + const summaryOut = { + total_operations: filteredEntries.length, + success_count: successCount, + failure_count: failureCount, + }; + + return JSON.stringify( + { + summary: summaryOut, + ...(hasFilters ? { filters_applied: true } : {}), + message: + summaryOut.total_operations === 0 + ? hasFilters + ? 'No matching audit log entries found' + : 'No write operations have been performed yet' + : `${summaryOut.total_operations} operations logged${hasFilters ? ' (filtered)' : ''}`, + }, + null, + 2 + ); + } + + // Full response - apply limit + filterOptions.limit = validated.limit ?? 20; + const entries = auditLog.getFiltered(filterOptions); + + // Get global summary for context (unfiltered) + const globalSummary = auditLog.getSummary(); + + return JSON.stringify( + { + entries, + count: entries.length, + summary: { + total_operations: globalSummary.totalOperations, + success_count: globalSummary.successCount, + failure_count: globalSummary.failureCount, + }, + message: + entries.length === 0 + ? 'No matching audit log entries found' + : `Showing ${entries.length} most recent entries`, + }, + null, + 2 + ); +} diff --git a/src/tools/system/health-check.ts b/src/tools/system/health-check.ts new file mode 100644 index 0000000..493c24b --- /dev/null +++ b/src/tools/system/health-check.ts @@ -0,0 +1,137 @@ +/** + * Health Check Tool + * + * Verifies the YNAB API connection and server status. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { sanitizeErrorMessage } from '../../utils/sanitize.js'; + +/** + * Input schema for health check tool. + * Accepts an empty object (no parameters required). + */ +const inputSchema = z.object({}).strict(); + +// Tool definition +export const healthCheckTool: Tool = { + name: 'ynab_health_check', + description: `Check the health of the YNAB MCP server and API connection. + +Use when: +- Troubleshooting connection issues +- Verifying the server is configured correctly +- Checking if the YNAB API is accessible + +Returns server status, API connectivity, and configuration details.`, + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_health_check tool. + */ +export async function handleHealthCheck( + args: Record, + client: YnabClient +): Promise { + // Validate inputs (rejects unexpected properties) + inputSchema.parse(args); + + const startTime = Date.now(); + const checks: { + name: string; + status: 'pass' | 'fail'; + duration_ms?: number; + message?: string; + error?: string; + }[] = []; + + // Check 1: Rate limiter status + const rateLimitStatus = client.getRateLimitStatus(); + checks.push({ + name: 'rate_limiter', + status: rateLimitStatus.canMakeRequest ? 'pass' : 'fail', + message: rateLimitStatus.canMakeRequest + ? `${rateLimitStatus.available}/${rateLimitStatus.limit} requests available` + : 'Rate limit exhausted', + }); + + // Check 2: API connectivity (attempt to get user info) + const apiCheckStart = Date.now(); + try { + await client.getUser(); + const apiCheckDuration = Date.now() - apiCheckStart; + checks.push({ + name: 'api_connectivity', + status: 'pass', + duration_ms: apiCheckDuration, + message: 'Connected successfully', + }); + } catch (err) { + const apiCheckDuration = Date.now() - apiCheckStart; + // Log sanitized error internally for debugging (not exposed in response) + console.error('Health check API connectivity failed:', sanitizeErrorMessage(err)); + checks.push({ + name: 'api_connectivity', + status: 'fail', + duration_ms: apiCheckDuration, + error: 'Failed to connect to YNAB API', + }); + } + + // Check 3: Read-only mode status + checks.push({ + name: 'write_operations', + status: 'pass', // Not a failure, just informational + message: client.isReadOnly() + ? 'Server is in READ-ONLY mode (write operations disabled)' + : 'Write operations are ENABLED', + }); + + // Check 4: Default budget configuration + const defaultBudgetId = client.getDefaultBudgetId(); + // Mask UUID to avoid exposing internal IDs (show first 4 and last 4 chars) + const maskedBudgetId = defaultBudgetId.length > 12 + ? `${defaultBudgetId.slice(0, 4)}...${defaultBudgetId.slice(-4)}` + : defaultBudgetId; + checks.push({ + name: 'default_budget', + status: 'pass', + message: + defaultBudgetId === 'last-used' + ? 'Using "last-used" budget (no specific default set)' + : `Default budget configured (${maskedBudgetId})`, + }); + + // Calculate overall status + const failedChecks = checks.filter((c) => c.status === 'fail'); + const overallStatus = failedChecks.length === 0 ? 'healthy' : 'unhealthy'; + const totalDuration = Date.now() - startTime; + + return JSON.stringify( + { + status: overallStatus, + message: + overallStatus === 'healthy' + ? 'All systems operational' + : `${failedChecks.length} check(s) failed`, + checks, + summary: { + total_checks: checks.length, + passed: checks.filter((c) => c.status === 'pass').length, + failed: failedChecks.length, + total_duration_ms: totalDuration, + }, + timestamp: new Date().toISOString(), + }, + null, + 2 + ); +} diff --git a/src/tools/system/index.ts b/src/tools/system/index.ts new file mode 100644 index 0000000..ee38a60 --- /dev/null +++ b/src/tools/system/index.ts @@ -0,0 +1,9 @@ +/** + * System Tools Index + * + * Exports all system-related tools. + */ + +export { rateLimitStatusTool, handleRateLimitStatus } from './rate-limit-status.js'; +export { auditLogTool, handleAuditLog } from './audit-log.js'; +export { healthCheckTool, handleHealthCheck } from './health-check.js'; diff --git a/src/tools/system/rate-limit-status.ts b/src/tools/system/rate-limit-status.ts new file mode 100644 index 0000000..1e9c885 --- /dev/null +++ b/src/tools/system/rate-limit-status.ts @@ -0,0 +1,91 @@ +/** + * Rate Limit Status Tool + * + * Returns the current API rate limit status. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; + +// Input schema (strict - rejects unexpected properties) +const inputSchema = z.object({}).strict(); + +// Tool definition +export const rateLimitStatusTool: Tool = { + name: 'ynab_rate_limit_status', + description: `Check the current YNAB API rate limit status. + +Use when you need to: +- Check how many API requests are available +- See if rate limiting might affect operations +- Plan large operations that require many API calls + +YNAB allows 200 requests per hour. This server uses 180 as a safety margin.`, + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_rate_limit_status tool. + */ +export async function handleRateLimitStatus( + args: Record, + client: YnabClient +): Promise { + // Validate input (ensures no unexpected properties) + inputSchema.parse(args); + + const status = client.getRateLimitStatus(); + + // Calculate human-readable times + const waitTimeSeconds = Math.ceil(status.waitTimeMs / 1000); + const resetTimeMinutes = Math.ceil(status.resetTimeMs / 60000); + + // Determine status level + let statusLevel: 'healthy' | 'warning' | 'critical'; + let statusMessage: string; + + if (status.percentUsed < 50) { + statusLevel = 'healthy'; + statusMessage = 'Plenty of API quota available'; + } else if (status.percentUsed < 80) { + statusLevel = 'warning'; + statusMessage = 'API quota is being consumed - consider spacing out requests'; + } else { + statusLevel = 'critical'; + statusMessage = 'API quota is low - limit requests to essential operations'; + } + + return JSON.stringify( + { + status: statusLevel, + message: statusMessage, + rate_limit: { + available_requests: status.available, + total_limit: status.limit, + used_requests: status.used, + percent_used: status.percentUsed, + }, + timing: { + can_make_request_now: status.canMakeRequest, + wait_time_seconds: waitTimeSeconds, + full_reset_minutes: resetTimeMinutes, + }, + recommendations: + status.percentUsed > 50 + ? [ + 'Use filtered queries instead of fetching all data', + 'Rely on cached data when possible', + 'Batch operations when available', + ] + : [], + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/create-transaction.ts b/src/tools/transactions/create-transaction.ts new file mode 100644 index 0000000..4e46007 --- /dev/null +++ b/src/tools/transactions/create-transaction.ts @@ -0,0 +1,179 @@ +/** + * Create Transaction Tool + * + * Creates a new transaction in a budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type * as ynab from 'ynab'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Cleared status options +const clearedStatuses = ['cleared', 'uncleared', 'reconciled'] as const; + +// Flag colors +const flagColors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] as const; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + account_id: z.string().uuid().describe('The account UUID for this transaction'), + date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .describe('Transaction date in YYYY-MM-DD format'), + amount: z + .number() + .describe( + 'Amount in dollars (negative for outflow, positive for inflow). E.g., -50.00 for a $50 expense' + ), + payee_id: z.string().uuid().optional().describe('Payee UUID (use ynab_list_payees to find)'), + payee_name: z + .string() + .optional() + .describe('Payee name (creates new payee if payee_id not provided)'), + category_id: z + .string() + .uuid() + .optional() + .describe('Category UUID (use ynab_list_categories to find)'), + memo: z.string().max(200).optional().describe('Transaction memo/note'), + cleared: z + .enum(clearedStatuses) + .optional() + .describe('Cleared status: cleared, uncleared, or reconciled'), + approved: z.boolean().optional().describe('Whether the transaction is approved'), + flag_color: z.enum(flagColors).optional().describe('Flag color for the transaction'), +}); + +// Tool definition +export const createTransactionTool: Tool = { + name: 'ynab_create_transaction', + description: `Create a new transaction in a budget. + +Use when the user asks: +- "Add a transaction for $50 at Amazon" +- "Record a purchase" +- "Log an expense" +- "Create a transaction" + +Requires READ_ONLY mode to be disabled (YNAB_READ_ONLY=false). +Amount should be negative for expenses/outflows and positive for income/inflows.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + account_id: { + type: 'string', + description: 'The account UUID for this transaction', + }, + date: { + type: 'string', + description: 'Transaction date in YYYY-MM-DD format', + }, + amount: { + type: 'number', + description: 'Amount in dollars (negative for outflow, positive for inflow)', + }, + payee_id: { + type: 'string', + description: 'Payee UUID', + }, + payee_name: { + type: 'string', + description: 'Payee name (creates new payee if payee_id not provided)', + }, + category_id: { + type: 'string', + description: 'Category UUID', + }, + memo: { + type: 'string', + description: 'Transaction memo/note', + }, + cleared: { + type: 'string', + enum: clearedStatuses, + description: 'Cleared status', + }, + approved: { + type: 'boolean', + description: 'Whether the transaction is approved', + }, + flag_color: { + type: 'string', + enum: flagColors, + description: 'Flag color', + }, + }, + required: ['account_id', 'date', 'amount'], + }, +}; + +// Handler function +/** + * Handler for the ynab_create_transaction tool. + */ +export async function handleCreateTransaction( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Build transaction data, only including defined fields + const transactionData: ynab.SaveTransaction = { + account_id: validated.account_id, + date: validated.date, + amount: toMilliunits(validated.amount), + }; + + if (validated.payee_id !== undefined) transactionData.payee_id = validated.payee_id; + if (validated.payee_name !== undefined) transactionData.payee_name = validated.payee_name; + if (validated.category_id !== undefined) transactionData.category_id = validated.category_id; + if (validated.memo !== undefined) transactionData.memo = validated.memo; + if (validated.cleared !== undefined) + transactionData.cleared = validated.cleared as unknown as ynab.SaveTransaction.ClearedEnum; + if (validated.approved !== undefined) transactionData.approved = validated.approved; + if (validated.flag_color !== undefined) + transactionData.flag_color = validated.flag_color as unknown as ynab.SaveTransaction.FlagColorEnum; + + const response = await client.createTransaction(budgetId, { + transaction: transactionData, + }); + + const txn = response.data.transaction; + + if (txn == null) { + throw new Error('Transaction creation failed: no transaction returned'); + } + + return JSON.stringify( + { + success: true, + message: `Transaction created: ${formatCurrency(txn.amount)} at ${sanitizeName(txn.payee_name)}`, + transaction: { + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + memo: sanitizeMemo(txn.memo), + cleared: txn.cleared, + approved: txn.approved, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/create-transactions.ts b/src/tools/transactions/create-transactions.ts new file mode 100644 index 0000000..8f9ee7e --- /dev/null +++ b/src/tools/transactions/create-transactions.ts @@ -0,0 +1,163 @@ +/** + * Create Transactions (Bulk) Tool + * + * Creates multiple transactions in a single request. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type * as ynab from 'ynab'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits, sumMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeString } from '../../utils/sanitize.js'; + +// Transaction schema for bulk creation +const transactionSchema = z.object({ + account_id: z.string().uuid().describe('The account UUID for this transaction'), + date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .describe('Transaction date in YYYY-MM-DD format'), + amount: z + .number() + .describe('Amount in dollars (negative for outflow, positive for inflow)'), + payee_id: z.string().uuid().optional().describe('Payee UUID'), + payee_name: z.string().optional().describe('Payee name'), + category_id: z.string().uuid().optional().describe('Category UUID'), + memo: z.string().max(200).optional().describe('Transaction memo'), + cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(), + approved: z.boolean().optional(), + flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(), + import_id: z.string().optional().describe('Unique ID for import deduplication'), +}); + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + transactions: z + .array(transactionSchema) + .min(1) + .max(100) + .describe('Array of transactions to create (max 100)'), +}); + +// Tool definition +export const createTransactionsTool: Tool = { + name: 'ynab_create_transactions', + description: `Create multiple transactions in a single request (bulk import). + +Use when the user asks: +- "Import these transactions" +- "Add multiple transactions" +- "Bulk create transactions" + +Requires READ_ONLY mode to be disabled (YNAB_READ_ONLY=false). +Maximum 100 transactions per request. +Use import_id to prevent duplicate imports.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + transactions: { + type: 'array', + description: 'Array of transactions to create', + items: { + type: 'object', + properties: { + account_id: { type: 'string', description: 'Account UUID' }, + date: { type: 'string', description: 'Date in YYYY-MM-DD format' }, + amount: { type: 'number', description: 'Amount in dollars' }, + payee_id: { type: 'string', description: 'Payee UUID' }, + payee_name: { type: 'string', description: 'Payee name' }, + category_id: { type: 'string', description: 'Category UUID' }, + memo: { type: 'string', description: 'Memo' }, + cleared: { type: 'string', enum: ['cleared', 'uncleared', 'reconciled'] }, + approved: { type: 'boolean' }, + flag_color: { + type: 'string', + enum: ['red', 'orange', 'yellow', 'green', 'blue', 'purple'], + }, + import_id: { type: 'string', description: 'Unique ID for deduplication' }, + }, + required: ['account_id', 'date', 'amount'], + }, + }, + }, + required: ['transactions'], + }, +}; + +// Handler function +/** + * Handler for the ynab_create_transactions tool. + */ +export async function handleCreateTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Convert transactions to YNAB format + const ynabTransactions: ynab.SaveTransaction[] = validated.transactions.map((t) => { + const txn: ynab.SaveTransaction = { + account_id: t.account_id, + date: t.date, + amount: toMilliunits(t.amount), + }; + + if (t.payee_id !== undefined) txn.payee_id = t.payee_id; + if (t.payee_name !== undefined) txn.payee_name = t.payee_name; + if (t.category_id !== undefined) txn.category_id = t.category_id; + if (t.memo !== undefined) txn.memo = t.memo; + if (t.cleared !== undefined) txn.cleared = t.cleared as unknown as ynab.SaveTransaction.ClearedEnum; + if (t.approved !== undefined) txn.approved = t.approved; + if (t.flag_color !== undefined) + txn.flag_color = t.flag_color as unknown as ynab.SaveTransaction.FlagColorEnum; + if (t.import_id !== undefined) txn.import_id = t.import_id; + + return txn; + }); + + const response = await client.createTransaction(budgetId, { + transactions: ynabTransactions, + }); + + const created = response.data.transactions ?? []; + const duplicates = response.data.duplicate_import_ids ?? []; + + // Calculate totals (guard for empty array when all are duplicates) + const amounts = created.map((t) => t.amount); + const totalAmount = created.length > 0 ? sumMilliunits(amounts) : 0; + + return JSON.stringify( + { + success: true, + message: `Created ${created.length} transactions`, + summary: { + created_count: created.length, + duplicate_count: duplicates.length, + total_amount: formatCurrency(totalAmount), + }, + transactions: created.map((t) => ({ + id: t.id, + date: t.date, + amount: formatCurrency(t.amount), + payee_name: sanitizeName(t.payee_name), + category_name: sanitizeName(t.category_name), + })), + duplicate_import_ids: + duplicates.length > 0 + ? duplicates.map((id) => sanitizeString(id, 100) ?? '') + : undefined, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/delete-transaction.ts b/src/tools/transactions/delete-transaction.ts new file mode 100644 index 0000000..3f1692d --- /dev/null +++ b/src/tools/transactions/delete-transaction.ts @@ -0,0 +1,84 @@ +/** + * Delete Transaction Tool + * + * Deletes a transaction from a budget. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + transaction_id: z.string().uuid().describe('The transaction UUID to delete'), +}); + +// Tool definition +export const deleteTransactionTool: Tool = { + name: 'ynab_delete_transaction', + description: `Delete a transaction from a budget. + +Use when the user asks: +- "Delete that transaction" +- "Remove the transaction" +- "Cancel that purchase entry" + +Requires READ_ONLY mode to be disabled (YNAB_READ_ONLY=false). +This action cannot be undone.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + transaction_id: { + type: 'string', + description: 'The transaction UUID to delete', + }, + }, + required: ['transaction_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_delete_transaction tool. + */ +export async function handleDeleteTransaction( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.deleteTransaction(budgetId, validated.transaction_id); + const txn = response.data.transaction; + + if (txn == null) { + throw new Error('Transaction deletion failed: no transaction returned'); + } + + return JSON.stringify( + { + success: true, + message: `Transaction deleted: ${formatCurrency(txn.amount)} at ${sanitizeName(txn.payee_name)} on ${txn.date}`, + deleted_transaction: { + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/get-transaction.ts b/src/tools/transactions/get-transaction.ts new file mode 100644 index 0000000..7932ff2 --- /dev/null +++ b/src/tools/transactions/get-transaction.ts @@ -0,0 +1,106 @@ +/** + * Get Transaction Tool + * + * Returns details about a specific transaction. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + transaction_id: z.string().uuid().describe('The transaction UUID to retrieve'), +}); + +// Tool definition +export const getTransactionTool: Tool = { + name: 'ynab_get_transaction', + description: `Get details about a specific transaction. + +Use when the user asks: +- "Show me details for that transaction" +- "What's the info on transaction [id]?" +- "Tell me more about that purchase" + +Requires a transaction_id. Use ynab_list_transactions first to find the transaction ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + transaction_id: { + type: 'string', + description: 'The transaction UUID to retrieve', + }, + }, + required: ['transaction_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_get_transaction tool. + */ +export async function handleGetTransaction( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.getTransactionById(budgetId, validated.transaction_id); + const txn = response.data.transaction; + + return JSON.stringify( + { + transaction: { + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + payee_id: txn.payee_id, + payee_name: sanitizeName(txn.payee_name), + category_id: txn.category_id, + category_name: sanitizeName(txn.category_name), + account_id: txn.account_id, + account_name: sanitizeName(txn.account_name), + cleared: txn.cleared, + approved: txn.approved, + flag_color: txn.flag_color, + import_id: txn.import_id, + import_payee_name: sanitizeName(txn.import_payee_name), + import_payee_name_original: sanitizeName(txn.import_payee_name_original), + debt_transaction_type: txn.debt_transaction_type, + transfer_account_id: txn.transfer_account_id, + transfer_transaction_id: txn.transfer_transaction_id, + matched_transaction_id: txn.matched_transaction_id, + subtransactions: + (txn.subtransactions ?? []).length > 0 + ? (txn.subtransactions ?? []).map((sub) => ({ + id: sub.id, + transaction_id: sub.transaction_id, + amount: formatCurrency(sub.amount), + memo: sanitizeMemo(sub.memo), + payee_id: sub.payee_id, + payee_name: sanitizeName(sub.payee_name), + category_id: sub.category_id, + category_name: sanitizeName(sub.category_name), + transfer_account_id: sub.transfer_account_id, + transfer_transaction_id: sub.transfer_transaction_id, + })) + : [], + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/import-transactions.ts b/src/tools/transactions/import-transactions.ts new file mode 100644 index 0000000..f298f46 --- /dev/null +++ b/src/tools/transactions/import-transactions.ts @@ -0,0 +1,84 @@ +/** + * Import Transactions Tool + * + * Triggers the import of transactions from linked bank accounts. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + include_ids: z + .boolean() + .optional() + .default(false) + .describe('Include imported transaction IDs in the response'), +}); + +// Tool definition +export const importTransactionsTool: Tool = { + name: 'ynab_import_transactions', + description: `Trigger import of transactions from linked bank accounts. + +Use when the user asks: +- "Import my bank transactions" +- "Sync my accounts" +- "Get latest transactions from my bank" +- "Refresh bank connections" +- "Pull in new transactions" + +Initiates a file-based import for accounts that have direct import enabled. +Returns the count of transactions that were imported. + +Note: This is a WRITE operation that requires write mode to be enabled.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + include_ids: { + type: 'boolean', + description: 'Include imported transaction IDs in the response', + }, + }, + required: [], + }, +}; + +// Handler function +/** + * Handler for the ynab_import_transactions tool. + */ +export async function handleImportTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + const response = await client.importTransactions(budgetId); + const importedIds = response.data.transaction_ids ?? []; + + return JSON.stringify( + { + success: true, + message: + importedIds.length > 0 + ? `Successfully imported ${importedIds.length} transaction(s)` + : 'No new transactions to import', + imported_count: importedIds.length, + ...(validated.include_ids ? { transaction_ids: importedIds } : {}), + note: 'Imported transactions may need to be categorized', + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/list-account-transactions.ts b/src/tools/transactions/list-account-transactions.ts new file mode 100644 index 0000000..6d011b5 --- /dev/null +++ b/src/tools/transactions/list-account-transactions.ts @@ -0,0 +1,132 @@ +/** + * List Account Transactions Tool + * + * Returns transactions for a specific account. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { parseNaturalDate } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + account_id: z.string().uuid().describe('The account UUID to get transactions for'), + since_date: z + .string() + .optional() + .describe( + 'Only return transactions on or after this date. Accepts ISO dates (YYYY-MM-DD) or natural language like "past 30 days", "this month"' + ), + limit: z + .number() + .int() + .positive() + .max(500) + .optional() + .describe('Maximum number of transactions to return (default 100, max 500)'), +}); + +// Tool definition +export const listAccountTransactionsTool: Tool = { + name: 'ynab_list_account_transactions', + description: `List transactions for a specific account. + +Use when the user asks: +- "Show transactions for my checking account" +- "What purchases were made on my credit card?" +- "List activity in [account name]" + +Requires an account_id. Use ynab_list_accounts first to find the account ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + account_id: { + type: 'string', + description: 'The account UUID to get transactions for', + }, + since_date: { + type: 'string', + description: + 'Only return transactions on or after this date. Accepts YYYY-MM-DD or natural language like "past 30 days"', + }, + limit: { + type: 'number', + description: 'Maximum number of transactions to return (default 100, max 500)', + }, + }, + required: ['account_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_list_account_transactions tool. + */ +export async function handleListAccountTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const limit = validated.limit ?? 100; + + // Parse natural language dates + const sinceDate = validated.since_date ? parseNaturalDate(validated.since_date) : undefined; + + const response = await client.getAccountTransactions( + budgetId, + validated.account_id, + sinceDate + ); + + let transactions = response.data.transactions; + + // Sort by date descending + transactions.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); + + // Apply limit + transactions = transactions.slice(0, limit); + + // Calculate summary + const inflow = transactions.filter((t) => t.amount > 0); + const outflow = transactions.filter((t) => t.amount < 0); + const totalInflow = sumMilliunits(inflow.map((t) => t.amount)); + const totalOutflow = sumMilliunits(outflow.map((t) => Math.abs(t.amount))); + + const formattedTransactions = transactions.map((txn) => ({ + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + cleared: txn.cleared, + approved: txn.approved, + })); + + return JSON.stringify( + { + account_id: validated.account_id, + transactions: formattedTransactions, + summary: { + count: formattedTransactions.length, + total_inflow: formatCurrency(totalInflow), + total_outflow: formatCurrency(totalOutflow), + net: formatCurrency(totalInflow - totalOutflow), + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/list-category-transactions.ts b/src/tools/transactions/list-category-transactions.ts new file mode 100644 index 0000000..9ae628e --- /dev/null +++ b/src/tools/transactions/list-category-transactions.ts @@ -0,0 +1,141 @@ +/** + * List Category Transactions Tool + * + * Returns transactions for a specific category. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { parseNaturalDate } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + category_id: z.string().uuid().describe('The category UUID to get transactions for'), + since_date: z + .string() + .optional() + .describe( + 'Only return transactions on or after this date. Accepts ISO dates (YYYY-MM-DD) or natural language like "past 30 days", "this month"' + ), + limit: z + .number() + .int() + .positive() + .max(500) + .optional() + .describe('Maximum number of transactions to return (default 100, max 500)'), +}); + +// Tool definition +export const listCategoryTransactionsTool: Tool = { + name: 'ynab_list_category_transactions', + description: `List transactions for a specific category. + +Use when the user asks: +- "Show my grocery transactions" +- "What did I spend on dining out?" +- "List transactions in [category name]" + +Requires a category_id. Use ynab_list_categories first to find the category ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + category_id: { + type: 'string', + format: 'uuid', + description: 'The category UUID to get transactions for', + }, + since_date: { + type: 'string', + description: + 'Only return transactions on or after this date. Accepts YYYY-MM-DD or natural language like "past 30 days"', + }, + limit: { + type: 'integer', + description: 'Maximum number of transactions to return (default 100, max 500)', + minimum: 1, + maximum: 500, + }, + }, + required: ['category_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_list_category_transactions tool. + */ +export async function handleListCategoryTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const limit = validated.limit ?? 100; + + // Parse natural language dates + const sinceDate = validated.since_date ? parseNaturalDate(validated.since_date) : undefined; + + const response = await client.getCategoryTransactions( + budgetId, + validated.category_id, + sinceDate + ); + + // Sort by date descending and apply limit (avoid mutating response) + const transactions = [...response.data.transactions] + .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) + .slice(0, limit); + + // Calculate summary - only count outflows (negative amounts) as spending + const outflows = transactions.filter((t) => t.amount < 0); + const totalSpent = sumMilliunits(outflows.map((t) => Math.abs(t.amount))); + + // Group by payee - only count outflows, sanitize during aggregation + const byPayee: Record = {}; + for (const txn of outflows) { + const payee = sanitizeName(txn.payee_name) ?? 'Unknown'; + byPayee[payee] = (byPayee[payee] ?? 0) + Math.abs(txn.amount); + } + + // Top payees (already sanitized during aggregation) + const topPayees = Object.entries(byPayee) + .sort((a, b) => b[1] - a[1]) + .slice(0, 5) + .map(([name, amount]) => ({ name, amount: formatCurrency(amount) })); + + const formattedTransactions = transactions.map((txn) => ({ + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + payee_name: sanitizeName(txn.payee_name), + account_name: sanitizeName(txn.account_name), + cleared: txn.cleared, + })); + + return JSON.stringify( + { + category_id: validated.category_id, + transactions: formattedTransactions, + summary: { + count: formattedTransactions.length, + total_spent: formatCurrency(totalSpent), + top_payees: topPayees, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/list-payee-transactions.ts b/src/tools/transactions/list-payee-transactions.ts new file mode 100644 index 0000000..c722344 --- /dev/null +++ b/src/tools/transactions/list-payee-transactions.ts @@ -0,0 +1,148 @@ +/** + * List Payee Transactions Tool + * + * Returns transactions for a specific payee. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { parseNaturalDate } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + payee_id: z.string().uuid().describe('The payee UUID to get transactions for'), + since_date: z + .string() + .optional() + .describe( + 'Only return transactions on or after this date. Accepts ISO dates (YYYY-MM-DD) or natural language like "past 30 days", "this month"' + ), + limit: z + .number() + .int() + .positive() + .max(500) + .optional() + .describe('Maximum number of transactions to return (default 100, max 500)'), +}); + +// Tool definition +export const listPayeeTransactionsTool: Tool = { + name: 'ynab_list_payee_transactions', + description: `List transactions for a specific payee (merchant/vendor). + +Use when the user asks: +- "Show my Amazon purchases" +- "What have I spent at Costco?" +- "List transactions for [payee name]" + +Requires a payee_id. Use ynab_list_payees first to find the payee ID.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + payee_id: { + type: 'string', + format: 'uuid', + description: 'The payee UUID to get transactions for', + }, + since_date: { + type: 'string', + description: + 'Only return transactions on or after this date. Accepts YYYY-MM-DD or natural language like "past 30 days"', + }, + limit: { + type: 'integer', + minimum: 1, + maximum: 500, + description: 'Maximum number of transactions to return (default 100, max 500)', + }, + }, + required: ['payee_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_list_payee_transactions tool. + */ +export async function handleListPayeeTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const limit = validated.limit ?? 100; + + // Parse natural language dates + const sinceDate = validated.since_date ? parseNaturalDate(validated.since_date) : undefined; + + const response = await client.getPayeeTransactions( + budgetId, + validated.payee_id, + sinceDate + ); + + // Sort by date descending and apply limit (avoid mutating response) + const transactions = [...response.data.transactions] + .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) + .slice(0, limit); + + // Calculate summary - separate inflows and outflows for clarity + const outflows = transactions.filter((t) => t.amount < 0); + const inflowCount = transactions.filter((t) => t.amount >= 0).length; + const totalSpent = sumMilliunits(outflows.map((t) => Math.abs(t.amount))); + + // Group by category (outflows only) + const byCategory: Record = {}; + for (const txn of outflows) { + const category = txn.category_name ?? 'Uncategorized'; + byCategory[category] = (byCategory[category] ?? 0) + Math.abs(txn.amount); + } + + // Top categories + const topCategories = Object.entries(byCategory) + .sort((a, b) => b[1] - a[1]) + .slice(0, 5) + .map(([name, amount]) => ({ name: sanitizeName(name), amount: formatCurrency(amount) })); + + // Calculate average and frequency (outflows only) + const avgAmount = outflows.length > 0 ? totalSpent / outflows.length : 0; + + const formattedTransactions = transactions.map((txn) => ({ + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + cleared: txn.cleared, + })); + + return JSON.stringify( + { + payee_id: validated.payee_id, + transactions: formattedTransactions, + summary: { + count: formattedTransactions.length, + outflow_count: outflows.length, + inflow_count: inflowCount, + total_spent: formatCurrency(totalSpent), + average_outflow: formatCurrency(avgAmount), // Average per outflow transaction + top_categories: topCategories, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/list-transactions.ts b/src/tools/transactions/list-transactions.ts new file mode 100644 index 0000000..c3bf857 --- /dev/null +++ b/src/tools/transactions/list-transactions.ts @@ -0,0 +1,175 @@ +/** + * List Transactions Tool + * + * Returns transactions for a budget with optional filters. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, sumMilliunits } from '../../utils/milliunits.js'; +import { parseNaturalDate } from '../../utils/dates.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Input schema +const inputSchema = z.object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + since_date: z + .string() + .optional() + .describe( + 'Only return transactions on or after this date. Accepts ISO dates (YYYY-MM-DD) or natural language: "today", "yesterday", "this week", "last week", "this month", "last month", "past 7 days", "past 30 days"' + ), + type: z + .enum(['uncategorized', 'unapproved']) + .optional() + .describe('Filter by transaction type: "uncategorized" or "unapproved"'), + limit: z + .number() + .int() + .positive() + .max(500) + .optional() + .describe('Maximum number of transactions to return (default 100, max 500)'), +}); + +// Tool definition +export const listTransactionsTool: Tool = { + name: 'ynab_list_transactions', + description: `List transactions for a budget with optional filters. + +Use when the user asks: +- "Show my recent transactions" +- "What did I spend this month?" +- "List my uncategorized transactions" +- "Show transactions since [date]" +- "What purchases have I made recently?" +- "Show me the past 7 days of transactions" +- "What did I spend last week?" + +Supports filtering by date (ISO or natural language like "past 30 days", "this month") and type (uncategorized/unapproved). +Returns transaction details including date, payee, amount, category, and status.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + since_date: { + type: 'string', + description: + 'Only return transactions on or after this date. Accepts YYYY-MM-DD or natural language: "today", "this week", "past 30 days", etc.', + }, + type: { + type: 'string', + enum: ['uncategorized', 'unapproved'], + description: 'Filter by transaction type', + }, + limit: { + type: 'number', + description: 'Maximum number of transactions to return (default 100, max 500)', + }, + }, + }, +}; + +// Handler function +/** + * Handler for the ynab_list_transactions tool. + */ +export async function handleListTransactions( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + const limit = validated.limit ?? 100; + + const options: { + sinceDate?: string; + type?: 'uncategorized' | 'unapproved'; + } = {}; + if (validated.since_date !== undefined) { + // Parse natural language dates like "past 7 days", "this month", etc. + options.sinceDate = parseNaturalDate(validated.since_date); + } + if (validated.type !== undefined) { + options.type = validated.type; + } + + const response = await client.getTransactions(budgetId, options); + + let transactions = response.data.transactions; + + // Sort by date descending (most recent first) + transactions.sort((a, b) => { + const dateA = new Date(a.date).getTime(); + const dateB = new Date(b.date).getTime(); + return dateB - dateA; + }); + + // Apply limit + transactions = transactions.slice(0, limit); + + // Calculate summary stats + const inflow = transactions.filter((t) => t.amount > 0); + const outflow = transactions.filter((t) => t.amount < 0); + const totalInflow = sumMilliunits(inflow.map((t) => t.amount)); + const totalOutflow = sumMilliunits(outflow.map((t) => Math.abs(t.amount))); + + // Format transactions + const formattedTransactions = transactions.map((txn) => ({ + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + memo: sanitizeMemo(txn.memo), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + cleared: txn.cleared, + approved: txn.approved, + flag_color: txn.flag_color, + transfer_account_id: txn.transfer_account_id, + subtransactions: + (txn.subtransactions ?? []).length > 0 + ? (txn.subtransactions ?? []).map((sub) => ({ + amount: formatCurrency(sub.amount), + memo: sanitizeMemo(sub.memo), + payee_name: sanitizeName(sub.payee_name), + category_name: sanitizeName(sub.category_name), + })) + : undefined, + })); + + // Date range + const dates = transactions.map((t) => t.date); + const minDate = dates.length > 0 ? dates[dates.length - 1] : null; + const maxDate = dates.length > 0 ? dates[0] : null; + + return JSON.stringify( + { + transactions: formattedTransactions, + summary: { + count: formattedTransactions.length, + total_inflow: formatCurrency(totalInflow), + total_outflow: formatCurrency(totalOutflow), + net: formatCurrency(totalInflow - totalOutflow), + date_range: minDate && maxDate ? { from: minDate, to: maxDate } : null, + }, + filters_applied: { + since_date: validated.since_date + ? { input: validated.since_date, parsed: options.sinceDate } + : null, + type: validated.type ?? null, + limit, + }, + server_knowledge: response.data.server_knowledge, + }, + null, + 2 + ); +} diff --git a/src/tools/transactions/update-transaction.ts b/src/tools/transactions/update-transaction.ts new file mode 100644 index 0000000..76ff4b3 --- /dev/null +++ b/src/tools/transactions/update-transaction.ts @@ -0,0 +1,191 @@ +/** + * Update Transaction Tool + * + * Updates an existing transaction. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type * as ynab from 'ynab'; +import type { YnabClient } from '../../services/ynab-client.js'; +import { formatCurrency, toMilliunits } from '../../utils/milliunits.js'; +import { sanitizeName, sanitizeMemo } from '../../utils/sanitize.js'; + +// Cleared status options +const clearedStatuses = ['cleared', 'uncleared', 'reconciled'] as const; + +// Flag colors +const flagColors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] as const; + +// Input schema +const inputSchema = z + .object({ + budget_id: z + .string() + .optional() + .describe('Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"'), + transaction_id: z.string().uuid().describe('The transaction UUID to update'), + account_id: z.string().uuid().optional().describe('New account UUID'), + date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .optional() + .describe('New transaction date in YYYY-MM-DD format'), + amount: z + .number() + .optional() + .describe('New amount in dollars (negative for outflow, positive for inflow)'), + payee_id: z.string().uuid().optional().describe('New payee UUID'), + payee_name: z.string().optional().describe('New payee name'), + category_id: z.string().uuid().optional().describe('New category UUID'), + memo: z.string().max(200).optional().describe('New memo/note'), + cleared: z.enum(clearedStatuses).optional().describe('New cleared status'), + approved: z.boolean().optional().describe('New approved status'), + flag_color: z.enum(flagColors).nullable().optional().describe('New flag color (null to remove)'), + }) + .refine( + (d) => + d.account_id !== undefined || + d.date !== undefined || + d.amount !== undefined || + d.payee_id !== undefined || + d.payee_name !== undefined || + d.category_id !== undefined || + d.memo !== undefined || + d.cleared !== undefined || + d.approved !== undefined || + d.flag_color !== undefined, + { message: 'Provide at least one field to update' } + ) + .refine((d) => !(d.payee_id && d.payee_name), { + message: 'Provide either payee_id or payee_name, not both', + }); + +// Tool definition +export const updateTransactionTool: Tool = { + name: 'ynab_update_transaction', + description: `Update an existing transaction. + +Use when the user asks: +- "Change the category on that transaction" +- "Update the amount" +- "Mark transaction as cleared" +- "Add a memo to the transaction" +- "Recategorize a transaction" + +Requires READ_ONLY mode to be disabled (YNAB_READ_ONLY=false). +Only provide the fields you want to change.`, + inputSchema: { + type: 'object', + properties: { + budget_id: { + type: 'string', + description: 'Budget UUID. Defaults to YNAB_BUDGET_ID env var or "last-used"', + }, + transaction_id: { + type: 'string', + description: 'The transaction UUID to update', + }, + account_id: { + type: 'string', + description: 'New account UUID', + }, + date: { + type: 'string', + description: 'New transaction date in YYYY-MM-DD format', + }, + amount: { + type: 'number', + description: 'New amount in dollars', + }, + payee_id: { + type: 'string', + description: 'New payee UUID', + }, + payee_name: { + type: 'string', + description: 'New payee name', + }, + category_id: { + type: 'string', + description: 'New category UUID', + }, + memo: { + type: 'string', + description: 'New memo/note', + }, + cleared: { + type: 'string', + enum: clearedStatuses, + description: 'New cleared status', + }, + approved: { + type: 'boolean', + description: 'New approved status', + }, + flag_color: { + type: ['string', 'null'], + enum: [...flagColors, null], + description: 'New flag color (null to remove)', + }, + }, + required: ['transaction_id'], + }, +}; + +// Handler function +/** + * Handler for the ynab_update_transaction tool. + */ +export async function handleUpdateTransaction( + args: Record, + client: YnabClient +): Promise { + const validated = inputSchema.parse(args); + const budgetId = client.resolveBudgetId(validated.budget_id); + + // Build update object with only provided fields using YNAB SDK type + const updateData: ynab.SaveTransactionWithOptionalFields = {}; + + if (validated.account_id !== undefined) updateData.account_id = validated.account_id; + if (validated.date !== undefined) updateData.date = validated.date; + if (validated.amount !== undefined) updateData.amount = toMilliunits(validated.amount); + if (validated.payee_id !== undefined) updateData.payee_id = validated.payee_id; + if (validated.payee_name !== undefined) updateData.payee_name = validated.payee_name; + if (validated.category_id !== undefined) updateData.category_id = validated.category_id; + if (validated.memo !== undefined) updateData.memo = validated.memo; + if (validated.cleared !== undefined) + updateData.cleared = + validated.cleared as unknown as ynab.SaveTransactionWithOptionalFields.ClearedEnum; + if (validated.approved !== undefined) updateData.approved = validated.approved; + if (validated.flag_color !== undefined) + updateData.flag_color = + validated.flag_color as unknown as ynab.SaveTransactionWithOptionalFields.FlagColorEnum | null; + + const response = await client.updateTransaction(budgetId, validated.transaction_id, { + transaction: updateData, + }); + + const txn = response.data.transaction; + + return JSON.stringify( + { + success: true, + message: `Transaction updated: ${formatCurrency(txn.amount)} at ${sanitizeName(txn.payee_name)}`, + transaction: { + id: txn.id, + date: txn.date, + amount: formatCurrency(txn.amount), + payee_name: sanitizeName(txn.payee_name), + category_name: sanitizeName(txn.category_name), + account_name: sanitizeName(txn.account_name), + memo: sanitizeMemo(txn.memo), + cleared: txn.cleared, + approved: txn.approved, + flag_color: txn.flag_color, + }, + }, + null, + 2 + ); +} diff --git a/src/tools/user/get-user.ts b/src/tools/user/get-user.ts new file mode 100644 index 0000000..bb94e37 --- /dev/null +++ b/src/tools/user/get-user.ts @@ -0,0 +1,54 @@ +/** + * Get User Tool + * + * Returns information about the authenticated user. + */ + +import { z } from 'zod'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; +import type { YnabClient } from '../../services/ynab-client.js'; + +// Input schema (no parameters needed) +const inputSchema = z.object({}).strict(); + +// Tool definition +export const getUserTool: Tool = { + name: 'ynab_get_user', + description: `Get information about the authenticated YNAB user. + +Use when the user asks: +- "Who am I logged in as?" +- "What's my YNAB user ID?" +- "Show my user ID" + +Returns the user's ID.`, + inputSchema: { + type: 'object', + properties: {}, + additionalProperties: false, + }, +}; + +// Handler function +/** + * Handler for the ynab_get_user tool. + */ +export async function handleGetUser( + args: Record, + client: YnabClient +): Promise { + inputSchema.parse(args); + + const response = await client.getUser(); + const user = response.data.user; + + return JSON.stringify( + { + user: { + id: user.id, + }, + }, + null, + 2 + ); +} diff --git a/src/utils/dates.ts b/src/utils/dates.ts new file mode 100644 index 0000000..23822d5 --- /dev/null +++ b/src/utils/dates.ts @@ -0,0 +1,261 @@ +/** + * Date Utilities + * + * Provides natural language date parsing and date range helpers. + * + * IMPORTANT: Time zone behavior varies by function: + * + * - parseNaturalDate(), formatDate(), getDateRange(): Use LOCAL time. + * These are designed for user-facing input/output where local dates make sense. + * + * - getCurrentMonth(), getPreviousMonth(): Use UTC time. + * These are designed for YNAB API calls where UTC consistency is needed. + * + * - daysBetween(): Uses UTC to avoid DST edge cases. + * + * - isValidIsoDate(), getMonthStart(): Pure string operations, no timezone concerns. + * + * This split is intentional: user input (e.g., "yesterday") should respect local time, + * while API-facing functions use UTC for consistency across time zones. + */ + +/** + * Parse natural language date expressions into YYYY-MM-DD format. + * + * Uses LOCAL time for all calculations. This is appropriate for user-facing + * input where "today" and "yesterday" should reflect the user's local date. + * + * Supported expressions: + * - "today", "yesterday" + * - "this week", "last week" - Returns start of week (Sunday) + * - "this month", "last month" - Returns first of month + * - "this year", "last year" - Returns January 1st of the year + * - "past N days", "last N days" - N days ago from today + * - "past N weeks", "last N weeks" - N*7 days ago from today + * - "past N months", "last N months" - First of the month, N months ago + * - "past N years", "last N years" - Same day, N years ago + * - ISO dates (YYYY-MM-DD) - Validated and passed through + * + * Note: "last year" returns January 1st of previous year (calendar year start), + * while "last 1 year" returns the same day one year ago (relative date). + * This matches common usage: "last year's transactions" vs "past year of data". + * + * @param input - Natural language date string or ISO date + * @returns ISO date string (YYYY-MM-DD) + */ +export function parseNaturalDate(input: string): string { + const normalized = input.toLowerCase().trim(); + const today = new Date(); + today.setHours(0, 0, 0, 0); + + // ISO date format - validate and pass through + if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) { + // Validate the date is actually valid (not 2024-99-99 or 2024-02-30) + const parts = normalized.split('-'); + const year = parseInt(parts[0] ?? '0', 10); + const month = parseInt(parts[1] ?? '0', 10); + const day = parseInt(parts[2] ?? '0', 10); + + if (month >= 1 && month <= 12) { + const daysInMonth = new Date(year, month, 0).getDate(); + if (day >= 1 && day <= daysInMonth) { + return normalized; + } + } + // Invalid date values - fall through to throw error + } + + // Today / Yesterday + if (normalized === 'today') { + return formatDate(today); + } + + if (normalized === 'yesterday') { + const yesterday = new Date(today); + yesterday.setDate(yesterday.getDate() - 1); + return formatDate(yesterday); + } + + // This week (start of current week - Sunday) + if (normalized === 'this week') { + const startOfWeek = new Date(today); + startOfWeek.setDate(today.getDate() - today.getDay()); + return formatDate(startOfWeek); + } + + // Last week (start of previous week) + if (normalized === 'last week') { + const startOfLastWeek = new Date(today); + startOfLastWeek.setDate(today.getDate() - today.getDay() - 7); + return formatDate(startOfLastWeek); + } + + // This month (first of current month) + if (normalized === 'this month') { + const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); + return formatDate(startOfMonth); + } + + // Last month (first of previous month) + if (normalized === 'last month') { + const startOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1); + return formatDate(startOfLastMonth); + } + + // This year (January 1st of current year) + if (normalized === 'this year') { + const startOfYear = new Date(today.getFullYear(), 0, 1); + return formatDate(startOfYear); + } + + // Last year (January 1st of previous year) + if (normalized === 'last year') { + const startOfLastYear = new Date(today.getFullYear() - 1, 0, 1); + return formatDate(startOfLastYear); + } + + // Past N days (e.g., "past 7 days", "past 30 days", "last 7 days") + const pastDaysMatch = normalized.match(/^(?:past|last)\s+(\d+)\s+days?$/); + if (pastDaysMatch) { + const days = parseInt(pastDaysMatch[1] ?? '0', 10); + const pastDate = new Date(today); + pastDate.setDate(today.getDate() - days); + return formatDate(pastDate); + } + + // Past N weeks (e.g., "past 2 weeks", "last 4 weeks") + const pastWeeksMatch = normalized.match(/^(?:past|last)\s+(\d+)\s+weeks?$/); + if (pastWeeksMatch) { + const weeks = parseInt(pastWeeksMatch[1] ?? '0', 10); + const pastDate = new Date(today); + pastDate.setDate(today.getDate() - weeks * 7); + return formatDate(pastDate); + } + + // Past N months (e.g., "past 3 months", "last 6 months") + // Set day to 1 first to avoid month overflow (e.g., Mar 31 - 1 month = Feb 31 = Mar 3) + const pastMonthsMatch = normalized.match(/^(?:past|last)\s+(\d+)\s+months?$/); + if (pastMonthsMatch) { + const months = parseInt(pastMonthsMatch[1] ?? '0', 10); + const pastDate = new Date(today); + pastDate.setDate(1); + pastDate.setMonth(today.getMonth() - months); + return formatDate(pastDate); + } + + // Past N years (e.g., "past 2 years", "last year") + const pastYearsMatch = normalized.match(/^(?:past|last)\s+(\d+)\s+years?$/); + if (pastYearsMatch) { + const years = parseInt(pastYearsMatch[1] ?? '0', 10); + const pastDate = new Date(today); + const originalMonth = today.getMonth(); + pastDate.setFullYear(today.getFullYear() - years); + + // Handle leap year edge case: if month rolled over, set to last day of previous month + if (pastDate.getMonth() !== originalMonth) { + pastDate.setDate(0); // Sets to last day of previous month + } + + return formatDate(pastDate); + } + + // Unrecognized format - throw error with helpful message + throw new Error( + `Unrecognized date format: "${input}". Use ISO format (YYYY-MM-DD) or natural language like "past 7 days", "this month", "last week".` + ); +} + +/** + * Get a date range object for common periods. + * Uses LOCAL time (via parseNaturalDate). + */ +export function getDateRange(period: string): { start: string; end: string } { + const today = new Date(); + today.setHours(0, 0, 0, 0); + const endDate = formatDate(today); + + const startDate = parseNaturalDate(period); + + return { start: startDate, end: endDate }; +} + +/** + * Get the first day of a month in YYYY-MM-DD format. + */ +export function getMonthStart(year: number, month: number): string { + return `${year}-${String(month).padStart(2, '0')}-01`; +} + +/** + * Get the current month in YYYY-MM-DD format (first day). + * Uses UTC to ensure consistency with daysBetween() and other date functions. + */ +export function getCurrentMonth(): string { + const today = new Date(); + return getMonthStart(today.getUTCFullYear(), today.getUTCMonth() + 1); +} + +/** + * Get the previous month in YYYY-MM-DD format (first day). + * Uses UTC to ensure consistency with daysBetween() and other date functions. + */ +export function getPreviousMonth(): string { + const today = new Date(); + const year = today.getUTCFullYear(); + const month = today.getUTCMonth(); + // Handle January -> December of previous year + const prevYear = month === 0 ? year - 1 : year; + const prevMonth = month === 0 ? 12 : month; + return getMonthStart(prevYear, prevMonth); +} + +/** + * Format a Date object as YYYY-MM-DD. + * Uses the Date object's LOCAL time components (getFullYear, getMonth, getDate). + */ +export function formatDate(date: Date): string { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; +} + +/** + * Check if a string is a valid ISO date (YYYY-MM-DD). + */ +export function isValidIsoDate(input: string): boolean { + if (!/^\d{4}-\d{2}-\d{2}$/.test(input)) { + return false; + } + + // Parse the components + const parts = input.split('-'); + const year = parseInt(parts[0] ?? '0', 10); + const month = parseInt(parts[1] ?? '0', 10); + const day = parseInt(parts[2] ?? '0', 10); + + // Check month range + if (month < 1 || month > 12) { + return false; + } + + // Check day range for the specific month + const daysInMonth = new Date(year, month, 0).getDate(); + if (day < 1 || day > daysInMonth) { + return false; + } + + return true; +} + +/** + * Get the number of days between two dates. + * Uses UTC midnight to avoid timezone/DST off-by-one errors. + */ +export function daysBetween(start: string, end: string): number { + // Parse to UTC midnight to avoid timezone issues + const startDate = new Date(start + 'T00:00:00Z'); + const endDate = new Date(end + 'T00:00:00Z'); + const diffTime = Math.abs(endDate.getTime() - startDate.getTime()); + return Math.round(diffTime / (1000 * 60 * 60 * 24)); +} diff --git a/src/utils/errors.ts b/src/utils/errors.ts new file mode 100644 index 0000000..d5a593c --- /dev/null +++ b/src/utils/errors.ts @@ -0,0 +1,244 @@ +/** + * Custom Error Classes + * + * Provides structured error handling for the YNAB MCP server. + */ + +import { sanitizeErrorMessage } from './sanitize.js'; + +/** + * Error thrown when a write operation is attempted in read-only mode. + */ +export class ReadOnlyModeError extends Error { + constructor(operation: string) { + super( + `Operation "${operation}" is not allowed: server is in READ_ONLY mode. ` + + `Set YNAB_READ_ONLY=false in your .env file to enable write operations.` + ); + this.name = 'ReadOnlyModeError'; + } +} + +/** + * Error thrown when the YNAB API returns an error. + */ +export class YnabApiError extends Error { + constructor( + message: string, + public readonly code: string, + public readonly details?: unknown + ) { + super(message); + this.name = 'YnabApiError'; + } +} + +/** + * Error thrown when input validation fails. + */ +export class ValidationError extends Error { + constructor( + message: string, + public readonly field?: string + ) { + super(message); + this.name = 'ValidationError'; + } +} + +/** + * Error thrown when rate limit is exceeded. + * + * Note: The server uses a configurable rate limit budget (default 180 requests/hour), + * which is 10% below YNAB's official limit of 200 requests/hour. This provides a + * safety margin for concurrent requests and avoids hitting the hard limit. + * The actual limit is set via RATE_LIMIT_PER_HOUR environment variable. + */ +export class RateLimitError extends Error { + constructor(public readonly retryAfterMs?: number) { + super('Rate limit exceeded. Please wait before making more requests.'); + this.name = 'RateLimitError'; + } +} + +/** + * Error thrown when a resource is not found. + */ +export class NotFoundError extends Error { + constructor(resource: string, id: string) { + super(`${resource} not found: ${id}`); + this.name = 'NotFoundError'; + } +} + +/** + * YNAB API error codes and their meanings. + */ +export const YNAB_ERROR_CODES: Record = { + '400': { + message: 'Bad request', + suggestion: 'Check that all required parameters are provided and valid.', + }, + '401': { + message: 'Unauthorized', + suggestion: 'Authentication failed. Verify your credentials are valid and try again.', + }, + '403': { + message: 'Forbidden', + suggestion: 'You do not have permission to access this resource.', + }, + '404': { + message: 'Not found', + suggestion: 'The requested resource does not exist. Check the ID is correct.', + }, + '409': { + message: 'Conflict', + suggestion: 'The resource has been modified. Refresh and try again.', + }, + '429': { + message: 'Too many requests', + suggestion: 'Rate limit exceeded. Wait a moment before retrying.', + }, + '500': { + message: 'Internal server error', + suggestion: 'YNAB is experiencing issues. Try again later.', + }, + '503': { + message: 'Service unavailable', + suggestion: 'YNAB is temporarily unavailable. Try again later.', + }, +}; + +/** + * Format an error as a structured JSON response for tool output. + */ +export function formatErrorResponse(error: unknown): string { + if (error instanceof ReadOnlyModeError) { + return JSON.stringify({ + error: true, + type: 'read_only_mode', + message: 'Write operation not allowed in read-only mode', + suggestion: 'Set YNAB_READ_ONLY=false in your environment to enable write operations.', + }, null, 2); + } + + if (error instanceof RateLimitError) { + return JSON.stringify({ + error: true, + type: 'rate_limit', + message: 'Rate limit exceeded', + retry_after_ms: error.retryAfterMs, + // Note: Server uses 180 req/hr budget (10% below YNAB's 200 limit) for safety margin + suggestion: 'Wait before making more requests. Check ynab_rate_limit_status for current limits.', + }, null, 2); + } + + if (error instanceof ValidationError) { + return JSON.stringify({ + error: true, + type: 'validation_error', + message: sanitizeErrorMessage(error.message) || 'Validation failed', + field: error.field, + suggestion: 'Check that all input parameters are valid.', + }, null, 2); + } + + if (error instanceof NotFoundError) { + return JSON.stringify({ + error: true, + type: 'not_found', + message: sanitizeErrorMessage(error.message) || 'Resource not found', + suggestion: 'Verify the ID exists by listing available resources first.', + }, null, 2); + } + + if (error instanceof YnabApiError) { + const errorInfo = YNAB_ERROR_CODES[error.code] ?? { + message: 'Unknown error', + suggestion: 'Check the YNAB API documentation for more information.', + }; + // Log sanitized error server-side for debugging (no raw details) + console.error('[YnabApiError]', error.code, sanitizeErrorMessage(error.message)); + // Return mapped message only (no upstream error text to prevent data leakage) + return JSON.stringify({ + error: true, + type: 'ynab_api_error', + code: error.code, + message: errorInfo.message, + suggestion: errorInfo.suggestion, + }, null, 2); + } + + // Handle YNAB SDK errors + if (isYnabSdkError(error)) { + const statusCode = String(error.error?.id ?? 'unknown'); + const errorInfo = YNAB_ERROR_CODES[statusCode] ?? { + message: 'Unknown error', + suggestion: 'Check the YNAB API documentation.', + }; + // Log sanitized error server-side for debugging + console.error('[YnabSdkError]', statusCode, sanitizeErrorMessage(error.error?.detail)); + // Return mapped message only (no upstream error text to prevent data leakage) + return JSON.stringify({ + error: true, + type: 'ynab_api_error', + code: statusCode, + message: errorInfo.message, + suggestion: errorInfo.suggestion, + }, null, 2); + } + + // Handle Zod validation errors + if (isZodError(error)) { + const issues = error.issues.map((issue: { path?: unknown; message?: unknown }) => { + // Defensive checks for malformed issue shapes + const path = Array.isArray(issue.path) ? issue.path.join('.') : ''; + const message = typeof issue.message === 'string' + ? sanitizeErrorMessage(issue.message) + : 'Validation error'; + return { field: path, message }; + }); + return JSON.stringify({ + error: true, + type: 'validation_error', + message: 'Invalid input parameters', + issues, + suggestion: 'Check that all required parameters are provided with correct types.', + }, null, 2); + } + + // Generic error - log sanitized error server-side, return sanitized message + console.error('[UnknownError]', sanitizeErrorMessage(error)); + return JSON.stringify({ + error: true, + type: 'unknown_error', + message: sanitizeErrorMessage(error), + suggestion: 'An unexpected error occurred. Check the server logs for details.', + }, null, 2); +} + +/** + * Type guard for YNAB SDK errors. + */ +function isYnabSdkError(error: unknown): error is { error: { id: string; detail?: string } } { + return ( + typeof error === 'object' && + error !== null && + 'error' in error && + typeof (error as { error: unknown }).error === 'object' && + (error as { error: { id?: unknown } }).error !== null && + 'id' in ((error as { error: object }).error) + ); +} + +/** + * Type guard for Zod validation errors. + */ +function isZodError(error: unknown): error is { issues: { path: (string | number)[]; message: string }[] } { + return ( + typeof error === 'object' && + error !== null && + 'issues' in error && + Array.isArray((error as { issues: unknown }).issues) + ); +} diff --git a/src/utils/milliunits.ts b/src/utils/milliunits.ts new file mode 100644 index 0000000..2247a61 --- /dev/null +++ b/src/utils/milliunits.ts @@ -0,0 +1,146 @@ +/** + * Milliunit Utilities + * + * YNAB uses "milliunits" for all currency values: + * - 1 dollar = 1000 milliunits + * - $10.50 = 10500 milliunits + * - -$25.00 = -25000 milliunits + * + * IMPORTANT: Always use Decimal.js for currency calculations + * to avoid floating point errors. + */ + +import DecimalJS from 'decimal.js'; +import type { CurrencyFormat } from 'ynab'; + +// Get the Decimal constructor +const Decimal = DecimalJS.default ?? DecimalJS; + +// Configure Decimal.js for financial calculations +Decimal.set({ precision: 20, rounding: Decimal.ROUND_HALF_UP }); + +/** + * Convert milliunits to a formatted currency string. + * + * @param milliunits - The amount in milliunits (1000 = $1.00) + * @param currencySymbol - The currency symbol to use (default: '$') + * @returns Formatted string like "$10.50" or "-$25.00" + */ +export function formatCurrency(milliunits: number, currencySymbol = '$'): string { + const dollars = new Decimal(milliunits).dividedBy(1000); + const isNegative = dollars.isNegative(); + const absolute = dollars.absoluteValue(); + const formatted = absolute.toFixed(2); + + return isNegative ? `-${currencySymbol}${formatted}` : `${currencySymbol}${formatted}`; +} + +/** + * Convert milliunits to a formatted currency string using YNAB's CurrencyFormat. + * + * This respects the budget's currency settings including: + * - Currency symbol and position (symbol_first) + * - Decimal separator (. vs ,) + * - Group separator (, vs . vs space) + * - Number of decimal digits + * + * @param milliunits - The amount in milliunits (1000 = 1 currency unit) + * @param format - YNAB CurrencyFormat object from budget settings + * @returns Formatted string like "$10.50", "10,50 €", etc. + */ +export function formatCurrencyWithFormat( + milliunits: number, + format: CurrencyFormat +): string { + const amount = new Decimal(milliunits).dividedBy(1000); + const isNegative = amount.isNegative(); + const absolute = amount.absoluteValue(); + + // Format with the correct number of decimal digits + const formatted = absolute.toFixed(format.decimal_digits); + const parts = formatted.split('.'); + const intPart = parts[0] ?? '0'; + const decPart = parts[1] ?? ''; + + // Add group separators to the integer part (e.g., 1000000 -> 1,000,000) + const intWithSeparators = intPart.replace( + /\B(?=(\d{3})+(?!\d))/g, + format.group_separator + ); + + // Combine integer and decimal parts with the correct decimal separator + const withSeparators = decPart + ? `${intWithSeparators}${format.decimal_separator}${decPart}` + : intWithSeparators; + + // Add currency symbol in the correct position + const symbol = format.display_symbol ? format.currency_symbol : ''; + const withSymbol = format.symbol_first + ? `${symbol}${withSeparators}` + : `${withSeparators}${symbol}`; + + return isNegative ? `-${withSymbol}` : withSymbol; +} + +/** + * Convert milliunits to a decimal dollar amount. + * + * @param milliunits - The amount in milliunits + * @returns Decimal instance representing the dollar amount + */ +export function toDecimal(milliunits: number): InstanceType { + return new Decimal(milliunits).dividedBy(1000); +} + +/** + * Convert a dollar amount to milliunits. + * + * @param dollars - The dollar amount (can be string or number) + * @returns Integer milliunits + */ +export function toMilliunits(dollars: number | string): number { + return new Decimal(dollars).times(1000).round().toNumber(); +} + +/** + * Convert milliunits to cents (useful for some integrations). + * + * @param milliunits - The amount in milliunits + * @returns Integer cents + */ +export function toCents(milliunits: number): number { + return new Decimal(milliunits).dividedBy(10).round().toNumber(); +} + +/** + * Add two milliunit amounts safely. + */ +export function addMilliunits(a: number, b: number): number { + return new Decimal(a).plus(b).toNumber(); +} + +/** + * Subtract two milliunit amounts safely. + */ +export function subtractMilliunits(a: number, b: number): number { + return new Decimal(a).minus(b).toNumber(); +} + +/** + * Sum an array of milliunit amounts. + */ +export function sumMilliunits(amounts: number[]): number { + return amounts.reduce((sum, amt) => new Decimal(sum).plus(amt).toNumber(), 0); +} + +/** + * Calculate percentage of one milliunit amount relative to another. + * + * @param part - The partial amount + * @param whole - The total amount + * @returns Percentage as a number (0-100) + */ +export function percentageOfMilliunits(part: number, whole: number): number { + if (whole === 0) return 0; + return new Decimal(part).dividedBy(whole).times(100).toDecimalPlaces(1).toNumber(); +} diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts new file mode 100644 index 0000000..24b50c1 --- /dev/null +++ b/src/utils/sanitize.ts @@ -0,0 +1,144 @@ +/** + * String Sanitization Utilities + * + * Sanitizes user-controlled strings before including in responses + * to prevent log forging, injection, and other security issues. + */ + +/** + * Sanitize a user-provided string for safe output. + * + * - Removes control characters (except common whitespace) + * - Trims whitespace + * - Enforces maximum length + * - Returns null for null/undefined input + */ +export function sanitizeString( + input: string | null | undefined, + maxLength: number = 500 +): string | null { + if (input === null || input === undefined) { + return null; + } + + // Ensure maxLength is a valid positive integer + const effectiveMaxLength = Math.max(1, Math.floor(Number(maxLength) || 500)); + + // Convert to string if not already + const str = String(input); + + // Remove control characters except tab, newline, carriage return + // Includes: ASCII controls (0x00-0x1F, 0x7F), C1 controls (0x80-0x9F), + // zero-width characters (U+200B-U+200F, U+FEFF), + // and Unicode line/paragraph separators (U+2028, U+2029) which can break JS string literals + // eslint-disable-next-line no-control-regex + const cleaned = str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x80-\x9F\u200B-\u200F\u2028\u2029\uFEFF]/g, ''); + + // Trim whitespace + const trimmed = cleaned.trim(); + + // Enforce max length (reserve space for ellipsis to stay within limit) + if (trimmed.length > effectiveMaxLength) { + if (effectiveMaxLength <= 3) { + return trimmed.substring(0, effectiveMaxLength); + } + return trimmed.substring(0, effectiveMaxLength - 3) + '...'; + } + + return trimmed; +} + +/** + * Sanitize a string, returning empty string instead of null for missing input. + * Useful when a non-null string is required. + */ +export function sanitizeStringOrEmpty( + input: string | null | undefined, + maxLength: number = 500 +): string { + return sanitizeString(input, maxLength) ?? ''; +} + +/** + * Sanitize a memo or note field (allows slightly longer content). + */ +export function sanitizeMemo(input: string | null | undefined): string | null { + return sanitizeString(input, 1000); +} + +/** + * Sanitize a name field (account name, category name, payee name). + * Returns 'Unknown' for null, undefined, or empty/whitespace-only input. + */ +export function sanitizeName(input: string | null | undefined): string { + const sanitized = sanitizeString(input, 200); + return sanitized && sanitized.length > 0 ? sanitized : 'Unknown'; +} + +/** + * Patterns that may indicate sensitive data in error messages. + * Used to redact potential tokens, paths, and other sensitive information. + */ +const SENSITIVE_PATTERNS: { pattern: RegExp; replacement: string }[] = [ + // API tokens and keys (various formats) + { pattern: /Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: 'Bearer [REDACTED]' }, + { pattern: /token[=:]\s*["']?[A-Za-z0-9\-._~+/]+["']?/gi, replacement: 'token=[REDACTED]' }, + { pattern: /key[=:]\s*["']?[A-Za-z0-9\-._~+/]+["']?/gi, replacement: 'key=[REDACTED]' }, + { pattern: /api[_-]?key[=:]\s*["']?[A-Za-z0-9\-._~+/]+["']?/gi, replacement: 'api_key=[REDACTED]' }, + { pattern: /access[_-]?token[=:]\s*["']?[A-Za-z0-9\-._~+/]+["']?/gi, replacement: 'access_token=[REDACTED]' }, + { pattern: /authorization[=:]\s*["']?[A-Za-z0-9\-._~+/]+["']?/gi, replacement: 'authorization=[REDACTED]' }, + // Passwords and secrets (various naming conventions) + { pattern: /password[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'password=[REDACTED]' }, + { pattern: /passwd[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'passwd=[REDACTED]' }, + { pattern: /pwd[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'pwd=[REDACTED]' }, + { pattern: /secret[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'secret=[REDACTED]' }, + { pattern: /secret[_-]?key[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'secret_key=[REDACTED]' }, + { pattern: /private[_-]?key[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'private_key=[REDACTED]' }, + { pattern: /credential[s]?[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'credentials=[REDACTED]' }, + { pattern: /auth[=:]\s*["']?[^\s"']+["']?/gi, replacement: 'auth=[REDACTED]' }, + // Connection strings and database URLs (may contain credentials) + { pattern: /(?:mongodb|postgres|mysql|redis|amqp):\/\/[^\s"']+/gi, replacement: '[CONNECTION_STRING_REDACTED]' }, + // File paths (Unix and Windows) + { pattern: /\/(?:Users|home|var|etc|tmp|app|opt|srv|root)\/[^\s"']+/gi, replacement: '[PATH_REDACTED]' }, + { pattern: /[A-Z]:\\(?:Users|Windows|Program Files)[^\s"']*/gi, replacement: '[PATH_REDACTED]' }, + // Stack trace file references + { pattern: /at\s+[^\s]+\s+\([^)]+:\d+:\d+\)/g, replacement: 'at [STACK_REDACTED]' }, + { pattern: /\([^)]+\.(?:ts|js):\d+:\d+\)/g, replacement: '([FILE_REDACTED])' }, +]; + +/** + * Sanitize an error message to remove sensitive data. + * + * Removes: + * - API tokens and authentication headers + * - File system paths + * - Stack trace details + * - Control characters + * + * @param error - The error to sanitize (Error object, string, or unknown) + * @param maxLength - Maximum length of the output (default 500) + * @returns A sanitized error message safe for logging and responses + */ +export function sanitizeErrorMessage( + error: unknown, + maxLength: number = 500 +): string { + // Extract message from error + let message: string; + if (error instanceof Error) { + message = error.message; + } else if (typeof error === 'string') { + message = error; + } else { + message = 'An error occurred'; + } + + // Apply sensitive pattern redactions + let sanitized = message; + for (const { pattern, replacement } of SENSITIVE_PATTERNS) { + sanitized = sanitized.replace(pattern, replacement); + } + + // Remove control characters and enforce length limit + return sanitizeStringOrEmpty(sanitized, maxLength); +} diff --git a/tests/unit/services/audit-log.test.ts b/tests/unit/services/audit-log.test.ts new file mode 100644 index 0000000..24455c9 --- /dev/null +++ b/tests/unit/services/audit-log.test.ts @@ -0,0 +1,236 @@ +/** + * Audit Log Service Tests + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AuditLog } from '../../../src/services/audit-log.js'; + +describe('AuditLog', () => { + let auditLog: AuditLog; + + beforeEach(() => { + auditLog = new AuditLog(100); + }); + + describe('log', () => { + it('should add entries with timestamp', () => { + auditLog.log({ + operation: 'create', + tool: 'ynab_create_transaction', + budgetId: 'budget-123', + resourceType: 'transaction', + resourceId: 'txn-456', + details: { amount: 10000 }, + success: true, + }); + + const entries = auditLog.getAll(); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + operation: 'create', + tool: 'ynab_create_transaction', + budgetId: 'budget-123', + resourceType: 'transaction', + resourceId: 'txn-456', + success: true, + }); + expect(entries[0]?.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/); + }); + + it('should log errors for failed operations', () => { + auditLog.log({ + operation: 'create', + tool: 'ynab_create_transaction', + budgetId: 'budget-123', + resourceType: 'transaction', + details: {}, + success: false, + error: 'API rate limit exceeded', + }); + + const entries = auditLog.getAll(); + expect(entries[0]?.success).toBe(false); + expect(entries[0]?.error).toBe('API rate limit exceeded'); + }); + + it('should trim old entries when exceeding max', () => { + const smallLog = new AuditLog(3); + + for (let i = 0; i < 5; i++) { + smallLog.log({ + operation: 'create', + tool: 'test_tool', + budgetId: 'budget-123', + resourceType: 'transaction', + details: { index: i }, + success: true, + }); + } + + const entries = smallLog.getAll(); + expect(entries).toHaveLength(3); + // Should have the last 3 entries (index 2, 3, 4) + expect((entries[0]?.details as { index: number }).index).toBe(2); + expect((entries[2]?.details as { index: number }).index).toBe(4); + }); + }); + + describe('getFiltered', () => { + beforeEach(() => { + // Add various entries for filtering tests + auditLog.log({ + operation: 'create', + tool: 'ynab_create_transaction', + budgetId: 'budget-1', + resourceType: 'transaction', + details: {}, + success: true, + }); + auditLog.log({ + operation: 'update', + tool: 'ynab_update_transaction', + budgetId: 'budget-1', + resourceType: 'transaction', + details: {}, + success: true, + }); + auditLog.log({ + operation: 'delete', + tool: 'ynab_delete_transaction', + budgetId: 'budget-2', + resourceType: 'transaction', + details: {}, + success: false, + error: 'Not found', + }); + auditLog.log({ + operation: 'create', + tool: 'ynab_create_account', + budgetId: 'budget-1', + resourceType: 'account', + details: {}, + success: true, + }); + }); + + it('should filter by operation', () => { + const entries = auditLog.getFiltered({ operation: 'create' }); + expect(entries).toHaveLength(2); + expect(entries.every((e) => e.operation === 'create')).toBe(true); + }); + + it('should filter by resourceType', () => { + const entries = auditLog.getFiltered({ resourceType: 'account' }); + expect(entries).toHaveLength(1); + expect(entries[0]?.resourceType).toBe('account'); + }); + + it('should filter by success', () => { + const failed = auditLog.getFiltered({ success: false }); + expect(failed).toHaveLength(1); + expect(failed[0]?.success).toBe(false); + + const succeeded = auditLog.getFiltered({ success: true }); + expect(succeeded).toHaveLength(3); + }); + + it('should filter by budgetId', () => { + const entries = auditLog.getFiltered({ budgetId: 'budget-2' }); + expect(entries).toHaveLength(1); + expect(entries[0]?.budgetId).toBe('budget-2'); + }); + + it('should limit results', () => { + const entries = auditLog.getFiltered({ limit: 2 }); + expect(entries).toHaveLength(2); + }); + + it('should return most recent first', () => { + const entries = auditLog.getFiltered({}); + // Last logged is account creation + expect(entries[0]?.resourceType).toBe('account'); + }); + + it('should combine multiple filters', () => { + const entries = auditLog.getFiltered({ + operation: 'create', + resourceType: 'transaction', + }); + expect(entries).toHaveLength(1); + expect(entries[0]?.tool).toBe('ynab_create_transaction'); + }); + }); + + describe('getSummary', () => { + it('should return empty summary for no entries', () => { + const summary = auditLog.getSummary(); + expect(summary.totalOperations).toBe(0); + expect(summary.successCount).toBe(0); + expect(summary.failureCount).toBe(0); + expect(summary.oldestEntry).toBeUndefined(); + expect(summary.newestEntry).toBeUndefined(); + }); + + it('should return correct counts', () => { + auditLog.log({ + operation: 'create', + tool: 'test', + budgetId: 'b1', + resourceType: 'transaction', + details: {}, + success: true, + }); + auditLog.log({ + operation: 'create', + tool: 'test', + budgetId: 'b1', + resourceType: 'transaction', + details: {}, + success: false, + error: 'test error', + }); + auditLog.log({ + operation: 'update', + tool: 'test', + budgetId: 'b1', + resourceType: 'account', + details: {}, + success: true, + }); + + const summary = auditLog.getSummary(); + expect(summary.totalOperations).toBe(3); + expect(summary.successCount).toBe(2); + expect(summary.failureCount).toBe(1); + expect(summary.byOperation).toEqual({ create: 2, update: 1 }); + expect(summary.byResourceType).toEqual({ transaction: 2, account: 1 }); + expect(summary.oldestEntry).toBeDefined(); + expect(summary.newestEntry).toBeDefined(); + }); + }); + + describe('clear', () => { + it('should clear all entries and return count', () => { + auditLog.log({ + operation: 'create', + tool: 'test', + budgetId: 'b1', + resourceType: 'transaction', + details: {}, + success: true, + }); + auditLog.log({ + operation: 'update', + tool: 'test', + budgetId: 'b1', + resourceType: 'transaction', + details: {}, + success: true, + }); + + const count = auditLog.clear(); + expect(count).toBe(2); + expect(auditLog.getAll()).toHaveLength(0); + }); + }); +}); diff --git a/tests/unit/services/cache.test.ts b/tests/unit/services/cache.test.ts new file mode 100644 index 0000000..ce21733 --- /dev/null +++ b/tests/unit/services/cache.test.ts @@ -0,0 +1,197 @@ +/** + * Cache Service Tests + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { Cache } from '../../../src/services/cache.js'; + +describe('Cache', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + describe('constructor', () => { + it('should accept valid positive TTL', () => { + const cache = new Cache(5000); + cache.set('key', 'value'); + expect(cache.get('key')).toBe('value'); + }); + + it('should throw on NaN default TTL', () => { + expect(() => new Cache(NaN)).toThrow('Invalid default TTL'); + }); + + it('should throw on Infinity default TTL', () => { + expect(() => new Cache(Infinity)).toThrow('Invalid default TTL'); + }); + + it('should throw on negative default TTL', () => { + expect(() => new Cache(-1000)).toThrow('Invalid default TTL'); + }); + + it('should throw on zero default TTL', () => { + expect(() => new Cache(0)).toThrow('Invalid default TTL'); + }); + }); + + describe('get/set', () => { + it('should store and retrieve values', () => { + const cache = new Cache(); + cache.set('key', { data: 'test' }); + expect(cache.get('key')).toEqual({ data: 'test' }); + }); + + it('should return undefined for missing keys', () => { + const cache = new Cache(); + expect(cache.get('nonexistent')).toBeUndefined(); + }); + + it('should return undefined for expired keys', () => { + const cache = new Cache(1000); // 1 second TTL + cache.set('key', 'value'); + + // Advance time past TTL + vi.advanceTimersByTime(2000); + + expect(cache.get('key')).toBeUndefined(); + }); + + it('should allow custom TTL per item', () => { + const cache = new Cache(10000); // 10 second default + cache.set('short', 'value', 1000); // 1 second TTL + cache.set('long', 'value', 5000); // 5 second TTL + + vi.advanceTimersByTime(2000); + + expect(cache.get('short')).toBeUndefined(); + expect(cache.get('long')).toBe('value'); + }); + + it('should throw on NaN TTL', () => { + const cache = new Cache(); + expect(() => cache.set('key', 'value', NaN)).toThrow('Invalid TTL'); + }); + + it('should throw on Infinity TTL', () => { + const cache = new Cache(); + expect(() => cache.set('key', 'value', Infinity)).toThrow('Invalid TTL'); + }); + + it('should throw on negative TTL', () => { + const cache = new Cache(); + expect(() => cache.set('key', 'value', -1000)).toThrow('Invalid TTL'); + }); + + it('should throw on zero TTL', () => { + const cache = new Cache(); + expect(() => cache.set('key', 'value', 0)).toThrow('Invalid TTL'); + }); + }); + + describe('delete', () => { + it('should delete specific keys', () => { + const cache = new Cache(); + cache.set('key1', 'value1'); + cache.set('key2', 'value2'); + + const deleted = cache.delete('key1'); + + expect(deleted).toBe(true); + expect(cache.get('key1')).toBeUndefined(); + expect(cache.get('key2')).toBe('value2'); + }); + + it('should return false for missing keys', () => { + const cache = new Cache(); + expect(cache.delete('nonexistent')).toBe(false); + }); + }); + + describe('deleteByPrefix', () => { + it('should delete all keys with matching prefix', () => { + const cache = new Cache(); + cache.set('budget:123:accounts', 'data1'); + cache.set('budget:123:categories', 'data2'); + cache.set('budget:456:accounts', 'data3'); + cache.set('other', 'data4'); + + const count = cache.deleteByPrefix('budget:123'); + + expect(count).toBe(2); + expect(cache.get('budget:123:accounts')).toBeUndefined(); + expect(cache.get('budget:123:categories')).toBeUndefined(); + expect(cache.get('budget:456:accounts')).toBe('data3'); + expect(cache.get('other')).toBe('data4'); + }); + + it('should return 0 when no keys match the prefix', () => { + const cache = new Cache(); + cache.set('budget:123:accounts', 'data1'); + cache.set('budget:456:accounts', 'data2'); + cache.set('other', 'data3'); + + const count = cache.deleteByPrefix('nonexistent:prefix'); + + expect(count).toBe(0); + // Verify no entries were deleted + expect(cache.get('budget:123:accounts')).toBe('data1'); + expect(cache.get('budget:456:accounts')).toBe('data2'); + expect(cache.get('other')).toBe('data3'); + expect(cache.size()).toBe(3); + }); + }); + + describe('clear', () => { + it('should remove all entries', () => { + const cache = new Cache(); + cache.set('key1', 'value1'); + cache.set('key2', 'value2'); + + cache.clear(); + + expect(cache.size()).toBe(0); + expect(cache.get('key1')).toBeUndefined(); + }); + }); + + describe('size', () => { + it('should return number of entries', () => { + const cache = new Cache(); + expect(cache.size()).toBe(0); + + cache.set('key1', 'value1'); + expect(cache.size()).toBe(1); + + cache.set('key2', 'value2'); + expect(cache.size()).toBe(2); + }); + }); + + describe('prune', () => { + it('should remove expired entries', () => { + const cache = new Cache(); + cache.set('short', 'value', 1000); + cache.set('long', 'value', 10000); + + vi.advanceTimersByTime(2000); + + const pruned = cache.prune(); + + expect(pruned).toBe(1); + expect(cache.size()).toBe(1); + }); + + it('should return 0 when no expired entries', () => { + const cache = new Cache(); + cache.set('key', 'value', 10000); + + const pruned = cache.prune(); + + expect(pruned).toBe(0); + }); + }); +}); diff --git a/tests/unit/services/rate-limiter.test.ts b/tests/unit/services/rate-limiter.test.ts new file mode 100644 index 0000000..0348037 --- /dev/null +++ b/tests/unit/services/rate-limiter.test.ts @@ -0,0 +1,93 @@ +/** + * Rate Limiter Tests + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { RateLimiter } from '../../../src/services/rate-limiter.js'; + +describe('RateLimiter', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should initialize with full tokens', () => { + const limiter = new RateLimiter(100); + expect(limiter.getAvailableTokens()).toBe(100); + }); + + it('should use default of 180 tokens', () => { + const limiter = new RateLimiter(); + expect(limiter.getAvailableTokens()).toBe(180); + }); + + it('should allow requests within rate limit', async () => { + const limiter = new RateLimiter(10); + + // Should allow 10 requests + for (let i = 0; i < 10; i++) { + await limiter.acquire(); + } + + expect(limiter.getAvailableTokens()).toBe(0); + }); + + it('should decrement tokens on acquire', async () => { + const limiter = new RateLimiter(100); + await limiter.acquire(); + expect(limiter.getAvailableTokens()).toBe(99); + }); + + it('should report canAcquire correctly', async () => { + const limiter = new RateLimiter(2); + expect(limiter.canAcquire()).toBe(true); + + await limiter.acquire(); + expect(limiter.canAcquire()).toBe(true); + + await limiter.acquire(); + expect(limiter.canAcquire()).toBe(false); + }); + + it('should return zero wait time when tokens available', () => { + const limiter = new RateLimiter(100); + expect(limiter.getWaitTime()).toBe(0); + }); + + it('should calculate wait time when no tokens', async () => { + const limiter = new RateLimiter(2); + await limiter.acquire(); + await limiter.acquire(); + + // Should need to wait since no tokens left + expect(limiter.getWaitTime()).toBeGreaterThan(0); + }); + + it('should refill tokens over time', async () => { + const limiter = new RateLimiter(100); // 100 per hour + + // Use all tokens + for (let i = 0; i < 100; i++) { + await limiter.acquire(); + } + expect(limiter.getAvailableTokens()).toBe(0); + + // Advance time by 36 seconds (should get 1 token back at 100/hour rate) + vi.advanceTimersByTime(36 * 1000); + + expect(limiter.getAvailableTokens()).toBeGreaterThanOrEqual(1); + }); + + it('should not exceed max tokens on refill', async () => { + const limiter = new RateLimiter(100); + + // Advance time by 2 hours + vi.advanceTimersByTime(2 * 60 * 60 * 1000); + + // Should still be capped at 100 + expect(limiter.getAvailableTokens()).toBe(100); + }); +}); diff --git a/tests/unit/tools/analytics/budget-health.test.ts b/tests/unit/tools/analytics/budget-health.test.ts new file mode 100644 index 0000000..5aae5af --- /dev/null +++ b/tests/unit/tools/analytics/budget-health.test.ts @@ -0,0 +1,159 @@ +/** + * Budget Health Tool Tests + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { handleBudgetHealth } from '../../../../src/tools/analytics/budget-health.js'; +import { + createMockClient, + createMonthResponse, + createCategoriesResponse, + mockCategoryGroups, + mockMonthDetail, + mockOverspentMonth, +} from '../fixtures/index.js'; +import type { MockClient } from '../fixtures/index.js'; + +describe('handleBudgetHealth', () => { + let mockClient: MockClient; + + beforeEach(() => { + mockClient = createMockClient(); + }); + + it('returns health assessment for healthy budget', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.health_score).toBeGreaterThanOrEqual(0); + expect(parsed.health_score).toBeLessThanOrEqual(100); + expect(parsed.health_status).toMatch(/excellent|good|fair|poor/); + expect(parsed.key_metrics).toBeDefined(); + expect(parsed.key_metrics.to_be_budgeted).toBeDefined(); + expect(parsed.month_progress).toBeDefined(); + expect(parsed.category_health).toBeInstanceOf(Array); + expect(parsed.recommendations).toBeInstanceOf(Array); + }); + + it('identifies overspent categories', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Dining Out is overspent by $75 in mock data + const overspentAlerts = parsed.alerts.filter( + (a: { type: string }) => a.type === 'overspent_category' + ); + expect(overspentAlerts.length).toBeGreaterThan(0); + + const diningAlert = overspentAlerts.find( + (a: { category: string }) => a.category === 'Dining Out' + ); + expect(diningAlert).toBeDefined(); + }); + + it('identifies underfunded goals', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Vacation has goal_under_funded in mock data + const underfundedAlerts = parsed.alerts.filter( + (a: { type: string }) => a.type === 'underfunded_goal' + ); + expect(underfundedAlerts.length).toBeGreaterThan(0); + }); + + it('detects overbudgeted month', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockOverspentMonth)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Should have critical alert for overbudgeted + const overbudgetedAlert = parsed.alerts.find( + (a: { type: string }) => a.type === 'overbudgeted' + ); + expect(overbudgetedAlert).toBeDefined(); + expect(overbudgetedAlert.severity).toBe('critical'); + expect(parsed.health_score).toBeLessThan(80); // Score should be reduced + }); + + it('reports unbudgeted funds', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Mock month has $500 to_be_budgeted + const unbudgetedAlert = parsed.alerts.find( + (a: { type: string }) => a.type === 'unbudgeted_funds' + ); + expect(unbudgetedAlert).toBeDefined(); + expect(unbudgetedAlert.severity).toBe('info'); + }); + + it('calculates month progress correctly', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.month_progress.days_remaining).toBeGreaterThanOrEqual(0); + expect(parsed.month_progress.percent_complete).toBeGreaterThanOrEqual(0); + expect(parsed.month_progress.percent_complete).toBeLessThanOrEqual(100); + expect(parsed.month_progress.daily_budget_remaining).toBeDefined(); + }); + + it('generates appropriate recommendations', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockOverspentMonth)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.recommendations.length).toBeGreaterThan(0); + // Should recommend addressing critical issues + const criticalRec = parsed.recommendations.find((r: string) => + r.toLowerCase().includes('critical') + ); + expect(criticalRec).toBeDefined(); + }); + + it('respects budget_id parameter', async () => { + const customBudgetId = 'custom-budget-id'; + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockMonthDetail)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + await handleBudgetHealth({ budget_id: customBudgetId }, mockClient as never); + + expect(mockClient.resolveBudgetId).toHaveBeenCalledWith(customBudgetId); + }); + + it('sorts alerts by severity', async () => { + mockClient.getBudgetMonth.mockResolvedValue(createMonthResponse(mockOverspentMonth)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleBudgetHealth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Critical should come before warning, warning before info + const severityOrder = { critical: 0, warning: 1, info: 2 }; + let lastSeverity = -1; + for (const alert of parsed.alerts) { + const currentSeverity = severityOrder[alert.severity as keyof typeof severityOrder]; + expect(currentSeverity).toBeGreaterThanOrEqual(lastSeverity); + lastSeverity = currentSeverity; + } + }); +}); diff --git a/tests/unit/tools/analytics/goal-progress.test.ts b/tests/unit/tools/analytics/goal-progress.test.ts new file mode 100644 index 0000000..a8ca403 --- /dev/null +++ b/tests/unit/tools/analytics/goal-progress.test.ts @@ -0,0 +1,340 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { handleGoalProgress } from '../../../../src/tools/analytics/goal-progress.js'; +import { createMockClient, type MockClient } from '../fixtures/mock-client.js'; + +describe('handleGoalProgress', () => { + let mockClient: MockClient; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-15T12:00:00Z')); + mockClient = createMockClient(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should return empty goals array when no goals exist', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals).toEqual([]); + expect(result.summary.total_goals).toBe(0); + }); + + it('should mark goals as complete when 100% funded', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Emergency Fund', + goal_type: 'TB', + goal_target: 1000000, + balance: 1000000, + budgeted: 100000, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Emergency Fund', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals[0].status).toBe('complete'); + expect(result.goals[0].progress).toBe('100%'); + }); + + it('should mark goals as underfunded when goal_under_funded > 0', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Vacation', + goal_type: 'TBD', + goal_target: 500000, + goal_target_month: '2026-06-01', + balance: 200000, + budgeted: 50000, + activity: 0, + goal_under_funded: 50000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Vacation', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals[0].status).toBe('underfunded'); + expect(result.goals[0].status_message).toContain('$50.00'); + }); + + it('should filter goals by status when filter is provided', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [ + { + id: 'cat-1', + name: 'Emergency Fund', + goal_type: 'TB', + goal_target: 1000000, + balance: 1000000, + budgeted: 0, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Vacation', + goal_type: 'TB', + goal_target: 500000, + balance: 200000, + budgeted: 0, + activity: 0, + goal_under_funded: 50000, + hidden: false, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [ + { id: 'cat-1', name: 'Emergency Fund', hidden: false, deleted: false }, + { id: 'cat-2', name: 'Vacation', hidden: false, deleted: false }, + ], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({ filter: 'underfunded' }, mockClient as any)); + + expect(result.goals.length).toBe(1); + expect(result.goals[0].category).toBe('Vacation'); + expect(result.filter_applied).toBe('underfunded'); + }); + + it('should skip hidden categories', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Hidden Goal', + goal_type: 'TB', + goal_target: 100000, + balance: 50000, + budgeted: 0, + activity: 0, + goal_under_funded: 0, + hidden: true, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Hidden Goal', hidden: true, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals.length).toBe(0); + }); + + it('should skip Internal Master Category', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Inflow: Ready to Assign', + goal_type: 'TB', + goal_target: 100000, + balance: 50000, + budgeted: 0, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'internal-group', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'internal-group', + name: 'Internal Master Category', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Inflow: Ready to Assign', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals.length).toBe(0); + }); + + it('should calculate correct progress percentage', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Car Fund', + goal_type: 'TB', + goal_target: 1000000, + balance: 250000, + budgeted: 50000, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Car Fund', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.goals[0].progress).toBe('25%'); + }); + + it('should provide overall status summary', async () => { + mockClient.getBudgetMonth.mockResolvedValue({ + data: { + month: { + month: '2026-01-01', + categories: [ + { + id: 'cat-1', + name: 'Emergency Fund', + goal_type: 'TB', + goal_target: 1000000, + balance: 1000000, + budgeted: 0, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Vacation', + goal_type: 'TB', + goal_target: 500000, + balance: 400000, + budgeted: 50000, + activity: 0, + goal_under_funded: 0, + hidden: false, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Savings', + hidden: false, + deleted: false, + categories: [ + { id: 'cat-1', name: 'Emergency Fund', hidden: false, deleted: false }, + { id: 'cat-2', name: 'Vacation', hidden: false, deleted: false }, + ], + }], + }, + }); + + const result = JSON.parse(await handleGoalProgress({}, mockClient as any)); + + expect(result.status).toBe('healthy'); + expect(result.message).toBe('All goals are on track or complete'); + expect(result.summary.total_goals).toBe(2); + expect(result.summary.complete).toBe(1); + expect(result.summary.on_track).toBe(1); + }); +}); diff --git a/tests/unit/tools/analytics/monthly-comparison.test.ts b/tests/unit/tools/analytics/monthly-comparison.test.ts new file mode 100644 index 0000000..b3dda39 --- /dev/null +++ b/tests/unit/tools/analytics/monthly-comparison.test.ts @@ -0,0 +1,545 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { handleMonthlyComparison } from '../../../../src/tools/analytics/monthly-comparison.js'; +import { createMockClient, type MockClient } from '../fixtures/mock-client.js'; + +describe('handleMonthlyComparison', () => { + let mockClient: MockClient; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-15T12:00:00Z')); + mockClient = createMockClient(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should handle zero spending in previous month', async () => { + // Current month with spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -25000, + balance: 25000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + // Previous month with no spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: 0, + balance: 50000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.message).toContain('from $0'); + expect(result.insights.new_categories).toBe(1); + }); + + it('should identify spending increase correctly', async () => { + // Current month - more spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -40000, + balance: 10000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + // Previous month - less spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -25000, + balance: 25000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.status).toBe('worse'); + expect(result.comparison.spending.direction).toBe('up'); + }); + + it('should identify spending decrease correctly', async () => { + // Current month - less spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -20000, + balance: 30000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + // Previous month - more spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -40000, + balance: 10000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.status).toBe('better'); + expect(result.comparison.spending.direction).toBe('down'); + }); + + it('should report similar spending when change is small', async () => { + // Current month + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -25000, + balance: 25000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + // Previous month - nearly same spending + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -26000, + balance: 24000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.status).toBe('similar'); + }); + + it('should skip hidden categories', async () => { + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -25000, + balance: 25000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Hidden Category', + budgeted: 100000, + activity: -50000, + balance: 50000, + hidden: true, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -20000, + balance: 30000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Hidden Category', + budgeted: 100000, + activity: -30000, + balance: 70000, + hidden: true, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [ + { id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }, + { id: 'cat-2', name: 'Hidden Category', hidden: true, deleted: false }, + ], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + // Only the visible category spending should be counted + expect(result.comparison.spending.this_month).toBe('$25.00'); + expect(result.comparison.spending.last_month).toBe('$20.00'); + }); + + it('should skip Internal Master Category', async () => { + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -25000, + balance: 25000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'internal-cat', + name: 'Inflow: Ready to Assign', + budgeted: 0, + activity: 100000, + balance: 100000, + hidden: false, + category_group_id: 'internal-group', + }, + ], + }, + }, + }); + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -20000, + balance: 30000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'internal-cat', + name: 'Inflow: Ready to Assign', + budgeted: 0, + activity: 80000, + balance: 80000, + hidden: false, + category_group_id: 'internal-group', + }, + ], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [ + { + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }, + { + id: 'internal-group', + name: 'Internal Master Category', + hidden: false, + deleted: false, + categories: [{ id: 'internal-cat', name: 'Inflow: Ready to Assign', hidden: false, deleted: false }], + }, + ], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + // Only the regular category spending should be counted + expect(result.comparison.spending.this_month).toBe('$25.00'); + }); + + it('should handle zero spending in both months', async () => { + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: 0, + balance: 50000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [{ + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: 0, + balance: 50000, + hidden: false, + category_group_id: 'group-1', + }], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [{ id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.status).toBe('similar'); + expect(result.message).toBe('No spending in either month'); + }); + + it('should track notable category changes', async () => { + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -80000, + balance: -30000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Entertainment', + budgeted: 20000, + activity: -5000, + balance: 15000, + hidden: false, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [ + { + id: 'cat-1', + name: 'Groceries', + budgeted: 50000, + activity: -40000, + balance: 10000, + hidden: false, + category_group_id: 'group-1', + }, + { + id: 'cat-2', + name: 'Entertainment', + budgeted: 20000, + activity: -30000, + balance: -10000, + hidden: false, + category_group_id: 'group-1', + }, + ], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [{ + id: 'group-1', + name: 'Bills', + hidden: false, + deleted: false, + categories: [ + { id: 'cat-1', name: 'Groceries', hidden: false, deleted: false }, + { id: 'cat-2', name: 'Entertainment', hidden: false, deleted: false }, + ], + }], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.notable_changes.biggest_increases.length).toBeGreaterThan(0); + expect(result.notable_changes.biggest_decreases.length).toBeGreaterThan(0); + expect(result.notable_changes.biggest_increases[0].category).toBe('Groceries'); + expect(result.notable_changes.biggest_decreases[0].category).toBe('Entertainment'); + }); + + it('should include month references in response', async () => { + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2026-01-01', + categories: [], + }, + }, + }); + mockClient.getBudgetMonth.mockResolvedValueOnce({ + data: { + month: { + month: '2025-12-01', + categories: [], + }, + }, + }); + mockClient.getCategories.mockResolvedValue({ + data: { + category_groups: [], + }, + }); + + const result = JSON.parse(await handleMonthlyComparison({}, mockClient as any)); + + expect(result.months.current).toBe('2026-01-01'); + expect(result.months.previous).toBe('2025-12-01'); + }); +}); diff --git a/tests/unit/tools/analytics/net-worth.test.ts b/tests/unit/tools/analytics/net-worth.test.ts new file mode 100644 index 0000000..6a738d3 --- /dev/null +++ b/tests/unit/tools/analytics/net-worth.test.ts @@ -0,0 +1,184 @@ +/** + * Net Worth Tool Tests + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { handleNetWorth } from '../../../../src/tools/analytics/net-worth.js'; +import { + createMockClient, + createAccountsResponse, + mockAllAccounts, + mockBudgetAccounts, + mockCheckingAccount, + mockSavingsAccount, + mockCreditCardAccount, + mockCreditCardWithOverpayment, + mockMortgageAccount, + mockInvestmentAccount, + mockClosedAccount, +} from '../fixtures/index.js'; +import type { MockClient } from '../fixtures/index.js'; + +describe('handleNetWorth', () => { + let mockClient: MockClient; + + beforeEach(() => { + mockClient = createMockClient(); + }); + + it('calculates net worth from all accounts', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.net_worth).toBeDefined(); + expect(parsed.summary).toBeDefined(); + expect(parsed.summary.total_assets).toBeDefined(); + expect(parsed.summary.total_liabilities).toBeDefined(); + expect(parsed.by_account_type).toBeInstanceOf(Array); + }); + + it('correctly separates assets and liabilities', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Assets should include checking, savings, investments + // Liabilities should include credit cards, mortgage, auto loan + expect(parsed.summary.total_assets).toBeDefined(); + expect(parsed.summary.total_liabilities).toBeDefined(); + + // Verify net worth = assets - liabilities + const assets = parseFloat(parsed.summary.total_assets.replace(/[^0-9.-]/g, '')); + const liabilities = parseFloat(parsed.summary.total_liabilities.replace(/[^0-9.-]/g, '')); + const netWorth = parseFloat(parsed.summary.net_worth.replace(/[^0-9.-]/g, '')); + + // Due to the complexity of the calculation, just verify the values are reasonable + expect(assets).toBeGreaterThan(0); + expect(liabilities).toBeGreaterThan(0); + }); + + it('groups accounts by type', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + const checkingGroup = parsed.by_account_type.find( + (g: { type: string }) => g.type === 'checking' + ); + const savingsGroup = parsed.by_account_type.find( + (g: { type: string }) => g.type === 'savings' + ); + const creditCardGroup = parsed.by_account_type.find( + (g: { type: string }) => g.type === 'creditCard' + ); + + expect(checkingGroup).toBeDefined(); + expect(savingsGroup).toBeDefined(); + expect(creditCardGroup).toBeDefined(); + }); + + it('excludes closed accounts by default', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Count should not include closed account + expect(parsed.account_count.closed_excluded).toBeGreaterThan(0); + + // Verify closed account is not in the list + const allAccountNames = parsed.by_account_type.flatMap( + (g: { accounts: { name: string }[] }) => g.accounts.map((a) => a.name) + ); + expect(allAccountNames).not.toContain('Old Savings'); + }); + + it('includes closed accounts when requested', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({ include_closed: true }, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.account_count.closed_excluded).toBe(0); + }); + + it('separates budget and tracking accounts', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockAllAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.breakdown.budget_accounts).toBeDefined(); + expect(parsed.breakdown.tracking_accounts).toBeDefined(); + expect(parsed.breakdown.budget_accounts.count).toBeGreaterThan(0); + expect(parsed.breakdown.tracking_accounts.count).toBeGreaterThan(0); + }); + + it('determines correct status for positive net worth', async () => { + // Create accounts with positive net worth + const positiveNetWorthAccounts = [ + mockCheckingAccount, + mockSavingsAccount, + mockInvestmentAccount, + ]; + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(positiveNetWorthAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.status).toBe('positive'); + expect(parsed.message).toContain('positive'); + }); + + it('determines correct status for negative net worth', async () => { + // Create accounts with negative net worth (more debt than assets) + const negativeNetWorthAccounts = [ + { ...mockCheckingAccount, balance: 100000 }, // $100 + mockMortgageAccount, // -$250,000 + ]; + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(negativeNetWorthAccounts)); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.status).toBe('negative'); + expect(parsed.message).toContain('negative'); + }); + + it('handles credit card overpayment correctly', async () => { + // Credit card with positive balance (overpayment) should be an asset + mockClient.getAccounts.mockResolvedValue( + createAccountsResponse([mockCreditCardWithOverpayment]) + ); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + // Overpayment should contribute positively to net worth + const netWorth = parseFloat(parsed.net_worth.replace(/[^0-9.-]/g, '')); + expect(netWorth).toBeGreaterThan(0); + }); + + it('respects budget_id parameter', async () => { + const customBudgetId = 'custom-budget-id'; + mockClient.getAccounts.mockResolvedValue(createAccountsResponse(mockBudgetAccounts)); + + await handleNetWorth({ budget_id: customBudgetId }, mockClient as never); + + expect(mockClient.resolveBudgetId).toHaveBeenCalledWith(customBudgetId); + }); + + it('handles empty accounts list', async () => { + mockClient.getAccounts.mockResolvedValue(createAccountsResponse([])); + + const result = await handleNetWorth({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.status).toBe('zero'); + expect(parsed.account_count.total).toBe(0); + }); +}); diff --git a/tests/unit/tools/analytics/spending-analysis.test.ts b/tests/unit/tools/analytics/spending-analysis.test.ts new file mode 100644 index 0000000..0c75245 --- /dev/null +++ b/tests/unit/tools/analytics/spending-analysis.test.ts @@ -0,0 +1,192 @@ +/** + * Spending Analysis Tool Tests + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { handleSpendingAnalysis } from '../../../../src/tools/analytics/spending-analysis.js'; +import { + createMockClient, + createTransactionsResponse, + createCategoriesResponse, + mockAllTransactions, + mockCategoryGroups, +} from '../fixtures/index.js'; +import type { MockClient } from '../fixtures/index.js'; + +describe('handleSpendingAnalysis', () => { + let mockClient: MockClient; + + beforeEach(() => { + mockClient = createMockClient(); + }); + + it('analyzes spending by category', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.spending_by_category).toBeInstanceOf(Array); + expect(parsed.spending_by_category.length).toBeGreaterThan(0); + + // Each category should have expected fields + const firstCategory = parsed.spending_by_category[0]; + expect(firstCategory.category_name).toBeDefined(); + expect(firstCategory.total_spent).toBeDefined(); + expect(firstCategory.transaction_count).toBeGreaterThan(0); + expect(firstCategory.percent_of_total).toBeDefined(); + expect(firstCategory.trend).toMatch(/increasing|decreasing|stable/); + }); + + it('calculates spending summary', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.summary).toBeDefined(); + expect(parsed.summary.total_spent).toBeDefined(); + expect(parsed.summary.monthly_average).toBeDefined(); + expect(parsed.summary.daily_average).toBeDefined(); + expect(parsed.summary.transaction_count).toBeGreaterThan(0); + expect(parsed.summary.category_count).toBeGreaterThan(0); + }); + + it('provides monthly spending breakdown', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.monthly_spending).toBeInstanceOf(Array); + if (parsed.monthly_spending.length > 0) { + const firstMonth = parsed.monthly_spending[0]; + expect(firstMonth.month).toMatch(/^\d{4}-\d{2}$/); + expect(firstMonth.total_spent).toBeDefined(); + expect(firstMonth.category_breakdown).toBeInstanceOf(Array); + } + }); + + it('identifies top spending categories', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.insights.top_5_categories).toBeInstanceOf(Array); + expect(parsed.insights.top_5_categories.length).toBeLessThanOrEqual(5); + + // Top categories should be sorted by amount (descending) + const amounts = parsed.insights.top_5_categories.map((c: { amount: string }) => + parseFloat(c.amount.replace(/[^0-9.-]/g, '')) + ); + for (let i = 1; i < amounts.length; i++) { + expect(amounts[i]).toBeLessThanOrEqual(amounts[i - 1]); + } + }); + + it('respects months parameter', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({ months: 6 }, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.summary.analysis_period).toBe('6 months'); + }); + + it('filters by category_id when provided', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis( + { category_id: 'cat-groceries-555' }, + mockClient as never + ); + const parsed = JSON.parse(result); + + // Should only have one category in results (category_id is not exposed in output) + expect(parsed.spending_by_category.length).toBe(1); + expect(parsed.spending_by_category[0].category_name).toBe('Groceries'); + }); + + it('excludes transfer transactions', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + // Transfers should not appear as spending categories + const transferCategory = parsed.spending_by_category.find( + (c: { category_name: string }) => c.category_name?.includes('Transfer') + ); + expect(transferCategory).toBeUndefined(); + }); + + it('excludes income transactions', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + // Income should not appear in spending analysis + const incomeCategory = parsed.spending_by_category.find( + (c: { category_name: string }) => c.category_name === 'Inflow: Ready to Assign' + ); + expect(incomeCategory).toBeUndefined(); + }); + + it('identifies increasing spending trends', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.insights.increasing_spending).toBeInstanceOf(Array); + expect(parsed.insights.decreasing_spending).toBeInstanceOf(Array); + }); + + it('handles empty transaction list', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse([])); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + expect(parsed.spending_by_category).toEqual([]); + expect(parsed.summary.total_spent).toBe('$0.00'); + expect(parsed.summary.transaction_count).toBe(0); + }); + + it('calculates correct percent of total', async () => { + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + const result = await handleSpendingAnalysis({}, mockClient as never); + const parsed = JSON.parse(result); + + // Sum of all percentages should be approximately 100 + const totalPercent = parsed.spending_by_category.reduce( + (sum: number, c: { percent_of_total: number }) => sum + c.percent_of_total, + 0 + ); + expect(totalPercent).toBeCloseTo(100, 0); + }); + + it('respects budget_id parameter', async () => { + const customBudgetId = 'custom-budget-id'; + mockClient.getTransactions.mockResolvedValue(createTransactionsResponse(mockAllTransactions)); + mockClient.getCategories.mockResolvedValue(createCategoriesResponse(mockCategoryGroups)); + + await handleSpendingAnalysis({ budget_id: customBudgetId }, mockClient as never); + + expect(mockClient.resolveBudgetId).toHaveBeenCalledWith(customBudgetId); + }); +}); diff --git a/tests/unit/tools/fixtures/index.ts b/tests/unit/tools/fixtures/index.ts new file mode 100644 index 0000000..2a5bf29 --- /dev/null +++ b/tests/unit/tools/fixtures/index.ts @@ -0,0 +1,104 @@ +/** + * Test Fixtures Index + * + * Central export for all mock data fixtures. + */ + +// Mock client factory +export { createMockClient, type MockClient } from './mock-client.js'; + +// Account fixtures +export { + mockCheckingAccount, + mockSavingsAccount, + mockCreditCardAccount, + mockCreditCardWithOverpayment, + mockMortgageAccount, + mockInvestmentAccount, + mockClosedAccount, + mockAutoLoanAccount, + mockBudgetAccounts, + mockTrackingAccounts, + mockAllAccounts, + createAccountsResponse, + createAccountResponse, +} from './mock-accounts.js'; + +// Category fixtures +export { + mockBillsCategories, + mockEverydayCategories, + mockSavingsCategories, + mockDiscretionaryCategories, + mockHiddenCategory, + mockCreditCardPaymentCategory, + mockReadyToAssignCategory, + mockCategoryGroups, + mockAllCategories, + createCategoriesResponse, + createCategoryResponse, + healthyBudgetCategories, + overspentBudgetCategories, +} from './mock-categories.js'; + +// Transaction fixtures +export { + mockGroceryTransactions, + mockDiningTransactions, + mockSubscriptionTransactions, + mockBillTransactions, + mockIncomeTransactions, + mockTransferTransaction, + mockCreditCardPaymentTransaction, + mockSplitTransaction, + mockUnclearedTransaction, + mockFlaggedTransaction, + mockAllTransactions, + mockScheduledTransactions, + createTransactionsResponse, + createTransactionResponse, + createScheduledTransactionsResponse, + createScheduledTransactionResponse, + createMonthTransactions, +} from './mock-transactions.js'; + +// Budget fixtures +export { + mockUsdCurrencyFormat, + mockEurCurrencyFormat, + mockGbpCurrencyFormat, + mockJpyCurrencyFormat, + mockBudgetSummary, + mockEurBudgetSummary, + mockBudgetDetail, + mockMonthSummaries, + mockMonthDetail, + mockOverspentMonth, + mockBudgetSettings, + mockEurBudgetSettings, + createBudgetsResponse, + createBudgetResponse, + createBudgetSettingsResponse, + createMonthsResponse, + createMonthResponse, + createHealthyBudgetMonth, + createUnderBudgetedMonth, +} from './mock-budgets.js'; + +// Payee fixtures +export { + mockPayees, + mockTransferPayees, + mockDeletedPayee, + mockAllPayees, + mockPayeeLocations, + createPayeesResponse, + createPayeeResponse, + createPayeeLocationsResponse, + createPayeeLocationResponse, + getPayeeById, + getLocationsForPayee, + mockSubscriptionPayees, + mockDiningPayees, + mockGroceryPayees, +} from './mock-payees.js'; diff --git a/tests/unit/tools/fixtures/mock-accounts.ts b/tests/unit/tools/fixtures/mock-accounts.ts new file mode 100644 index 0000000..907d2b9 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-accounts.ts @@ -0,0 +1,216 @@ +/** + * Mock Account Fixtures + * + * Realistic YNAB account data for testing. + */ + +import type { Account } from 'ynab'; + +// Use type assertion to allow string literal types +type MockAccount = Omit & { type: string }; + +export const mockCheckingAccount: MockAccount = { + id: '11111111-1111-1111-1111-111111111111', + name: 'Primary Checking', + type: 'checking', + on_budget: true, + closed: false, + note: 'Main checking account', + balance: 2500000, // $2,500.00 + cleared_balance: 2400000, // $2,400.00 + uncleared_balance: 100000, // $100.00 + transfer_payee_id: 'tp-checking-111', + direct_import_linked: true, + direct_import_in_error: false, + last_reconciled_at: '2024-01-15T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockSavingsAccount: MockAccount = { + id: '22222222-2222-2222-2222-222222222222', + name: 'Emergency Fund', + type: 'savings', + on_budget: true, + closed: false, + note: 'Emergency savings', + balance: 10000000, // $10,000.00 + cleared_balance: 10000000, + uncleared_balance: 0, + transfer_payee_id: 'tp-savings-222', + direct_import_linked: true, + direct_import_in_error: false, + last_reconciled_at: '2024-01-10T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockCreditCardAccount: MockAccount = { + id: '33333333-3333-3333-3333-333333333333', + name: 'Chase Visa', + type: 'creditCard', + on_budget: true, + closed: false, + note: 'Primary credit card', + balance: -1500000, // -$1,500.00 (owed) + cleared_balance: -1450000, + uncleared_balance: -50000, + transfer_payee_id: 'tp-cc-333', + direct_import_linked: true, + direct_import_in_error: false, + last_reconciled_at: '2024-01-14T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockCreditCardWithOverpayment: MockAccount = { + id: '33333333-3333-3333-3333-333333333334', + name: 'Amex Gold', + type: 'creditCard', + on_budget: true, + closed: false, + note: 'Has credit balance from overpayment', + balance: 50000, // $50.00 credit (overpaid) + cleared_balance: 50000, + uncleared_balance: 0, + transfer_payee_id: 'tp-cc-amex', + direct_import_linked: true, + direct_import_in_error: false, + last_reconciled_at: '2024-01-12T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockMortgageAccount: MockAccount = { + id: '44444444-4444-4444-4444-444444444444', + name: 'Home Mortgage', + type: 'mortgage', + on_budget: false, + closed: false, + note: '30-year fixed', + balance: -250000000, // -$250,000.00 + cleared_balance: -250000000, + uncleared_balance: 0, + transfer_payee_id: 'tp-mortgage-444', + direct_import_linked: false, + direct_import_in_error: false, + last_reconciled_at: '2024-01-01T12:00:00Z', + debt_original_balance: -300000000, // -$300,000.00 original + debt_interest_rates: { '44444444-4444-4444-4444-444444444444': 4500 }, // 4.5% + debt_minimum_payments: { '44444444-4444-4444-4444-444444444444': 1500000 }, // $1,500/month + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockInvestmentAccount: MockAccount = { + id: '55555555-5555-5555-5555-555555555555', + name: '401k', + type: 'otherAsset', + on_budget: false, + closed: false, + note: 'Retirement account', + balance: 75000000, // $75,000.00 + cleared_balance: 75000000, + uncleared_balance: 0, + transfer_payee_id: 'tp-401k-555', + direct_import_linked: false, + direct_import_in_error: false, + last_reconciled_at: '2024-01-01T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockClosedAccount: MockAccount = { + id: '66666666-6666-6666-6666-666666666666', + name: 'Old Savings', + type: 'savings', + on_budget: true, + closed: true, + note: 'Closed account', + balance: 0, + cleared_balance: 0, + uncleared_balance: 0, + transfer_payee_id: 'tp-old-666', + direct_import_linked: false, + direct_import_in_error: false, + last_reconciled_at: '2023-06-01T12:00:00Z', + debt_original_balance: null, + debt_interest_rates: {}, + debt_minimum_payments: {}, + debt_escrow_amounts: {}, + deleted: false, +}; + +export const mockAutoLoanAccount: MockAccount = { + id: '77777777-7777-7777-7777-777777777777', + name: 'Car Loan', + type: 'autoLoan', + on_budget: false, + closed: false, + note: 'Auto loan', + balance: -15000000, // -$15,000.00 + cleared_balance: -15000000, + uncleared_balance: 0, + transfer_payee_id: 'tp-auto-777', + direct_import_linked: false, + direct_import_in_error: false, + last_reconciled_at: '2024-01-01T12:00:00Z', + debt_original_balance: -25000000, // -$25,000.00 original + debt_interest_rates: { '77777777-7777-7777-7777-777777777777': 5900 }, // 5.9% + debt_minimum_payments: { '77777777-7777-7777-7777-777777777777': 450000 }, // $450/month + debt_escrow_amounts: {}, + deleted: false, +}; + +// Preset collections for different test scenarios +export const mockBudgetAccounts: MockAccount[] = [ + mockCheckingAccount, + mockSavingsAccount, + mockCreditCardAccount, + mockCreditCardWithOverpayment, +]; + +export const mockTrackingAccounts: MockAccount[] = [ + mockMortgageAccount, + mockInvestmentAccount, + mockAutoLoanAccount, +]; + +export const mockAllAccounts: MockAccount[] = [ + ...mockBudgetAccounts, + ...mockTrackingAccounts, + mockClosedAccount, +]; + +// Account response factory +export function createAccountsResponse(accounts: MockAccount[] = mockAllAccounts) { + return { + data: { + accounts: accounts as unknown as Account[], + server_knowledge: 12345, + }, + }; +} + +export function createAccountResponse(account: MockAccount = mockCheckingAccount) { + return { + data: { + account: account as unknown as Account, + }, + }; +} diff --git a/tests/unit/tools/fixtures/mock-budgets.ts b/tests/unit/tools/fixtures/mock-budgets.ts new file mode 100644 index 0000000..4305353 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-budgets.ts @@ -0,0 +1,262 @@ +/** + * Mock Budget Fixtures + * + * Realistic YNAB budget and month data for testing. + */ + +import type { BudgetSummary, BudgetDetail, MonthSummary, MonthDetail, CurrencyFormat } from 'ynab'; +import { mockCategoryGroups } from './mock-categories.js'; +import { mockAllAccounts } from './mock-accounts.js'; + +// USD currency format (default) +export const mockUsdCurrencyFormat: CurrencyFormat = { + iso_code: 'USD', + example_format: '$1,234.56', + decimal_digits: 2, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '$', + display_symbol: true, +}; + +// EUR currency format +export const mockEurCurrencyFormat: CurrencyFormat = { + iso_code: 'EUR', + example_format: '1.234,56 €', + decimal_digits: 2, + decimal_separator: ',', + symbol_first: false, + group_separator: '.', + currency_symbol: '€', + display_symbol: true, +}; + +// GBP currency format +export const mockGbpCurrencyFormat: CurrencyFormat = { + iso_code: 'GBP', + example_format: '£1,234.56', + decimal_digits: 2, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '£', + display_symbol: true, +}; + +// JPY currency format (no decimals) +export const mockJpyCurrencyFormat: CurrencyFormat = { + iso_code: 'JPY', + example_format: '¥1,234', + decimal_digits: 0, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '¥', + display_symbol: true, +}; + +// Budget summary +export const mockBudgetSummary: BudgetSummary = { + id: 'budget-11111111-1111-1111-1111-111111111111', + name: 'My Budget', + last_modified_on: '2024-01-30T12:00:00Z', + first_month: '2023-01-01', + last_month: '2024-12-01', + date_format: { + format: 'MM/DD/YYYY', + }, + currency_format: mockUsdCurrencyFormat, + accounts: mockAllAccounts as unknown as BudgetSummary['accounts'], +}; + +// Secondary budget (EUR) +export const mockEurBudgetSummary: BudgetSummary = { + id: 'budget-22222222-2222-2222-2222-222222222222', + name: 'European Budget', + last_modified_on: '2024-01-28T12:00:00Z', + first_month: '2023-06-01', + last_month: '2024-12-01', + date_format: { + format: 'DD/MM/YYYY', + }, + currency_format: mockEurCurrencyFormat, + accounts: [], +}; + +// Budget detail +export const mockBudgetDetail: BudgetDetail = { + id: 'budget-11111111-1111-1111-1111-111111111111', + name: 'My Budget', + last_modified_on: '2024-01-30T12:00:00Z', + first_month: '2023-01-01', + last_month: '2024-12-01', + date_format: { + format: 'MM/DD/YYYY', + }, + currency_format: mockUsdCurrencyFormat, + accounts: mockAllAccounts as unknown as BudgetDetail['accounts'], + payees: [], + payee_locations: [], + category_groups: mockCategoryGroups, + categories: [], + months: [], + transactions: [], + subtransactions: [], + scheduled_transactions: [], + scheduled_subtransactions: [], +}; + +// Month summary (for list months) +export const mockMonthSummaries: MonthSummary[] = [ + { + month: '2024-01-01', + note: 'January budget', + income: 5000000, // $5,000 + budgeted: 4500000, // $4,500 + activity: -3200000, // -$3,200 + to_be_budgeted: 500000, // $500 + age_of_money: 45, + deleted: false, + }, + { + month: '2023-12-01', + note: 'December budget', + income: 5000000, + budgeted: 4800000, + activity: -4500000, + to_be_budgeted: 0, + age_of_money: 42, + deleted: false, + }, + { + month: '2023-11-01', + note: 'November budget', + income: 5000000, + budgeted: 4600000, + activity: -4200000, + to_be_budgeted: 0, + age_of_money: 40, + deleted: false, + }, + { + month: '2023-10-01', + note: null, + income: 5000000, + budgeted: 4700000, + activity: -4100000, + to_be_budgeted: 0, + age_of_money: 38, + deleted: false, + }, +]; + +// Month detail (for get month) +export const mockMonthDetail: MonthDetail = { + month: '2024-01-01', + note: 'January budget', + income: 5000000, + budgeted: 4500000, + activity: -3200000, + to_be_budgeted: 500000, + age_of_money: 45, + deleted: false, + categories: mockCategoryGroups.flatMap((g) => g.categories), +}; + +// Overspent month +export const mockOverspentMonth: MonthDetail = { + month: '2024-01-01', + note: 'Overspent month', + income: 5000000, + budgeted: 5500000, // Budgeted more than income + activity: -4800000, + to_be_budgeted: -500000, // Negative to_be_budgeted + age_of_money: 30, + deleted: false, + categories: mockCategoryGroups.flatMap((g) => g.categories), +}; + +// Budget settings +export const mockBudgetSettings = { + settings: { + date_format: { + format: 'MM/DD/YYYY', + }, + currency_format: mockUsdCurrencyFormat, + }, +}; + +export const mockEurBudgetSettings = { + settings: { + date_format: { + format: 'DD/MM/YYYY', + }, + currency_format: mockEurCurrencyFormat, + }, +}; + +// Response factories +export function createBudgetsResponse(budgets: BudgetSummary[] = [mockBudgetSummary, mockEurBudgetSummary]) { + return { + data: { + budgets, + default_budget: budgets[0] ?? null, + }, + }; +} + +export function createBudgetResponse(budget: BudgetDetail = mockBudgetDetail) { + return { + data: { + budget, + server_knowledge: 12345, + }, + }; +} + +export function createBudgetSettingsResponse(currencyFormat: CurrencyFormat = mockUsdCurrencyFormat) { + return { + data: { + settings: { + date_format: { + format: currencyFormat.iso_code === 'USD' ? 'MM/DD/YYYY' : 'DD/MM/YYYY', + }, + currency_format: currencyFormat, + }, + }, + }; +} + +export function createMonthsResponse(months: MonthSummary[] = mockMonthSummaries) { + return { + data: { + months, + server_knowledge: 12345, + }, + }; +} + +export function createMonthResponse(month: MonthDetail = mockMonthDetail) { + return { + data: { + month, + }, + }; +} + +// Preset scenarios +export function createHealthyBudgetMonth(): MonthDetail { + return { + ...mockMonthDetail, + to_be_budgeted: 0, // Fully allocated + activity: -4000000, // Spent less than budgeted + }; +} + +export function createUnderBudgetedMonth(): MonthDetail { + return { + ...mockMonthDetail, + to_be_budgeted: 1000000, // $1,000 unallocated + }; +} diff --git a/tests/unit/tools/fixtures/mock-categories.ts b/tests/unit/tools/fixtures/mock-categories.ts new file mode 100644 index 0000000..b2d5883 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-categories.ts @@ -0,0 +1,353 @@ +/** + * Mock Category Fixtures + * + * Realistic YNAB category data for testing. + */ + +import type { Category, CategoryGroupWithCategories } from 'ynab'; + +// Type for mock categories with flexible goal_type +type MockCategory = Omit & { goal_type: string | null }; + +// Helper to create a category +function createCategory(overrides: Partial & { id: string; name: string }): MockCategory { + return { + category_group_id: 'group-1', + budgeted: 0, + activity: 0, + balance: 0, + goal_type: null, + goal_day: null, + goal_cadence: null, + goal_cadence_frequency: null, + goal_creation_month: null, + goal_target: null, + goal_target_month: null, + goal_percentage_complete: null, + goal_months_to_budget: null, + goal_under_funded: null, + goal_overall_funded: null, + goal_overall_left: null, + note: null, + original_category_group_id: null, + hidden: false, + deleted: false, + ...overrides, + }; +} + +// Bills category group +export const mockBillsCategories: MockCategory[] = [ + createCategory({ + id: 'cat-rent-111', + name: 'Rent/Mortgage', + category_group_id: 'group-bills', + budgeted: 1500000, // $1,500 + activity: -1500000, + balance: 0, + goal_type: 'MF', + goal_target: 1500000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-utilities-222', + name: 'Utilities', + category_group_id: 'group-bills', + budgeted: 200000, // $200 + activity: -175000, // $175 spent + balance: 25000, // $25 remaining + goal_type: 'NEED', + goal_target: 200000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-internet-333', + name: 'Internet', + category_group_id: 'group-bills', + budgeted: 80000, // $80 + activity: -80000, + balance: 0, + goal_type: 'MF', + goal_target: 80000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-phone-444', + name: 'Phone', + category_group_id: 'group-bills', + budgeted: 75000, // $75 + activity: -75000, + balance: 0, + goal_type: 'MF', + goal_target: 75000, + goal_percentage_complete: 100, + }), +]; + +// Everyday expenses category group +export const mockEverydayCategories: MockCategory[] = [ + createCategory({ + id: 'cat-groceries-555', + name: 'Groceries', + category_group_id: 'group-everyday', + budgeted: 600000, // $600 + activity: -450000, // $450 spent + balance: 150000, // $150 remaining + goal_type: 'NEED', + goal_target: 600000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-dining-666', + name: 'Dining Out', + category_group_id: 'group-everyday', + budgeted: 200000, // $200 + activity: -275000, // $275 spent - OVERSPENT + balance: -75000, // -$75 overspent + goal_type: 'NEED', + goal_target: 200000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-transport-777', + name: 'Transportation', + category_group_id: 'group-everyday', + budgeted: 300000, // $300 + activity: -180000, // $180 spent + balance: 120000, // $120 remaining + goal_type: 'NEED', + goal_target: 300000, + goal_percentage_complete: 100, + }), + createCategory({ + id: 'cat-gas-888', + name: 'Gas', + category_group_id: 'group-everyday', + budgeted: 150000, // $150 + activity: -125000, // $125 spent + balance: 25000, // $25 remaining + goal_type: 'NEED', + goal_target: 150000, + goal_percentage_complete: 100, + }), +]; + +// Savings goals category group +export const mockSavingsCategories: MockCategory[] = [ + createCategory({ + id: 'cat-emergency-999', + name: 'Emergency Fund', + category_group_id: 'group-savings', + budgeted: 500000, // $500 + activity: 0, + balance: 10000000, // $10,000 saved + goal_type: 'TB', + goal_target: 15000000, // $15,000 target + goal_percentage_complete: 67, + goal_overall_funded: 10000000, + goal_overall_left: 5000000, + }), + createCategory({ + id: 'cat-vacation-aaa', + name: 'Vacation', + category_group_id: 'group-savings', + budgeted: 200000, // $200 + activity: 0, + balance: 1200000, // $1,200 saved + goal_type: 'TBD', + goal_target: 3000000, // $3,000 target + goal_target_month: '2024-06-01', + goal_percentage_complete: 40, + goal_under_funded: 300000, // $300 underfunded + goal_overall_funded: 1200000, + goal_overall_left: 1800000, + goal_months_to_budget: 4, + }), + createCategory({ + id: 'cat-car-bbb', + name: 'New Car Fund', + category_group_id: 'group-savings', + budgeted: 300000, // $300 + activity: 0, + balance: 5000000, // $5,000 saved + goal_type: 'TBD', + goal_target: 20000000, // $20,000 target + goal_target_month: '2025-12-01', + goal_percentage_complete: 25, + goal_under_funded: 0, + goal_overall_funded: 5000000, + goal_overall_left: 15000000, + goal_months_to_budget: 20, + }), +]; + +// Discretionary spending category group +export const mockDiscretionaryCategories: MockCategory[] = [ + createCategory({ + id: 'cat-entertainment-ccc', + name: 'Entertainment', + category_group_id: 'group-discretionary', + budgeted: 100000, // $100 + activity: -85000, // $85 spent + balance: 15000, // $15 remaining + }), + createCategory({ + id: 'cat-subscriptions-ddd', + name: 'Subscriptions', + category_group_id: 'group-discretionary', + budgeted: 50000, // $50 + activity: -65000, // $65 spent - OVERSPENT + balance: -15000, // -$15 overspent + }), + createCategory({ + id: 'cat-shopping-eee', + name: 'Shopping', + category_group_id: 'group-discretionary', + budgeted: 150000, // $150 + activity: -100000, // $100 spent + balance: 50000, // $50 remaining + }), + createCategory({ + id: 'cat-hobbies-fff', + name: 'Hobbies', + category_group_id: 'group-discretionary', + budgeted: 75000, // $75 + activity: 0, // Nothing spent + balance: 75000, // Full amount remaining + }), +]; + +// Hidden/unused category +export const mockHiddenCategory: MockCategory = createCategory({ + id: 'cat-hidden-ggg', + name: 'Old Category', + category_group_id: 'group-hidden', + budgeted: 0, + activity: 0, + balance: 0, + hidden: true, +}); + +// Credit card payment category +export const mockCreditCardPaymentCategory: MockCategory = createCategory({ + id: 'cat-cc-payment-hhh', + name: 'Chase Visa', + category_group_id: 'group-credit-cards', + budgeted: 1500000, // $1,500 + activity: -1500000, + balance: 0, + note: 'Credit card payment category', +}); + +// Internal category (Ready to Assign) +export const mockReadyToAssignCategory: MockCategory = createCategory({ + id: 'cat-rta-iii', + name: 'Inflow: Ready to Assign', + category_group_id: 'group-internal', + budgeted: 0, + activity: 5000000, // $5,000 income + balance: 500000, // $500 to be budgeted +}); + +// Category groups +export const mockCategoryGroups: CategoryGroupWithCategories[] = [ + { + id: 'group-internal', + name: 'Internal Master Category', + hidden: true, + deleted: false, + categories: [mockReadyToAssignCategory as unknown as Category], + }, + { + id: 'group-credit-cards', + name: 'Credit Card Payments', + hidden: false, + deleted: false, + categories: [mockCreditCardPaymentCategory as unknown as Category], + }, + { + id: 'group-bills', + name: 'Bills', + hidden: false, + deleted: false, + categories: mockBillsCategories as unknown as Category[], + }, + { + id: 'group-everyday', + name: 'Everyday Expenses', + hidden: false, + deleted: false, + categories: mockEverydayCategories as unknown as Category[], + }, + { + id: 'group-savings', + name: 'Savings Goals', + hidden: false, + deleted: false, + categories: mockSavingsCategories as unknown as Category[], + }, + { + id: 'group-discretionary', + name: 'Discretionary', + hidden: false, + deleted: false, + categories: mockDiscretionaryCategories as unknown as Category[], + }, + { + id: 'group-hidden', + name: 'Hidden', + hidden: true, + deleted: false, + categories: [mockHiddenCategory as unknown as Category], + }, +]; + +// All categories flat list +export const mockAllCategories: MockCategory[] = [ + mockReadyToAssignCategory, + mockCreditCardPaymentCategory, + ...mockBillsCategories, + ...mockEverydayCategories, + ...mockSavingsCategories, + ...mockDiscretionaryCategories, + mockHiddenCategory, +]; + +// Response factories +export function createCategoriesResponse(groups = mockCategoryGroups) { + return { + data: { + category_groups: groups, + server_knowledge: 12345, + }, + }; +} + +export function createCategoryResponse(category: MockCategory = mockBillsCategories[0]!) { + return { + data: { + category: category as unknown as Category, + }, + }; +} + +// Preset scenarios +export const healthyBudgetCategories = mockCategoryGroups; + +// Creates a budget with overspent everyday expenses categories +// Note: slice(0, 3) gets indices 0-2, slice(4) gets indices 4-6 +// This intentionally excludes index 3 (group-everyday) since we're replacing it +export const overspentBudgetCategories: CategoryGroupWithCategories[] = [ + ...mockCategoryGroups.slice(0, 3), // indices 0-2: internal, credit-cards, bills + { + id: 'group-everyday', + name: 'Everyday Expenses', + hidden: false, + deleted: false, + categories: mockEverydayCategories.map((c) => ({ + ...c, + balance: c.balance - 200000, // Make all overspent + })) as unknown as Category[], + }, + ...mockCategoryGroups.slice(4), // indices 4-6: savings, discretionary, hidden +]; diff --git a/tests/unit/tools/fixtures/mock-client.ts b/tests/unit/tools/fixtures/mock-client.ts new file mode 100644 index 0000000..6704fd8 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-client.ts @@ -0,0 +1,54 @@ +import { vi } from 'vitest'; + +export function createMockClient() { + return { + resolveBudgetId: vi.fn((id?: string) => id ?? 'test-budget-id'), + getDefaultBudgetId: vi.fn(() => 'test-budget-id'), + isReadOnly: vi.fn(() => true), + + // Budget endpoints + getBudgets: vi.fn(), + getBudgetById: vi.fn(), + getBudgetSettingsById: vi.fn(), + + // Account endpoints + getAccounts: vi.fn(), + getAccountById: vi.fn(), + createAccount: vi.fn(), + + // Category endpoints + getCategories: vi.fn(), + getCategoryById: vi.fn(), + getMonthCategoryById: vi.fn(), + updateMonthCategory: vi.fn(), + + // Transaction endpoints + getTransactions: vi.fn(), + getTransactionById: vi.fn(), + createTransaction: vi.fn(), + updateTransaction: vi.fn(), + deleteTransaction: vi.fn(), + getAccountTransactions: vi.fn(), + getCategoryTransactions: vi.fn(), + getPayeeTransactions: vi.fn(), + + // Scheduled transaction endpoints + getScheduledTransactions: vi.fn(), + getScheduledTransactionById: vi.fn(), + + // Payee endpoints + getPayees: vi.fn(), + getPayeeById: vi.fn(), + getPayeeLocations: vi.fn(), + getPayeeLocationById: vi.fn(), + + // Month endpoints + getBudgetMonths: vi.fn(), + getBudgetMonth: vi.fn(), + + // Import + importTransactions: vi.fn(), + }; +} + +export type MockClient = ReturnType; diff --git a/tests/unit/tools/fixtures/mock-payees.ts b/tests/unit/tools/fixtures/mock-payees.ts new file mode 100644 index 0000000..b5e2719 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-payees.ts @@ -0,0 +1,250 @@ +/** + * Mock Payee Fixtures + * + * Realistic YNAB payee data for testing. + */ + +import type { Payee, PayeeLocation } from 'ynab'; + +// Common payees +export const mockPayees: Payee[] = [ + { + id: 'payee-kroger', + name: 'Kroger', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-whole-foods', + name: 'Whole Foods', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-chipotle', + name: 'Chipotle', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-olive-garden', + name: 'Olive Garden', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-starbucks', + name: 'Starbucks', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-sushi-place', + name: 'Tokyo Sushi', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-netflix', + name: 'Netflix', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-spotify', + name: 'Spotify', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-planet-fitness', + name: 'Planet Fitness', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-landlord', + name: 'ABC Property Management', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-electric', + name: 'City Electric', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-comcast', + name: 'Comcast', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-verizon', + name: 'Verizon', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-employer', + name: 'Acme Corp', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-amazon', + name: 'Amazon', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-target', + name: 'Target', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-gas-station', + name: 'Shell Gas', + transfer_account_id: null, + deleted: false, + }, + { + id: 'payee-unknown', + name: 'Unknown Merchant', + transfer_account_id: null, + deleted: false, + }, +]; + +// Transfer payees (auto-created for transfers) +export const mockTransferPayees: Payee[] = [ + { + id: 'tp-checking-111', + name: 'Transfer : Primary Checking', + transfer_account_id: '11111111-1111-1111-1111-111111111111', + deleted: false, + }, + { + id: 'tp-savings-222', + name: 'Transfer : Emergency Fund', + transfer_account_id: '22222222-2222-2222-2222-222222222222', + deleted: false, + }, + { + id: 'tp-cc-333', + name: 'Transfer : Chase Visa', + transfer_account_id: '33333333-3333-3333-3333-333333333333', + deleted: false, + }, +]; + +// Deleted payee +export const mockDeletedPayee: Payee = { + id: 'payee-deleted', + name: 'Old Store', + transfer_account_id: null, + deleted: true, +}; + +// All payees +export const mockAllPayees: Payee[] = [...mockPayees, ...mockTransferPayees, mockDeletedPayee]; + +// Payee locations +export const mockPayeeLocations: PayeeLocation[] = [ + { + id: 'loc-kroger-1', + payee_id: 'payee-kroger', + latitude: '39.7392', + longitude: '-104.9903', + deleted: false, + }, + { + id: 'loc-kroger-2', + payee_id: 'payee-kroger', + latitude: '39.7500', + longitude: '-105.0000', + deleted: false, + }, + { + id: 'loc-starbucks-1', + payee_id: 'payee-starbucks', + latitude: '39.7400', + longitude: '-104.9850', + deleted: false, + }, + { + id: 'loc-chipotle-1', + payee_id: 'payee-chipotle', + latitude: '39.7450', + longitude: '-104.9900', + deleted: false, + }, + { + id: 'loc-target-1', + payee_id: 'payee-target', + latitude: '39.7300', + longitude: '-104.9800', + deleted: false, + }, +]; + +// Response factories +export function createPayeesResponse(payees: Payee[] = mockAllPayees) { + return { + data: { + payees, + server_knowledge: 12345, + }, + }; +} + +export function createPayeeResponse(payee: Payee = mockPayees[0]!) { + return { + data: { + payee, + }, + }; +} + +export function createPayeeLocationsResponse(locations: PayeeLocation[] = mockPayeeLocations) { + return { + data: { + payee_locations: locations, + }, + }; +} + +export function createPayeeLocationResponse(location: PayeeLocation = mockPayeeLocations[0]!) { + return { + data: { + payee_location: location, + }, + }; +} + +// Helper to get payee by ID +export function getPayeeById(payeeId: string): Payee | undefined { + return mockAllPayees.find((p) => p.id === payeeId); +} + +// Helper to get locations for a payee +export function getLocationsForPayee(payeeId: string): PayeeLocation[] { + return mockPayeeLocations.filter((l) => l.payee_id === payeeId); +} + +// Subscription payees (for recurring detection) +export const mockSubscriptionPayees = mockPayees.filter((p) => + ['payee-netflix', 'payee-spotify', 'payee-planet-fitness', 'payee-comcast', 'payee-verizon'].includes(p.id) +); + +// Dining payees +export const mockDiningPayees = mockPayees.filter((p) => + ['payee-chipotle', 'payee-olive-garden', 'payee-starbucks', 'payee-sushi-place'].includes(p.id) +); + +// Grocery payees +export const mockGroceryPayees = mockPayees.filter((p) => + ['payee-kroger', 'payee-whole-foods'].includes(p.id) +); diff --git a/tests/unit/tools/fixtures/mock-transactions.ts b/tests/unit/tools/fixtures/mock-transactions.ts new file mode 100644 index 0000000..f7fbbb4 --- /dev/null +++ b/tests/unit/tools/fixtures/mock-transactions.ts @@ -0,0 +1,460 @@ +/** + * Mock Transaction Fixtures + * + * Realistic YNAB transaction data for testing. + */ + +import type { TransactionDetail, ScheduledTransactionDetail } from 'ynab'; + +// Type for mock transactions with flexible cleared status +type MockTransaction = Omit & { + cleared: string; + flag_color: string | null; +}; + +// Helper to create a transaction +function createTransaction( + overrides: Partial & { id: string; date: string; amount: number } +): MockTransaction { + return { + account_id: '11111111-1111-1111-1111-111111111111', + account_name: 'Primary Checking', + payee_id: null, + payee_name: null, + category_id: null, + category_name: null, + transfer_account_id: null, + transfer_transaction_id: null, + matched_transaction_id: null, + import_id: null, + import_payee_name: null, + import_payee_name_original: null, + debt_transaction_type: null, + memo: null, + cleared: 'cleared', + approved: true, + flag_color: null, + flag_name: null, + subtransactions: [], + deleted: false, + ...overrides, + }; +} + +// Grocery transactions (recurring pattern) +export const mockGroceryTransactions: MockTransaction[] = [ + createTransaction({ + id: 'txn-grocery-001', + date: '2024-01-05', + amount: -85000, // $85 + payee_id: 'payee-kroger', + payee_name: 'Kroger', + category_id: 'cat-groceries-555', + category_name: 'Groceries', + memo: 'Weekly groceries', + }), + createTransaction({ + id: 'txn-grocery-002', + date: '2024-01-12', + amount: -92000, // $92 + payee_id: 'payee-kroger', + payee_name: 'Kroger', + category_id: 'cat-groceries-555', + category_name: 'Groceries', + }), + createTransaction({ + id: 'txn-grocery-003', + date: '2024-01-19', + amount: -78000, // $78 + payee_id: 'payee-kroger', + payee_name: 'Kroger', + category_id: 'cat-groceries-555', + category_name: 'Groceries', + }), + createTransaction({ + id: 'txn-grocery-004', + date: '2024-01-26', + amount: -105000, // $105 + payee_id: 'payee-whole-foods', + payee_name: 'Whole Foods', + category_id: 'cat-groceries-555', + category_name: 'Groceries', + memo: 'Special dinner ingredients', + }), +]; + +// Dining transactions +export const mockDiningTransactions: MockTransaction[] = [ + createTransaction({ + id: 'txn-dining-001', + date: '2024-01-03', + amount: -45000, // $45 + payee_id: 'payee-chipotle', + payee_name: 'Chipotle', + category_id: 'cat-dining-666', + category_name: 'Dining Out', + }), + createTransaction({ + id: 'txn-dining-002', + date: '2024-01-08', + amount: -85000, // $85 + payee_id: 'payee-olive-garden', + payee_name: 'Olive Garden', + category_id: 'cat-dining-666', + category_name: 'Dining Out', + memo: 'Dinner with friends', + }), + createTransaction({ + id: 'txn-dining-003', + date: '2024-01-15', + amount: -32000, // $32 + payee_id: 'payee-starbucks', + payee_name: 'Starbucks', + category_id: 'cat-dining-666', + category_name: 'Dining Out', + }), + createTransaction({ + id: 'txn-dining-004', + date: '2024-01-22', + amount: -68000, // $68 + payee_id: 'payee-sushi-place', + payee_name: 'Tokyo Sushi', + category_id: 'cat-dining-666', + category_name: 'Dining Out', + }), + createTransaction({ + id: 'txn-dining-005', + date: '2024-01-28', + amount: -45000, // $45 + payee_id: 'payee-chipotle', + payee_name: 'Chipotle', + category_id: 'cat-dining-666', + category_name: 'Dining Out', + }), +]; + +// Subscription transactions (monthly recurring) +export const mockSubscriptionTransactions: MockTransaction[] = [ + createTransaction({ + id: 'txn-netflix-001', + date: '2024-01-01', + amount: -15990, // $15.99 + payee_id: 'payee-netflix', + payee_name: 'Netflix', + category_id: 'cat-subscriptions-ddd', + category_name: 'Subscriptions', + import_id: 'YNAB:15990:2024-01-01:1', + }), + createTransaction({ + id: 'txn-spotify-001', + date: '2024-01-05', + amount: -10990, // $10.99 + payee_id: 'payee-spotify', + payee_name: 'Spotify', + category_id: 'cat-subscriptions-ddd', + category_name: 'Subscriptions', + import_id: 'YNAB:10990:2024-01-05:1', + }), + createTransaction({ + id: 'txn-gym-001', + date: '2024-01-01', + amount: -39000, // $39 + payee_id: 'payee-planet-fitness', + payee_name: 'Planet Fitness', + category_id: 'cat-subscriptions-ddd', + category_name: 'Subscriptions', + import_id: 'YNAB:39000:2024-01-01:1', + }), +]; + +// Bill transactions +export const mockBillTransactions: MockTransaction[] = [ + createTransaction({ + id: 'txn-rent-001', + date: '2024-01-01', + amount: -1500000, // $1,500 + payee_id: 'payee-landlord', + payee_name: 'ABC Property Management', + category_id: 'cat-rent-111', + category_name: 'Rent/Mortgage', + memo: 'January rent', + cleared: 'reconciled', + }), + createTransaction({ + id: 'txn-electric-001', + date: '2024-01-10', + amount: -125000, // $125 + payee_id: 'payee-electric', + payee_name: 'City Electric', + category_id: 'cat-utilities-222', + category_name: 'Utilities', + import_id: 'YNAB:125000:2024-01-10:1', + }), + createTransaction({ + id: 'txn-internet-001', + date: '2024-01-15', + amount: -80000, // $80 + payee_id: 'payee-comcast', + payee_name: 'Comcast', + category_id: 'cat-internet-333', + category_name: 'Internet', + import_id: 'YNAB:80000:2024-01-15:1', + }), + createTransaction({ + id: 'txn-phone-001', + date: '2024-01-18', + amount: -75000, // $75 + payee_id: 'payee-verizon', + payee_name: 'Verizon', + category_id: 'cat-phone-444', + category_name: 'Phone', + import_id: 'YNAB:75000:2024-01-18:1', + }), +]; + +// Income transactions +export const mockIncomeTransactions: MockTransaction[] = [ + createTransaction({ + id: 'txn-paycheck-001', + date: '2024-01-15', + amount: 2500000, // $2,500 + payee_id: 'payee-employer', + payee_name: 'Acme Corp', + category_id: 'cat-rta-iii', + category_name: 'Inflow: Ready to Assign', + memo: 'Paycheck', + cleared: 'reconciled', + }), + createTransaction({ + id: 'txn-paycheck-002', + date: '2024-01-31', + amount: 2500000, // $2,500 + payee_id: 'payee-employer', + payee_name: 'Acme Corp', + category_id: 'cat-rta-iii', + category_name: 'Inflow: Ready to Assign', + memo: 'Paycheck', + cleared: 'cleared', + }), +]; + +// Transfer transaction +export const mockTransferTransaction: MockTransaction = createTransaction({ + id: 'txn-transfer-001', + date: '2024-01-20', + amount: -500000, // $500 + payee_id: null, + payee_name: 'Transfer : Emergency Fund', + category_id: null, + category_name: null, + transfer_account_id: '22222222-2222-2222-2222-222222222222', + transfer_transaction_id: 'txn-transfer-001-paired', + memo: 'Monthly savings transfer', +}); + +// Credit card payment transaction +export const mockCreditCardPaymentTransaction: MockTransaction = createTransaction({ + id: 'txn-cc-payment-001', + date: '2024-01-25', + amount: -1500000, // $1,500 + account_id: '11111111-1111-1111-1111-111111111111', + account_name: 'Primary Checking', + payee_id: null, + payee_name: 'Transfer : Chase Visa', + category_id: null, + category_name: null, + transfer_account_id: '33333333-3333-3333-3333-333333333333', + transfer_transaction_id: 'txn-cc-payment-001-paired', + memo: 'Credit card payment', +}); + +// Split transaction +export const mockSplitTransaction: MockTransaction = createTransaction({ + id: 'txn-split-001', + date: '2024-01-20', + amount: -150000, // $150 + payee_id: 'payee-amazon', + payee_name: 'Amazon', + category_id: null, + category_name: 'Split (2 categories)', + memo: 'Various items', + subtransactions: [ + { + id: 'sub-001', + transaction_id: 'txn-split-001', + amount: -100000, // $100 + memo: 'Books', + payee_id: null, + payee_name: null, + category_id: 'cat-entertainment-ccc', + category_name: 'Entertainment', + transfer_account_id: null, + transfer_transaction_id: null, + deleted: false, + }, + { + id: 'sub-002', + transaction_id: 'txn-split-001', + amount: -50000, // $50 + memo: 'Kitchen supplies', + payee_id: null, + payee_name: null, + category_id: 'cat-shopping-eee', + category_name: 'Shopping', + transfer_account_id: null, + transfer_transaction_id: null, + deleted: false, + }, + ], +}); + +// Uncleared transaction +export const mockUnclearedTransaction: MockTransaction = createTransaction({ + id: 'txn-uncleared-001', + date: '2024-01-30', + amount: -55000, // $55 + payee_id: 'payee-target', + payee_name: 'Target', + category_id: 'cat-shopping-eee', + category_name: 'Shopping', + cleared: 'uncleared', + approved: false, +}); + +// Flagged transaction +export const mockFlaggedTransaction: MockTransaction = createTransaction({ + id: 'txn-flagged-001', + date: '2024-01-22', + amount: -200000, // $200 + payee_id: 'payee-unknown', + payee_name: 'Unknown Merchant', + category_id: 'cat-shopping-eee', + category_name: 'Shopping', + flag_color: 'red', + memo: 'Need to verify this charge', +}); + +// All transactions combined +export const mockAllTransactions: MockTransaction[] = [ + ...mockGroceryTransactions, + ...mockDiningTransactions, + ...mockSubscriptionTransactions, + ...mockBillTransactions, + ...mockIncomeTransactions, + mockTransferTransaction, + mockCreditCardPaymentTransaction, + mockSplitTransaction, + mockUnclearedTransaction, + mockFlaggedTransaction, +]; + +// Scheduled transactions +export const mockScheduledTransactions: ScheduledTransactionDetail[] = [ + { + id: 'sched-rent-001', + date_first: '2024-01-01', + date_next: '2024-02-01', + frequency: 'monthly', + amount: -1500000, // $1,500 + memo: 'Monthly rent', + flag_color: null, + flag_name: null, + account_id: '11111111-1111-1111-1111-111111111111', + account_name: 'Primary Checking', + payee_id: 'payee-landlord', + payee_name: 'ABC Property Management', + category_id: 'cat-rent-111', + category_name: 'Rent/Mortgage', + transfer_account_id: null, + deleted: false, + subtransactions: [], + }, + { + id: 'sched-paycheck-001', + date_first: '2024-01-15', + date_next: '2024-02-15', + frequency: 'twiceAMonth', + amount: 2500000, // $2,500 + memo: 'Paycheck', + flag_color: null, + flag_name: null, + account_id: '11111111-1111-1111-1111-111111111111', + account_name: 'Primary Checking', + payee_id: 'payee-employer', + payee_name: 'Acme Corp', + category_id: 'cat-rta-iii', + category_name: 'Inflow: Ready to Assign', + transfer_account_id: null, + deleted: false, + subtransactions: [], + }, + { + id: 'sched-savings-001', + date_first: '2024-01-20', + date_next: '2024-02-20', + frequency: 'monthly', + amount: -500000, // $500 + memo: 'Monthly savings', + flag_color: null, + flag_name: null, + account_id: '11111111-1111-1111-1111-111111111111', + account_name: 'Primary Checking', + payee_id: null, + payee_name: 'Transfer : Emergency Fund', + category_id: null, + category_name: null, + transfer_account_id: '22222222-2222-2222-2222-222222222222', + deleted: false, + subtransactions: [], + }, +]; + +// Response factories +export function createTransactionsResponse(transactions: MockTransaction[] = mockAllTransactions) { + return { + data: { + transactions: transactions as unknown as TransactionDetail[], + server_knowledge: 12345, + }, + }; +} + +export function createTransactionResponse(transaction: MockTransaction = mockGroceryTransactions[0]!) { + return { + data: { + transaction: transaction as unknown as TransactionDetail, + }, + }; +} + +export function createScheduledTransactionsResponse( + transactions: ScheduledTransactionDetail[] = mockScheduledTransactions +) { + return { + data: { + scheduled_transactions: transactions, + server_knowledge: 12345, + }, + }; +} + +export function createScheduledTransactionResponse( + transaction: ScheduledTransactionDetail = mockScheduledTransactions[0]! +) { + return { + data: { + scheduled_transaction: transaction, + }, + }; +} + +// Preset scenarios +export function createMonthTransactions(yearMonth: string): MockTransaction[] { + return mockAllTransactions + .filter((t) => !t.transfer_account_id) // Exclude transfers for spending analysis + .map((t) => ({ + ...t, + id: `${t.id}-${yearMonth}`, + date: t.date.replace(/^\d{4}-\d{2}/, yearMonth), + })); +} diff --git a/tests/unit/utils/dates.test.ts b/tests/unit/utils/dates.test.ts new file mode 100644 index 0000000..31f76af --- /dev/null +++ b/tests/unit/utils/dates.test.ts @@ -0,0 +1,210 @@ +/** + * Date Utilities Tests + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { + parseNaturalDate, + getDateRange, + formatDate, + isValidIsoDate, + daysBetween, + getCurrentMonth, + getPreviousMonth, +} from '../../../src/utils/dates.js'; + +describe('Date Utilities', () => { + beforeEach(() => { + // Mock date to 2026-01-23 for consistent testing + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-23T12:00:00Z')); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + describe('parseNaturalDate', () => { + it('should pass through ISO dates', () => { + expect(parseNaturalDate('2026-01-15')).toBe('2026-01-15'); + expect(parseNaturalDate('2025-12-31')).toBe('2025-12-31'); + }); + + it('should parse "today"', () => { + expect(parseNaturalDate('today')).toBe('2026-01-23'); + expect(parseNaturalDate('TODAY')).toBe('2026-01-23'); + }); + + it('should parse "yesterday"', () => { + expect(parseNaturalDate('yesterday')).toBe('2026-01-22'); + }); + + it('should parse "this week"', () => { + // Jan 23, 2026 is a Friday, so start of week (Sunday) is Jan 18 + expect(parseNaturalDate('this week')).toBe('2026-01-18'); + }); + + it('should parse "last week"', () => { + // Start of last week would be Jan 11 + expect(parseNaturalDate('last week')).toBe('2026-01-11'); + }); + + it('should parse "this month"', () => { + expect(parseNaturalDate('this month')).toBe('2026-01-01'); + }); + + it('should parse "last month"', () => { + expect(parseNaturalDate('last month')).toBe('2025-12-01'); + }); + + it('should parse "this year"', () => { + expect(parseNaturalDate('this year')).toBe('2026-01-01'); + }); + + it('should parse "last year"', () => { + expect(parseNaturalDate('last year')).toBe('2025-01-01'); + }); + + it('should parse "past N days"', () => { + expect(parseNaturalDate('past 7 days')).toBe('2026-01-16'); + expect(parseNaturalDate('past 30 days')).toBe('2025-12-24'); + expect(parseNaturalDate('last 1 day')).toBe('2026-01-22'); + }); + + it('should parse "past N weeks"', () => { + expect(parseNaturalDate('past 2 weeks')).toBe('2026-01-09'); + expect(parseNaturalDate('last 4 weeks')).toBe('2025-12-26'); + }); + + it('should parse "past N months"', () => { + // With day set to 1 first to prevent month overflow + expect(parseNaturalDate('past 3 months')).toBe('2025-10-01'); + expect(parseNaturalDate('last 6 months')).toBe('2025-07-01'); + }); + + // Month subtraction now sets day to 1 first to prevent overflow issues + // (e.g., Mar 31 - 1 month = Feb 31 = Mar 3 would be wrong without the fix) + it('should handle month subtraction without overflow', () => { + // With day set to 1 first: Jan 1 - 1 month = Dec 1 + expect(parseNaturalDate('past 1 month')).toBe('2025-12-01'); + }); + + it('should handle month subtraction from end of month dates', () => { + // Test with Jan 31 to verify no overflow + vi.setSystemTime(new Date('2026-01-31T12:00:00Z')); + // With day set to 1 first: Jan 1 - 1 month = Dec 1 (not Feb 31 = Mar 3) + expect(parseNaturalDate('past 1 month')).toBe('2025-12-01'); + // Restore to Jan 23 for other tests + vi.setSystemTime(new Date('2026-01-23T12:00:00Z')); + }); + + it('should parse "past N years"', () => { + expect(parseNaturalDate('past 1 years')).toBe('2025-01-23'); + expect(parseNaturalDate('last 2 years')).toBe('2024-01-23'); + }); + + it('should throw for unrecognized input', () => { + expect(() => parseNaturalDate('unknown')).toThrow('Unrecognized date format'); + expect(() => parseNaturalDate('next week')).toThrow('Unrecognized date format'); + }); + + it('should throw for invalid ISO dates', () => { + // Invalid month + expect(() => parseNaturalDate('2024-99-15')).toThrow('Unrecognized date format'); + // Invalid day for month + expect(() => parseNaturalDate('2024-02-30')).toThrow('Unrecognized date format'); + // Invalid day + expect(() => parseNaturalDate('2024-01-32')).toThrow('Unrecognized date format'); + }); + + it('should be case insensitive', () => { + expect(parseNaturalDate('TODAY')).toBe('2026-01-23'); + expect(parseNaturalDate('This Month')).toBe('2026-01-01'); + expect(parseNaturalDate('PAST 7 DAYS')).toBe('2026-01-16'); + }); + }); + + describe('getDateRange', () => { + it('should return start and end dates', () => { + const range = getDateRange('past 7 days'); + expect(range.start).toBe('2026-01-16'); + expect(range.end).toBe('2026-01-23'); + }); + + it('should work with this month', () => { + const range = getDateRange('this month'); + expect(range.start).toBe('2026-01-01'); + expect(range.end).toBe('2026-01-23'); + }); + }); + + describe('formatDate', () => { + it('should format dates correctly', () => { + // Use explicit year/month/day to avoid timezone issues + expect(formatDate(new Date(2026, 0, 23))).toBe('2026-01-23'); + expect(formatDate(new Date(2026, 11, 5))).toBe('2026-12-05'); + }); + + it('should pad single digit months and days', () => { + expect(formatDate(new Date(2026, 0, 5))).toBe('2026-01-05'); + expect(formatDate(new Date(2026, 8, 1))).toBe('2026-09-01'); + }); + }); + + describe('isValidIsoDate', () => { + it('should return true for valid dates', () => { + expect(isValidIsoDate('2026-01-23')).toBe(true); + expect(isValidIsoDate('2025-12-31')).toBe(true); + }); + + it('should return false for invalid formats', () => { + expect(isValidIsoDate('01-23-2026')).toBe(false); + expect(isValidIsoDate('2026/01/23')).toBe(false); + expect(isValidIsoDate('January 23, 2026')).toBe(false); + }); + + it('should return false for invalid dates', () => { + expect(isValidIsoDate('2026-13-01')).toBe(false); + expect(isValidIsoDate('2026-02-30')).toBe(false); + }); + }); + + describe('daysBetween', () => { + it('should calculate days between dates', () => { + expect(daysBetween('2026-01-01', '2026-01-31')).toBe(30); + expect(daysBetween('2026-01-01', '2026-01-02')).toBe(1); + }); + + it('should handle reverse order', () => { + expect(daysBetween('2026-01-31', '2026-01-01')).toBe(30); + }); + + it('should handle same day', () => { + expect(daysBetween('2026-01-15', '2026-01-15')).toBe(0); + }); + + it('should handle DST transitions correctly', () => { + // March 8, 2026 is DST start (spring forward) in US + expect(daysBetween('2026-03-07', '2026-03-09')).toBe(2); + // November 1, 2026 is DST end (fall back) in US + expect(daysBetween('2026-10-31', '2026-11-02')).toBe(2); + }); + + it('should handle year boundaries', () => { + expect(daysBetween('2025-12-31', '2026-01-01')).toBe(1); + expect(daysBetween('2025-12-25', '2026-01-05')).toBe(11); + }); + }); + + describe('getCurrentMonth', () => { + it('should return first day of current month', () => { + expect(getCurrentMonth()).toBe('2026-01-01'); + }); + }); + + describe('getPreviousMonth', () => { + it('should return first day of previous month', () => { + expect(getPreviousMonth()).toBe('2025-12-01'); + }); + }); +}); diff --git a/tests/unit/utils/errors.test.ts b/tests/unit/utils/errors.test.ts new file mode 100644 index 0000000..e8d4220 --- /dev/null +++ b/tests/unit/utils/errors.test.ts @@ -0,0 +1,153 @@ +/** + * Error Utilities Tests + */ + +import { describe, it, expect } from 'vitest'; +import { + ReadOnlyModeError, + YnabApiError, + ValidationError, + RateLimitError, + NotFoundError, + formatErrorResponse, +} from '../../../src/utils/errors.js'; + +describe('Error Classes', () => { + describe('ReadOnlyModeError', () => { + it('should create error with operation name', () => { + const error = new ReadOnlyModeError('createTransaction'); + expect(error.name).toBe('ReadOnlyModeError'); + expect(error.message).toContain('createTransaction'); + expect(error.message).toContain('READ_ONLY mode'); + }); + }); + + describe('YnabApiError', () => { + it('should create error with code and details', () => { + const error = new YnabApiError('Not found', '404', { resource: 'budget' }); + expect(error.name).toBe('YnabApiError'); + expect(error.code).toBe('404'); + expect(error.details).toEqual({ resource: 'budget' }); + }); + }); + + describe('ValidationError', () => { + it('should create error with field name', () => { + const error = new ValidationError('Invalid date format', 'since_date'); + expect(error.name).toBe('ValidationError'); + expect(error.field).toBe('since_date'); + }); + }); + + describe('RateLimitError', () => { + it('should create error with retry time', () => { + const error = new RateLimitError(5000); + expect(error.name).toBe('RateLimitError'); + expect(error.retryAfterMs).toBe(5000); + }); + }); + + describe('NotFoundError', () => { + it('should create error with resource and id', () => { + const error = new NotFoundError('Budget', 'abc-123'); + expect(error.name).toBe('NotFoundError'); + expect(error.message).toContain('Budget'); + expect(error.message).toContain('abc-123'); + }); + }); +}); + +describe('formatErrorResponse', () => { + it('should format ReadOnlyModeError', () => { + const error = new ReadOnlyModeError('deleteTransaction'); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('read_only_mode'); + expect(result.message).toContain('read-only'); + }); + + it('should format RateLimitError', () => { + const error = new RateLimitError(10000); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('rate_limit'); + expect(result.retry_after_ms).toBe(10000); + }); + + it('should format ValidationError', () => { + const error = new ValidationError('Invalid amount', 'amount'); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('validation_error'); + expect(result.field).toBe('amount'); + }); + + it('should format NotFoundError', () => { + const error = new NotFoundError('Account', 'xyz-456'); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('not_found'); + expect(result.message).toContain('Account'); + }); + + it('should format YnabApiError with known code', () => { + const error = new YnabApiError('Unauthorized', '401'); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('ynab_api_error'); + expect(result.code).toBe('401'); + expect(result.suggestion).toContain('Authentication failed'); + }); + + it('should format generic Error', () => { + const error = new Error('Something went wrong'); + const result = JSON.parse(formatErrorResponse(error)); + + expect(result.error).toBe(true); + expect(result.type).toBe('unknown_error'); + expect(result.message).toBe('Something went wrong'); + }); + + it('should handle non-Error values', () => { + const result = JSON.parse(formatErrorResponse('string error')); + + expect(result.error).toBe(true); + expect(result.message).toBe('string error'); + }); + + it('should format Zod-like validation errors', () => { + const zodError = { + issues: [ + { path: ['budget_id'], message: 'Required' }, + { path: ['amount'], message: 'Must be a number' }, + ], + }; + const result = JSON.parse(formatErrorResponse(zodError)); + + expect(result.error).toBe(true); + expect(result.type).toBe('validation_error'); + expect(result.issues).toHaveLength(2); + expect(result.issues[0].field).toBe('budget_id'); + }); + + it('should format YNAB SDK errors', () => { + const sdkError = { + error: { + id: '404', + detail: 'Budget not found', + }, + }; + const result = JSON.parse(formatErrorResponse(sdkError)); + + expect(result.error).toBe(true); + expect(result.type).toBe('ynab_api_error'); + expect(result.code).toBe('404'); + // Uses mapped message, not upstream detail (to prevent data leakage) + expect(result.message).toBe('Not found'); + }); +}); diff --git a/tests/unit/utils/milliunits.test.ts b/tests/unit/utils/milliunits.test.ts new file mode 100644 index 0000000..d8413a5 --- /dev/null +++ b/tests/unit/utils/milliunits.test.ts @@ -0,0 +1,195 @@ +import { describe, it, expect } from 'vitest'; +import { + formatCurrency, + formatCurrencyWithFormat, + toMilliunits, + toCents, + addMilliunits, + subtractMilliunits, + sumMilliunits, + percentageOfMilliunits, +} from '../../../src/utils/milliunits.js'; +import type { CurrencyFormat } from 'ynab'; + +describe('milliunits utilities', () => { + describe('formatCurrency', () => { + it('formats positive amounts', () => { + expect(formatCurrency(10000)).toBe('$10.00'); + expect(formatCurrency(10500)).toBe('$10.50'); + expect(formatCurrency(1000000)).toBe('$1000.00'); + }); + + it('formats negative amounts', () => { + expect(formatCurrency(-10000)).toBe('-$10.00'); + expect(formatCurrency(-25500)).toBe('-$25.50'); + }); + + it('formats zero', () => { + expect(formatCurrency(0)).toBe('$0.00'); + }); + + it('formats small amounts', () => { + expect(formatCurrency(1)).toBe('$0.00'); // 0.001 rounds to 0.00 + expect(formatCurrency(5)).toBe('$0.01'); // 0.005 rounds to 0.01 + expect(formatCurrency(10)).toBe('$0.01'); + expect(formatCurrency(100)).toBe('$0.10'); + }); + + it('uses custom currency symbol', () => { + expect(formatCurrency(10000, '€')).toBe('€10.00'); + expect(formatCurrency(-5000, '£')).toBe('-£5.00'); + }); + }); + + describe('formatCurrencyWithFormat', () => { + const usdFormat: CurrencyFormat = { + iso_code: 'USD', + example_format: '123,456.78', + decimal_digits: 2, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '$', + display_symbol: true, + }; + + const eurFormat: CurrencyFormat = { + iso_code: 'EUR', + example_format: '123.456,78', + decimal_digits: 2, + decimal_separator: ',', + symbol_first: false, + group_separator: '.', + currency_symbol: '€', + display_symbol: true, + }; + + const jpyFormat: CurrencyFormat = { + iso_code: 'JPY', + example_format: '123,456', + decimal_digits: 0, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '¥', + display_symbol: true, + }; + + const noSymbolFormat: CurrencyFormat = { + iso_code: 'USD', + example_format: '123,456.78', + decimal_digits: 2, + decimal_separator: '.', + symbol_first: true, + group_separator: ',', + currency_symbol: '$', + display_symbol: false, + }; + + it('formats USD correctly', () => { + expect(formatCurrencyWithFormat(10000, usdFormat)).toBe('$10.00'); + expect(formatCurrencyWithFormat(1234567890, usdFormat)).toBe('$1,234,567.89'); + expect(formatCurrencyWithFormat(-25500, usdFormat)).toBe('-$25.50'); + }); + + it('formats EUR correctly with symbol after and comma decimal', () => { + expect(formatCurrencyWithFormat(10000, eurFormat)).toBe('10,00€'); + expect(formatCurrencyWithFormat(1234567890, eurFormat)).toBe('1.234.567,89€'); + expect(formatCurrencyWithFormat(-25500, eurFormat)).toBe('-25,50€'); + }); + + it('formats JPY correctly with no decimal digits', () => { + expect(formatCurrencyWithFormat(10000, jpyFormat)).toBe('¥10'); + expect(formatCurrencyWithFormat(1234567000, jpyFormat)).toBe('¥1,234,567'); + expect(formatCurrencyWithFormat(-25000, jpyFormat)).toBe('-¥25'); + }); + + it('hides symbol when display_symbol is false', () => { + expect(formatCurrencyWithFormat(10000, noSymbolFormat)).toBe('10.00'); + expect(formatCurrencyWithFormat(-5000, noSymbolFormat)).toBe('-5.00'); + }); + + it('formats zero correctly', () => { + expect(formatCurrencyWithFormat(0, usdFormat)).toBe('$0.00'); + expect(formatCurrencyWithFormat(0, eurFormat)).toBe('0,00€'); + expect(formatCurrencyWithFormat(0, jpyFormat)).toBe('¥0'); + }); + + it('handles large numbers with group separators', () => { + expect(formatCurrencyWithFormat(1000000000000, usdFormat)).toBe('$1,000,000,000.00'); + expect(formatCurrencyWithFormat(1000000000000, eurFormat)).toBe('1.000.000.000,00€'); + }); + }); + + describe('toMilliunits', () => { + it('converts dollars to milliunits', () => { + expect(toMilliunits(10)).toBe(10000); + expect(toMilliunits(10.5)).toBe(10500); + expect(toMilliunits(0.01)).toBe(10); + }); + + it('handles string input', () => { + expect(toMilliunits('25.50')).toBe(25500); + expect(toMilliunits('100')).toBe(100000); + }); + + it('handles negative amounts', () => { + expect(toMilliunits(-25)).toBe(-25000); + expect(toMilliunits(-0.5)).toBe(-500); + }); + + it('rounds to nearest milliunit', () => { + expect(toMilliunits(10.0005)).toBe(10001); + expect(toMilliunits(10.0004)).toBe(10000); + }); + }); + + describe('toCents', () => { + it('converts milliunits to cents', () => { + expect(toCents(10000)).toBe(1000); // $10.00 = 1000 cents + expect(toCents(10500)).toBe(1050); // $10.50 = 1050 cents + expect(toCents(-5000)).toBe(-500); // -$5.00 = -500 cents + }); + }); + + describe('addMilliunits', () => { + it('adds two amounts', () => { + expect(addMilliunits(10000, 5000)).toBe(15000); + expect(addMilliunits(-10000, 5000)).toBe(-5000); + }); + }); + + describe('subtractMilliunits', () => { + it('subtracts two amounts', () => { + expect(subtractMilliunits(10000, 3000)).toBe(7000); + expect(subtractMilliunits(5000, 10000)).toBe(-5000); + }); + }); + + describe('sumMilliunits', () => { + it('sums an array of amounts', () => { + expect(sumMilliunits([1000, 2000, 3000])).toBe(6000); + expect(sumMilliunits([10000, -5000, 2500])).toBe(7500); + }); + + it('returns 0 for empty array', () => { + expect(sumMilliunits([])).toBe(0); + }); + }); + + describe('percentageOfMilliunits', () => { + it('calculates percentage', () => { + expect(percentageOfMilliunits(5000, 10000)).toBe(50); + expect(percentageOfMilliunits(2500, 10000)).toBe(25); + expect(percentageOfMilliunits(10000, 10000)).toBe(100); + }); + + it('returns 0 when whole is 0', () => { + expect(percentageOfMilliunits(5000, 0)).toBe(0); + }); + + it('rounds to one decimal place', () => { + expect(percentageOfMilliunits(3333, 10000)).toBe(33.3); + }); + }); +}); diff --git a/tests/unit/utils/sanitize.test.ts b/tests/unit/utils/sanitize.test.ts new file mode 100644 index 0000000..2b80e17 --- /dev/null +++ b/tests/unit/utils/sanitize.test.ts @@ -0,0 +1,280 @@ +import { describe, it, expect } from 'vitest'; +import { + sanitizeString, + sanitizeStringOrEmpty, + sanitizeMemo, + sanitizeName, + sanitizeErrorMessage, +} from '../../../src/utils/sanitize.js'; + +describe('sanitize utilities', () => { + describe('sanitizeString', () => { + it('returns null for null input', () => { + expect(sanitizeString(null)).toBeNull(); + }); + + it('returns null for undefined input', () => { + expect(sanitizeString(undefined)).toBeNull(); + }); + + it('trims whitespace', () => { + expect(sanitizeString(' hello world ')).toBe('hello world'); + }); + + it('removes control characters', () => { + expect(sanitizeString('hello\x00world')).toBe('helloworld'); + expect(sanitizeString('test\x1Fvalue')).toBe('testvalue'); + expect(sanitizeString('foo\x7Fbar')).toBe('foobar'); + }); + + it('removes Unicode line and paragraph separators', () => { + // U+2028 (line separator) and U+2029 (paragraph separator) can break JS string literals + expect(sanitizeString('hello\u2028world')).toBe('helloworld'); + expect(sanitizeString('test\u2029value')).toBe('testvalue'); + expect(sanitizeString('foo\u2028bar\u2029baz')).toBe('foobarbaz'); + }); + + it('preserves tabs, newlines, and carriage returns', () => { + expect(sanitizeString('hello\tworld')).toBe('hello\tworld'); + expect(sanitizeString('hello\nworld')).toBe('hello\nworld'); + expect(sanitizeString('hello\rworld')).toBe('hello\rworld'); + }); + + it('truncates long strings within maxLength', () => { + const longString = 'a'.repeat(600); + const result = sanitizeString(longString); + // Total output is exactly 500 chars (497 + 3 for '...') + expect(result).toBe('a'.repeat(497) + '...'); + expect(result.length).toBe(500); + }); + + it('respects custom maxLength including ellipsis', () => { + const result = sanitizeString('hello world', 5); + // Total output is exactly 5 chars (2 + 3 for '...') + expect(result).toBe('he...'); + expect(result.length).toBe(5); + }); + + it('handles maxLength of exactly 3', () => { + expect(sanitizeString('hello', 3)).toBe('hel'); + }); + + it('handles maxLength of 1', () => { + expect(sanitizeString('hello', 1)).toBe('h'); + }); + + it('handles maxLength of 2', () => { + expect(sanitizeString('hello', 2)).toBe('he'); + }); + + it('handles normal strings', () => { + expect(sanitizeString('Hello World')).toBe('Hello World'); + expect(sanitizeString('Test 123')).toBe('Test 123'); + }); + + it('handles empty string', () => { + expect(sanitizeString('')).toBe(''); + }); + + it('handles control characters near truncation boundary', () => { + // String with control chars that after removal is at the boundary + const str = 'a'.repeat(495) + '\x00\x01\x02\x03\x04'; + const result = sanitizeString(str); + // Control chars removed, result should be exactly 495 chars (under limit) + expect(result).toBe('a'.repeat(495)); + expect(result?.length).toBe(495); + expect(result).not.toContain('\x00'); + }); + + it('handles control characters with truncation needed after removal', () => { + // String that exceeds limit even after control char removal + const str = 'a'.repeat(600) + '\x00\x01\x02'; + const result = sanitizeString(str); + // Control chars removed, then truncated to 500 (497 + '...') + expect(result).toBe('a'.repeat(497) + '...'); + expect(result?.length).toBe(500); + }); + }); + + describe('sanitizeStringOrEmpty', () => { + it('returns empty string for null input', () => { + expect(sanitizeStringOrEmpty(null)).toBe(''); + }); + + it('returns empty string for undefined input', () => { + expect(sanitizeStringOrEmpty(undefined)).toBe(''); + }); + + it('returns sanitized string for valid input', () => { + expect(sanitizeStringOrEmpty(' hello ')).toBe('hello'); + }); + }); + + describe('sanitizeMemo', () => { + it('allows up to 1000 characters', () => { + const longMemo = 'a'.repeat(900); + expect(sanitizeMemo(longMemo)).toBe(longMemo); + }); + + it('truncates beyond 1000 characters within limit', () => { + const veryLongMemo = 'a'.repeat(1100); + const result = sanitizeMemo(veryLongMemo); + // Total output is exactly 1000 chars (997 + 3 for '...') + expect(result).toBe('a'.repeat(997) + '...'); + expect(result?.length).toBe(1000); + }); + + it('returns null for null input', () => { + expect(sanitizeMemo(null)).toBeNull(); + }); + + it('returns null for undefined input', () => { + expect(sanitizeMemo(undefined)).toBeNull(); + }); + }); + + describe('sanitizeName', () => { + it('returns "Unknown" for null input', () => { + expect(sanitizeName(null)).toBe('Unknown'); + }); + + it('returns "Unknown" for undefined input', () => { + expect(sanitizeName(undefined)).toBe('Unknown'); + }); + + it('sanitizes valid names', () => { + expect(sanitizeName('Groceries')).toBe('Groceries'); + expect(sanitizeName(' Rent ')).toBe('Rent'); + }); + + it('removes control characters from names', () => { + expect(sanitizeName('Test\x00Name')).toBe('TestName'); + }); + + it('truncates long names within 200 characters', () => { + const longName = 'a'.repeat(250); + const result = sanitizeName(longName); + // Total output is exactly 200 chars (197 + 3 for '...') + expect(result).toBe('a'.repeat(197) + '...'); + expect(result.length).toBe(200); + }); + + it('returns "Unknown" for whitespace-only input', () => { + expect(sanitizeName(' ')).toBe('Unknown'); + expect(sanitizeName('\t\n\r')).toBe('Unknown'); + }); + + it('returns "Unknown" for control-characters-only input', () => { + expect(sanitizeName('\x00\x01\x02')).toBe('Unknown'); + expect(sanitizeName('\x1F\x7F')).toBe('Unknown'); + }); + + it('returns "Unknown" for empty string input', () => { + expect(sanitizeName('')).toBe('Unknown'); + }); + }); + + describe('sanitizeErrorMessage', () => { + it('extracts message from Error objects', () => { + const error = new Error('Something went wrong'); + expect(sanitizeErrorMessage(error)).toBe('Something went wrong'); + }); + + it('handles string errors', () => { + expect(sanitizeErrorMessage('A string error')).toBe('A string error'); + }); + + it('returns generic message for non-string/Error values', () => { + expect(sanitizeErrorMessage(null)).toBe('An error occurred'); + expect(sanitizeErrorMessage(undefined)).toBe('An error occurred'); + expect(sanitizeErrorMessage({})).toBe('An error occurred'); + expect(sanitizeErrorMessage(123)).toBe('An error occurred'); + }); + + it('redacts Bearer tokens', () => { + const error = 'Failed with Bearer abc123xyz456 in request'; + expect(sanitizeErrorMessage(error)).toBe('Failed with Bearer [REDACTED] in request'); + }); + + it('redacts token= patterns', () => { + const error = 'Failed with token=secret123'; + expect(sanitizeErrorMessage(error)).toBe('Failed with token=[REDACTED]'); + }); + + it('redacts access_token patterns', () => { + const error = 'access_token: "my-secret-token"'; + expect(sanitizeErrorMessage(error)).toBe('access_token=[REDACTED]'); + }); + + it('redacts api_key patterns', () => { + const error = 'api_key=supersecret123'; + expect(sanitizeErrorMessage(error)).toBe('api_key=[REDACTED]'); + }); + + it('redacts Unix file paths', () => { + const error = 'Error in /Users/john/projects/app/config.ts'; + expect(sanitizeErrorMessage(error)).toBe('Error in [PATH_REDACTED]'); + }); + + it('redacts Windows file paths', () => { + const error = 'Error in C:\\Users\\john\\Documents\\secret.txt'; + expect(sanitizeErrorMessage(error)).toBe('Error in [PATH_REDACTED]'); + }); + + it('redacts stack trace file references', () => { + // Path matching happens before file reference matching + const error = 'Error at (/home/user/app/src/index.ts:42:10)'; + expect(sanitizeErrorMessage(error)).toContain('[PATH_REDACTED]'); + expect(sanitizeErrorMessage(error)).not.toContain('/home/user'); + }); + + it('redacts full stack trace at statements', () => { + // Use a non-matching path prefix to test the stack pattern + const error = 'at processRequest (app/server.js:100:5)'; + expect(sanitizeErrorMessage(error)).toBe('at [STACK_REDACTED]'); + }); + + it('removes control characters', () => { + const error = new Error('Error\x00with\x1Fcontrol\x7Fchars'); + expect(sanitizeErrorMessage(error)).toBe('Errorwithcontrolchars'); + }); + + it('respects maxLength parameter', () => { + const error = new Error('a'.repeat(600)); + const result = sanitizeErrorMessage(error, 100); + expect(result.length).toBe(100); + expect(result).toBe('a'.repeat(97) + '...'); + }); + + it('handles multiple sensitive patterns in one message', () => { + const error = 'Request to /Users/dev/app failed with token=secret123 and api_key=abc'; + const result = sanitizeErrorMessage(error); + expect(result).not.toContain('/Users/dev/app'); + expect(result).not.toContain('secret123'); + expect(result).not.toContain('abc'); + expect(result).toContain('[PATH_REDACTED]'); + expect(result).toContain('token=[REDACTED]'); + expect(result).toContain('api_key=[REDACTED]'); + }); + + it('handles Error with empty message', () => { + const error = new Error(''); + expect(sanitizeErrorMessage(error)).toBe(''); + }); + + it('redacts password patterns', () => { + const error = 'Failed with password=secret123'; + expect(sanitizeErrorMessage(error)).toBe('Failed with password=[REDACTED]'); + }); + + it('redacts pwd patterns', () => { + const error = 'Failed with pwd: "mypassword"'; + expect(sanitizeErrorMessage(error)).toBe('Failed with pwd=[REDACTED]'); + }); + + it('redacts secret patterns', () => { + const error = 'secret=supersecret123 was exposed'; + expect(sanitizeErrorMessage(error)).toBe('secret=[REDACTED] was exposed'); + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..b1679e7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "allowUnusedLabels": false, + "allowUnreachableCode": false, + "exactOptionalPropertyTypes": true, + "noPropertyAccessFromIndexSignature": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "tests"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..8f5c266 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,32 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + include: ['tests/**/*.test.ts'], + exclude: ['node_modules', 'dist'], + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + exclude: [ + 'node_modules', + 'dist', + 'tests', + '**/*.d.ts', + '**/*.config.*', + '**/types/**' + ], + thresholds: { + global: { + branches: 80, + functions: 80, + lines: 80, + statements: 80 + } + } + }, + testTimeout: 10000, + hookTimeout: 10000 + } +});