commit cb61a7d4574f0944c864bc95d07b768419925ce2 Author: Alex Date: Mon Nov 16 02:35:04 2026 +0000 LocalPing: self-hosted uptime monitor with static public status site diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8c3191e --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# Server Configuration +API_PORT=8000 +NODE_ENV=production +SESSION_SECRET=change_me_to_a_random_string + +# Notification Settings +NOTIFICATION_ENABLED=false +NOTIFICATION_METHOD=dbus + +# Monitoring +PING_INTERVAL=60 +ALERT_COOLDOWN=300 + +# API Authentication +ADMIN_API_KEY=localping-admin-key-12345 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7f6c91b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.env +data/ +logs/ +*.log diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..470d9bc --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,166 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +LocalPing is a self-hosted uptime monitoring system for homelabs. It monitors services using ICMP, TCP, UDP, HTTP/HTTPS protocols with real-time dashboards and historical tracking. Data is stored in PostgreSQL via Prisma ORM. + +## Commands + +```bash +# Development +npm run dev # Start with nodemon (auto-reload) +npm start # Start production server + +# Database (Prisma) +npm run prisma:generate # Generate Prisma client after schema changes +npm run prisma:push # Push schema changes to database +npm run prisma:studio # Open Prisma Studio GUI + +# Testing +npm test # Run all tests +npm run test:watch # Run tests in watch mode +npm run test:coverage # Run tests with coverage +npm run test:backup # Run backup service tests only + +# Production (PM2) +npm run pm2:start # Start with PM2 +npm run pm2:stop # Stop all PM2 processes +npm run pm2:restart # Restart all PM2 processes +npm run pm2:logs # View PM2 logs + +# Other +npm run gui # Launch Electron GUI +npm run web # Start in web-only mode +npm run verify:ping # Verify ping data integrity +``` + +### ICMP Capabilities (Linux) +```bash +sudo setcap cap_net_raw=ep $(which node) +``` + +## Architecture + +### Entry Point & Server +- `src/app.js` - Express server with WebSocket support, session management, route loading, and graceful shutdown handling + +### Database Layer (Prisma) +- `prisma/schema.prisma` - Database schema definition with 12 models +- `src/config/prisma.js` - Prisma client singleton and connection management +- `src/services/cacheService.js` - In-memory caching layer for database queries + +### Core Services +- `src/services/monitorService.js` - Central monitoring orchestrator. Manages ping intervals, status tracking (in-memory Map), alert cooldowns, and retry logic +- `src/services/pingService.js` - Ping execution layer. Delegates to worker pool for multi-threaded pings +- `src/services/workers/workerPool.js` - Thread pool manager (size: 2-8 based on CPU cores) +- `src/services/workers/pingWorker.js` - Worker thread for executing individual pings + +### Notification & Events +- `src/services/notificationService.js` - Discord webhook notifications for monitor status changes and incidents +- `src/services/eventDetectionService.js` - Rule-based event detection and auto-incident creation + +### Routes +- `src/routes/api.js` - REST API endpoints (`/api/*`) - requires API key auth +- `src/routes/admin.js` - Admin panel routes (`/admin/*`) - requires session auth +- `src/routes/public.js` - Public status page routes (`/`) +- `src/routes/setup.js` - First-time setup wizard (`/setup`) + +### Middleware +- `src/middleware/auth.js` - API key validation, rate limiting, input validation +- `src/middleware/setupCheck.js` - Redirects to setup wizard if not configured + +### Views +- `src/views/*.ejs` - EJS templates for admin panel, public dashboard, and setup wizard + +## Database Schema (Prisma) + +Models defined in `prisma/schema.prisma`: +- `Target` - Monitor configurations (host, protocol, interval, etc.) +- `PingResult` - Individual ping results with timestamps +- `Statistic` - Daily aggregated statistics per target (unique on targetId + date) +- `Alert` - Status change alerts +- `Incident` - Manual/auto-created incidents +- `EventRule` - Event detection rules for auto-incidents +- `Action` - Target-specific actions +- `Favicon` - Cached favicons for apps +- `NotificationSettings` - Discord webhook configuration (singleton) +- `AdminSettings` - Session duration, data retention, debug logging (singleton) +- `PublicUISettings` - Public dashboard customization (singleton) +- `Post` - Blog posts + +## Key Patterns + +### Monitor Status Flow +1. `monitorService.startMonitoring()` loads enabled targets +2. Each target gets an interval timer calling `pingTarget()` +3. `pingService.ping()` delegates to worker pool +4. Results stored via `prisma.pingResult.create()` +5. Status changes trigger `notificationService` and `eventDetectionService` + +### Database Query Pattern (Prisma) +```javascript +const { getPrisma } = require('../config/prisma'); +const prisma = getPrisma(); + +// Find all enabled targets +const targets = await prisma.target.findMany({ where: { enabled: true } }); + +// Find by ID +const target = await prisma.target.findUnique({ where: { id: targetId } }); + +// Create +await prisma.pingResult.create({ data: { targetId, success: true, responseTime: 50 } }); + +// Update +await prisma.target.update({ where: { id }, data: { name: 'New Name' } }); + +// Delete +await prisma.target.delete({ where: { id } }); + +// Raw SQL (for complex queries) +const result = await prisma.$queryRaw`SELECT * FROM targets WHERE enabled = true`; +``` + +### Non-Blocking Design +- Initial pings run in background (`setImmediate`, `Promise.allSettled`) +- Database writes deferred with `setImmediate` +- Worker pool prevents ping operations from blocking main thread + +## Environment Variables + +```env +DATABASE_URL="postgresql://localping:localping@localhost:5432/localping" +API_PORT=8000 # Server port +SESSION_SECRET=... # Express session secret +PING_INTERVAL=60 # Default ping interval (seconds) +ALERT_COOLDOWN=300 # Alert cooldown (seconds) +``` + +## Testing + +Tests are in `__tests__/` directory using Jest: +- `__tests__/services/backupService.test.js` - Export/import functionality +- `__tests__/services/pingService.test.js` - Ping service tests + +Run single test file: +```bash +npx jest __tests__/services/backupService.test.js +``` + +## Migration Note + +This codebase was migrated from a custom MongoDB-style PostgreSQL wrapper (`pg` package with `db.collection()` API) to Prisma ORM. Some route files may still contain legacy patterns that need to be updated to use the Prisma client. + +Legacy pattern (to be replaced): +```javascript +const db = getDB(); +await db.collection('targets').find({}).toArray(); +``` + +New Prisma pattern: +```javascript +const prisma = getPrisma(); +await prisma.target.findMany(); +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..9d5055e --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# LocalPing + +Self-hosted uptime monitor for homelabs: ICMP/TCP/UDP/HTTP(S) checks, incident log, news posts, admin panel, and a fast static public status site. + +## Install +```bash +git clone https://github.com/YOUR-ORG/localping.git && cd localping +sudo ./install.sh # Ubuntu 22.04+: Node, Postgres, systemd service +``` +Then open `http://:8000/setup` to create the admin account. + +## Public site +The public frontend is plain HTML/CSS/JS in `src/site` (no build step, ~10 KB). It reads a slim JSON API (`/api/site/summary`, `/api/site/news`) and supports: +- service **tiers** (featured / normal / background), per-service **explainers** (β“˜) and a **public link** switch, edited in *Admin β†’ Site* +- custom **name, accent colour and app icon** (also used for the PWA manifest), in *Admin β†’ Site* +- `SITE_DIR=/path/to/theme` to serve your own theme; `SITE_HOSTS=status.example.com` to limit it to certain hostnames +- `SITE_NAME`, `SITE_URL` env vars for RSS + +Edit the About page and footer in `src/site`. + +## Dev +`npm install && npx prisma db push && npm run dev`. Tests: `npm test`. +License: MIT. diff --git a/__tests__/services/backupService.test.js b/__tests__/services/backupService.test.js new file mode 100644 index 0000000..d19f85b --- /dev/null +++ b/__tests__/services/backupService.test.js @@ -0,0 +1,710 @@ +// Mock uuid before requiring backupService +jest.mock('uuid', () => ({ + v4: () => { + return 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(); + } +})); + +const backupService = require('../../src/services/backupService'); +const { getDB } = require('../../src/config/db'); + +// Simple UUID generator for tests +function generateId() { + return 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(); +} + +// Mock the database with shared state +const mockCollections = { + targets: [], + incidents: [], + posts: [], + pingResults: [], + statistics: [], + actions: [], + alerts: [], + adminSettings: [], + publicUISettings: [], + favicons: [] +}; + +jest.mock('../../src/config/db', () => { + + const createMockCollection = (name) => { + return { + find: (query = {}) => ({ + toArray: async () => { + let results = mockCollections[name] || []; + // Simple query matching + if (Object.keys(query).length > 0) { + results = results.filter(item => { + return Object.keys(query).every(key => { + if (query[key] && typeof query[key] === 'object' && '$in' in query[key]) { + return query[key].$in.includes(item[key]); + } + return item[key] === query[key]; + }); + }); + } + return results; + } + }), + findOne: async (query = {}) => { + const items = mockCollections[name] || []; + if (Object.keys(query).length === 0) { + return items[0] || null; + } + return items.find(item => { + return Object.keys(query).every(key => item[key] === query[key]); + }) || null; + }, + insertOne: async (doc) => { + if (!mockCollections[name]) { + mockCollections[name] = []; + } + if (!doc._id) { + // Generate a simple ID for testing + doc._id = 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(); + } + mockCollections[name].push(doc); + return { insertedId: doc._id }; + }, + updateOne: async (query, update) => { + const items = mockCollections[name] || []; + const index = items.findIndex(item => { + return Object.keys(query).every(key => item[key] === query[key]); + }); + if (index !== -1 && update.$set) { + items[index] = { ...items[index], ...update.$set }; + return { modifiedCount: 1 }; + } + return { modifiedCount: 0 }; + }, + deleteOne: async (query) => { + const items = mockCollections[name] || []; + const index = items.findIndex(item => { + return Object.keys(query).every(key => item[key] === query[key]); + }); + if (index !== -1) { + items.splice(index, 1); + return { deletedCount: 1 }; + } + return { deletedCount: 0 }; + } + }; + }; + + return { + getDB: () => ({ + collection: (name) => createMockCollection(name), + query: async (sql, params) => { + // Simple mock for SQL queries used in positions endpoint + if (sql.includes('SELECT _id FROM targets WHERE _id IN')) { + const targetIds = params; + const targets = mockCollections.targets.filter(t => targetIds.includes(t._id)); + return { rows: targets.map(t => ({ _id: t._id })) }; + } + return { rows: [] }; + } + }) + }; +}); + +describe('BackupService', () => { + let mockDB; + + beforeEach(async () => { + jest.clearAllMocks(); + mockDB = getDB(); + // Clear all collections + Object.keys(mockCollections).forEach(key => { + mockCollections[key] = []; + }); + }); + + describe('exportData', () => { + it('should export full data when full option is true', async () => { + // Setup test data + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Test Target', + host: 'example.com', + protocol: 'HTTP', + port: 80, + auth: JSON.stringify({ username: 'test', password: 'pass' }), + quickCommands: JSON.stringify(['cmd1', 'cmd2']) + }); + + const result = await backupService.exportData({ full: true }); + + expect(result).toHaveProperty('version'); + expect(result).toHaveProperty('exportDate'); + expect(result).toHaveProperty('data'); + expect(result.data).toHaveProperty('targets'); + expect(result.data.targets).toHaveLength(1); + expect(result.data.targets[0].name).toBe('Test Target'); + // Should parse JSON fields + expect(typeof result.data.targets[0].auth).toBe('object'); + expect(Array.isArray(result.data.targets[0].quickCommands)).toBe(true); + }); + + it('should export only monitors when monitors option is true', async () => { + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Test Target', + host: 'example.com' + }); + + const result = await backupService.exportData({ monitors: true }); + + expect(result.data).toHaveProperty('targets'); + expect(result.data.targets).toHaveLength(1); + expect(result.data).not.toHaveProperty('incidents'); + expect(result.data).not.toHaveProperty('posts'); + }); + + it('should export incidents when incidents option is true', async () => { + const incidentId = generateId(); + await mockDB.collection('incidents').insertOne({ + _id: incidentId, + title: 'Test Incident', + status: 'investigating' + }); + + const result = await backupService.exportData({ incidents: true }); + + expect(result.data).toHaveProperty('incidents'); + expect(result.data.incidents).toHaveLength(1); + expect(result.data.incidents[0].title).toBe('Test Incident'); + }); + + it('should export posts when posts option is true', async () => { + const postId = generateId(); + await mockDB.collection('posts').insertOne({ + _id: postId, + title: 'Test Post', + content: 'Test Content' + }); + + const result = await backupService.exportData({ posts: true }); + + expect(result.data).toHaveProperty('posts'); + expect(result.data.posts).toHaveLength(1); + expect(result.data.posts[0].title).toBe('Test Post'); + }); + + it('should export data points when dataPoints option is true', async () => { + const pingId = generateId(); + const statId = generateId(); + await mockDB.collection('pingResults').insertOne({ + _id: pingId, + targetId: generateId(), + success: true, + responseTime: 100 + }); + await mockDB.collection('statistics').insertOne({ + _id: statId, + targetId: generateId(), + date: new Date(), + totalPings: 100 + }); + + const result = await backupService.exportData({ dataPoints: true }); + + expect(result.data).toHaveProperty('pingResults'); + expect(result.data).toHaveProperty('statistics'); + expect(result.data).toHaveProperty('ping_results'); // Legacy format + expect(result.data).toHaveProperty('daily_stats'); // Legacy format + expect(result.data.pingResults).toHaveLength(1); + expect(result.data.statistics).toHaveLength(1); + }); + + it('should export settings when settings option is true', async () => { + await mockDB.collection('adminSettings').insertOne({ + _id: 'settings', + sessionDurationDays: 30 + }); + await mockDB.collection('publicUISettings').insertOne({ + _id: 'settings', + title: 'Test Title' + }); + + const result = await backupService.exportData({ settings: true }); + + expect(result.data).toHaveProperty('adminSettings'); + expect(result.data).toHaveProperty('publicUISettings'); + expect(result.data.adminSettings.sessionDurationDays).toBe(30); + expect(result.data.publicUISettings.title).toBe('Test Title'); + }); + + it('should parse JSON fields in targets correctly', async () => { + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Test Target', + auth: JSON.stringify({ username: 'user', password: 'pass' }), + quickCommands: JSON.stringify(['cmd1', 'cmd2']) + }); + + const result = await backupService.exportData({ monitors: true }); + + expect(typeof result.data.targets[0].auth).toBe('object'); + expect(result.data.targets[0].auth.username).toBe('user'); + expect(Array.isArray(result.data.targets[0].quickCommands)).toBe(true); + expect(result.data.targets[0].quickCommands[0]).toBe('cmd1'); + }); + + it('should handle invalid JSON in auth field gracefully', async () => { + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Test Target', + auth: 'invalid json {' + }); + + const result = await backupService.exportData({ monitors: true }); + + expect(result.data.targets[0].auth).toBeNull(); + }); + + it('should return empty arrays when collections are empty', async () => { + const result = await backupService.exportData({ monitors: true }); + + expect(result.data.targets).toEqual([]); + }); + }); + + describe('importData', () => { + it('should import targets successfully', async () => { + const targetId = generateId(); + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Imported Target', + host: 'example.com', + protocol: 'HTTP', + port: 80, + auth: { username: 'user', password: 'pass' }, + quickCommands: ['cmd1'] + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('targets'); + expect(result.imported.targets.imported).toBe(1); + + // Verify target was imported + const imported = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(imported).toBeTruthy(); + expect(imported.name).toBe('Imported Target'); + // Auth should be stringified + expect(typeof imported.auth).toBe('string'); + }); + + it('should skip existing targets when overwrite is false', async () => { + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Existing Target', + host: 'old.com' + }); + + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Existing Target', + host: 'new.com' + }] + } + }; + + const result = await backupService.importData(importData, { overwrite: false }); + + expect(result.imported.targets.skipped).toBe(1); + + // Verify target was not updated + const existing = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(existing.host).toBe('old.com'); + }); + + it('should update existing targets when overwrite is true', async () => { + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Existing Target', + host: 'old.com' + }); + + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Existing Target', + host: 'new.com' + }] + } + }; + + const result = await backupService.importData(importData, { overwrite: true }); + + expect(result.imported.targets.updated).toBe(1); + + // Verify target was updated + const updated = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(updated.host).toBe('new.com'); + }); + + it('should handle targets with same name but different ID', async () => { + const existingId = generateId(); + const newId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: existingId, + name: 'Same Name', + host: 'old.com' + }); + + const importData = { + data: { + targets: [{ + _id: newId, + name: 'Same Name', + host: 'new.com' + }] + } + }; + + const result = await backupService.importData(importData, { overwrite: true }); + + // Should update existing target with same name + expect(result.imported.targets.updated).toBe(1); + + const updated = await mockDB.collection('targets').findOne({ _id: existingId }); + expect(updated.host).toBe('new.com'); + }); + + it('should import incidents successfully', async () => { + const incidentId = generateId(); + const importData = { + data: { + incidents: [{ + _id: incidentId, + title: 'Imported Incident', + status: 'investigating' + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('incidents'); + expect(result.imported.incidents.imported).toBe(1); + + const imported = await mockDB.collection('incidents').findOne({ _id: incidentId }); + expect(imported).toBeTruthy(); + expect(imported.title).toBe('Imported Incident'); + }); + + it('should import posts successfully', async () => { + const postId = generateId(); + const importData = { + data: { + posts: [{ + _id: postId, + title: 'Imported Post', + content: 'Content' + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('posts'); + expect(result.imported.posts.imported).toBe(1); + }); + + it('should import pingResults successfully', async () => { + const pingId = generateId(); + const targetId = generateId(); + const importData = { + data: { + pingResults: [{ + _id: pingId, + targetId: targetId, + success: true, + responseTime: 100 + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('pingResults'); + expect(result.imported.pingResults.imported).toBe(1); + }); + + it('should import statistics successfully', async () => { + const statId = generateId(); + const targetId = generateId(); + const importData = { + data: { + statistics: [{ + _id: statId, + targetId: targetId, + date: new Date(), + totalPings: 100 + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('statistics'); + expect(result.imported.statistics.imported).toBe(1); + }); + + it('should import legacy ping_results format', async () => { + const targetId = generateId(); + const importData = { + data: { + ping_results: [{ + targetId: targetId, + success: 1, + responseTime: 100, + timestamp: new Date() + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('ping_results'); + expect(result.imported.ping_results.imported).toBe(1); + }); + + it('should import legacy daily_stats format', async () => { + const targetId = generateId(); + const importData = { + data: { + daily_stats: [{ + targetId: targetId, + date: new Date(), + totalPings: 100, + successfulPings: 95, + avgResponseTime: 50 + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('daily_stats'); + expect(result.imported.daily_stats.imported).toBe(1); + }); + + it('should import settings successfully', async () => { + const importData = { + data: { + adminSettings: { + _id: 'settings', + sessionDurationDays: 60 + }, + publicUISettings: { + _id: 'settings', + title: 'New Title' + } + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('adminSettings'); + expect(result.imported).toHaveProperty('publicUISettings'); + expect(result.imported.adminSettings.imported).toBe(1); + expect(result.imported.publicUISettings.imported).toBe(1); + }); + + it('should update settings when overwrite is true', async () => { + await mockDB.collection('adminSettings').insertOne({ + _id: 'settings', + sessionDurationDays: 30 + }); + + const importData = { + data: { + adminSettings: { + _id: 'settings', + sessionDurationDays: 60 + } + } + }; + + const result = await backupService.importData(importData, { overwrite: true }); + + expect(result.imported.adminSettings.updated).toBe(1); + + const updated = await mockDB.collection('adminSettings').findOne({ _id: 'settings' }); + expect(updated.sessionDurationDays).toBe(60); + }); + + it('should import favicons successfully', async () => { + const faviconId = generateId(); + const importData = { + data: { + favicons: [{ + _id: faviconId, + appUrl: 'https://example.com', + favicon: 'data:image/png;base64,...' + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported).toHaveProperty('favicons'); + expect(result.imported.favicons.imported).toBe(1); + }); + + it('should stringify object auth field when importing', async () => { + const targetId = generateId(); + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Test', + auth: { username: 'user', password: 'pass' } + }] + } + }; + + await backupService.importData(importData); + + const imported = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(typeof imported.auth).toBe('string'); + const parsed = JSON.parse(imported.auth); + expect(parsed.username).toBe('user'); + }); + + it('should stringify array quickCommands when importing', async () => { + const targetId = generateId(); + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Test', + quickCommands: ['cmd1', 'cmd2'] + }] + } + }; + + await backupService.importData(importData); + + const imported = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(typeof imported.quickCommands).toBe('string'); + const parsed = JSON.parse(imported.quickCommands); + expect(Array.isArray(parsed)).toBe(true); + expect(parsed[0]).toBe('cmd1'); + }); + + it('should throw error for invalid import data format', async () => { + const importData = { invalid: 'format' }; + + await expect(backupService.importData(importData)).rejects.toThrow('Invalid import data format'); + }); + + it('should handle errors gracefully and continue with other imports', async () => { + const targetId = generateId(); + const importData = { + data: { + targets: [{ + _id: targetId, + name: 'Valid Target' + }], + incidents: [{ + // Missing required _id - this will cause an error when trying to insert + title: 'Invalid Incident' + }] + } + }; + + const result = await backupService.importData(importData); + + // Targets should still be imported + expect(result.imported.targets.imported).toBe(1); + // Incidents import should either succeed (if _id is auto-generated) or have errors + // The mock will auto-generate _id, so it might succeed. Let's check that targets were imported + expect(result.imported.targets).toBeDefined(); + // If incidents failed, there should be errors, otherwise it should be imported + if (result.errors.length > 0) { + expect(result.errors.some(e => e.type === 'incidents')).toBe(true); + } else { + // If no errors, incidents should have been imported (with auto-generated _id) + expect(result.imported.incidents).toBeDefined(); + } + }); + + it('should skip duplicate pingResults', async () => { + const pingId = generateId(); + const targetId = generateId(); + + await mockDB.collection('pingResults').insertOne({ + _id: pingId, + targetId: targetId, + success: true + }); + + const importData = { + data: { + pingResults: [{ + _id: pingId, + targetId: targetId, + success: true + }] + } + }; + + const result = await backupService.importData(importData); + + expect(result.imported.pingResults.imported).toBe(0); + }); + + it('should handle round-trip export/import correctly', async () => { + // Create test data + const targetId = generateId(); + await mockDB.collection('targets').insertOne({ + _id: targetId, + name: 'Round Trip Test', + host: 'example.com', + protocol: 'HTTP', + port: 80, + auth: JSON.stringify({ username: 'user', password: 'pass' }), + quickCommands: JSON.stringify(['cmd1']) + }); + + // Export + const exported = await backupService.exportData({ monitors: true }); + + // Clear database + await mockDB.collection('targets').deleteOne({ _id: targetId }); + + // Import + const importResult = await backupService.importData(exported); + + expect(importResult.imported.targets.imported).toBe(1); + + // Verify data integrity + const imported = await mockDB.collection('targets').findOne({ _id: targetId }); + expect(imported.name).toBe('Round Trip Test'); + expect(imported.host).toBe('example.com'); + // Auth should be stringified after import + expect(typeof imported.auth).toBe('string'); + const parsedAuth = JSON.parse(imported.auth); + expect(parsedAuth.username).toBe('user'); + }); + }); +}); + diff --git a/__tests__/services/monitorService.test.js b/__tests__/services/monitorService.test.js new file mode 100644 index 0000000..9260b0e --- /dev/null +++ b/__tests__/services/monitorService.test.js @@ -0,0 +1,174 @@ +jest.useFakeTimers(); + +jest.mock('../../src/services/pingService', () => ({ + ping: jest.fn(), +})); + +jest.mock('../../src/services/notificationService', () => ({ + getMonitorDownDelayMinutes: jest.fn().mockResolvedValue(1), +})); + +jest.mock('../../src/config/prisma', () => ({ + getPrisma: () => ({ + adminSettings: { findUnique: jest.fn().mockResolvedValue({ debugLogging: false }) }, + pingResult: { create: jest.fn().mockResolvedValue({}) }, + statistic: { + findUnique: jest.fn().mockResolvedValue(null), + create: jest.fn().mockResolvedValue({}), + update: jest.fn().mockResolvedValue({}), + aggregate: jest.fn().mockResolvedValue({ _sum: { totalPings: 0, successfulPings: 0 } }), + }, + alert: { create: jest.fn().mockResolvedValue({}) }, + }), +})); + +jest.mock('../../src/services/eventDetectionService', () => ({ + evaluateRules: jest.fn().mockResolvedValue(undefined), +})); + +const pingService = require('../../src/services/pingService'); +const monitorService = require('../../src/services/monitorService'); + +const target = { + id: 'monitor-delay-test', + _id: 'monitor-delay-test', + name: 'Delay test', + host: 'example.test', + protocol: 'HTTPS', + interval: 60, + retries: 0, +}; + +function settle() { + return Promise.resolve().then(() => Promise.resolve()); +} + +describe('MonitorService sustained outage notifications', () => { + beforeEach(() => { + monitorService.stopAllMonitoring(); + monitorService.setNotificationDelayMinutes(1); + monitorService.handleTargetDown = jest.fn().mockResolvedValue({}); + monitorService.handleTargetUp = jest.fn().mockResolvedValue({}); + pingService.ping.mockReset(); + }); + + afterEach(() => { + monitorService.stopAllMonitoring(); + }); + + it('does not notify for an outage that recovers before the delay', async () => { + pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null }) + .mockResolvedValueOnce({ success: true, responseTime: 12 }); + + await monitorService.pingTarget(target); + await settle(); + jest.advanceTimersByTime(59 * 1000); + await monitorService.pingTarget(target); + jest.runOnlyPendingTimers(); + await settle(); + + expect(monitorService.handleTargetDown).not.toHaveBeenCalled(); + // Recovery is still recorded internally; only the external notification + // is suppressed because the outage did not reach the configured delay. + expect(monitorService.handleTargetUp).toHaveBeenCalledTimes(1); + expect(monitorService.handleTargetUp).toHaveBeenCalledWith( + target, + 12, + expect.any(Number), + false, + ); + expect(monitorService.getNotificationState(target.id).notificationSent).toBe(false); + }); + + it('sends one down notification after the configured delay and then one recovery notification', async () => { + pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null }) + .mockResolvedValueOnce({ success: true, responseTime: 18 }); + + await monitorService.pingTarget(target); + await settle(); + expect(monitorService.handleTargetDown).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(60 * 1000); + await settle(); + expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1); + + await monitorService.pingTarget(target); + jest.runOnlyPendingTimers(); + await settle(); + expect(monitorService.handleTargetUp).toHaveBeenCalledTimes(1); + expect(monitorService.handleTargetUp).toHaveBeenCalledWith( + target, + 18, + expect.any(Number), + true, + ); + }); + + it('uses the in-memory delay when the settings lookup fails', async () => { + const notificationService = require('../../src/services/notificationService'); + notificationService.getMonitorDownDelayMinutes.mockRejectedValueOnce(new Error('database unavailable')); + monitorService.setNotificationDelayMinutes(1); + pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null }); + + await monitorService.pingTarget(target); + await settle(); + jest.advanceTimersByTime(60 * 1000); + await settle(); + + expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1); + }); + + it('reschedules an active outage when the global delay changes', async () => { + const notificationService = require('../../src/services/notificationService'); + notificationService.getMonitorDownDelayMinutes.mockResolvedValue(1); + monitorService.setNotificationDelayMinutes(5); + pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null }); + + monitorService.startTargetMonitor({ ...target, interval: 3600 }); + await monitorService.pingTarget(target, monitorService.monitorGeneration.get(target.id)); + await settle(); + + jest.advanceTimersByTime(30 * 1000); + monitorService.setNotificationDelayMinutes(1); + await settle(); + jest.advanceTimersByTime(30 * 1000); + await settle(); + + expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1); + }); + + it('does not let an older settings lookup replace a newer delay', async () => { + const notificationService = require('../../src/services/notificationService'); + let resolveDelay; + notificationService.getMonitorDownDelayMinutes.mockReturnValueOnce(new Promise(resolve => { + resolveDelay = resolve; + })); + monitorService.setNotificationDelayMinutes(5); + pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null }); + + await monitorService.pingTarget(target); + await settle(); + monitorService.setNotificationDelayMinutes(1); + resolveDelay(5); + await settle(); + + expect(monitorService.notificationDelayMinutes).toBe(1); + }); + + it('ignores a ping result from a monitor generation that was restarted', async () => { + let resolvePing; + pingService.ping.mockReturnValueOnce(new Promise(resolve => { resolvePing = resolve; })); + + monitorService.startTargetMonitor(target); + const oldGeneration = monitorService.monitorGeneration.get(target.id); + const oldPing = monitorService.pingTarget(target, oldGeneration); + monitorService.startTargetMonitor(target); + + resolvePing({ success: false, responseTime: null }); + await oldPing; + await settle(); + + expect(monitorService.getTargetStatus(target.id)).toBe('unknown'); + expect(monitorService.getNotificationState(target.id).downSince).toBeNull(); + }); +}); diff --git a/__tests__/services/pingService.test.js b/__tests__/services/pingService.test.js new file mode 100644 index 0000000..2b4d7f2 --- /dev/null +++ b/__tests__/services/pingService.test.js @@ -0,0 +1,230 @@ +const pingService = require('../../src/services/pingService'); +const axios = require('axios'); +const tcpPing = require('tcp-ping'); + +jest.mock('axios'); +jest.mock('tcp-ping'); +jest.mock('child_process'); + +describe('PingService', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('ping method - protocol validation', () => { + it('should return error for unknown protocol', async () => { + const target = { + host: 'example.com', + protocol: 'UNKNOWN', + port: 80, + }; + + const result = await pingService.ping(target); + + expect(result.success).toBe(false); + expect(result.error).toContain('Unknown protocol'); + }); + + it('should handle case-insensitive protocol', async () => { + const target = { + host: 'example.com', + protocol: 'tcp', + port: 80, + }; + + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(null, true); + }); + + const result = await pingService.ping(target); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('TCP'); + }); + }); + + describe('pingTCP method', () => { + it('should successfully ping TCP host', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(null, true); + }); + + const result = await pingService.pingTCP('example.com', 80, Date.now()); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('TCP'); + expect(result.responseTime).toBeGreaterThanOrEqual(0); + }); + + it('should handle TCP connection failure', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(new Error('Connection refused'), false); + }); + + const result = await pingService.pingTCP('example.com', 80, Date.now()); + + expect(result.success).toBe(false); + expect(result.error).toContain('Connection refused'); + expect(result.protocol).toBe('TCP'); + }); + + it('should use default port 80 for TCP', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(null, true); + }); + + const result = await pingService.pingTCP('example.com', 80, Date.now()); + + expect(tcpPing.probe).toHaveBeenCalledWith('example.com', 80, expect.any(Function)); + }); + }); + + describe('pingUDP method', () => { + it('should successfully send UDP ping', async () => { + const result = await pingService.pingUDP('example.com', 53, Date.now()); + + // UDP is expected to timeout or fail without a listening server + expect(result.protocol).toBe('UDP'); + expect(result.responseTime).toBeGreaterThanOrEqual(0); + }); + + it('should handle UDP timeout', async () => { + const result = await pingService.pingUDP('example.com', 53, Date.now()); + + // Without a real server, UDP will timeout + expect(result).toHaveProperty('responseTime'); + expect(result).toHaveProperty('protocol', 'UDP'); + }); + + it('should use default port 53 for UDP', async () => { + const result = await pingService.pingUDP('example.com', 53, Date.now()); + + expect(result).toHaveProperty('protocol', 'UDP'); + }); + }); + + describe('pingHTTP method', () => { + it('should successfully ping HTTP endpoint', async () => { + axios.mockResolvedValue({ status: 200 }); + + const result = await pingService.pingHTTP('http://example.com/', Date.now()); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('HTTP'); + expect(result.responseTime).toBeGreaterThanOrEqual(0); + }); + + it('should handle HTTP timeout', async () => { + axios.mockRejectedValue(new Error('Request timeout')); + + const result = await pingService.pingHTTP('http://example.com/', Date.now()); + + expect(result.success).toBe(false); + expect(result.error).toContain('Request timeout'); + }); + + it('should use port 443 for HTTPS by default', async () => { + axios.mockResolvedValue({ status: 200 }); + + const result = await pingService.pingHTTP('https://example.com/', Date.now()); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('HTTPS'); + }); + + it('should use custom port in HTTP URL', async () => { + axios.mockResolvedValue({ status: 200 }); + + const result = await pingService.pingHTTP('http://example.com:8080/', Date.now()); + + expect(result.success).toBe(true); + }); + }); + + describe('ping routing', () => { + it('should route TCP protocol correctly', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(null, true); + }); + + const target = { + host: 'example.com', + protocol: 'TCP', + port: 80, + }; + + const result = await pingService.ping(target); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('TCP'); + }); + + it('should route HTTP protocol correctly', async () => { + axios.mockResolvedValue({ status: 200 }); + + const target = { + host: 'example.com', + protocol: 'HTTP', + port: 80, + path: '/', + }; + + const result = await pingService.ping(target); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('HTTP'); + }); + + it('should route HTTPS protocol correctly', async () => { + axios.mockResolvedValue({ status: 200 }); + + const target = { + host: 'example.com', + protocol: 'HTTPS', + port: 443, + path: '/', + }; + + const result = await pingService.ping(target); + + expect(result.success).toBe(true); + expect(result.protocol).toBe('HTTPS'); + }); + }); + + describe('response structure', () => { + it('should always include success, responseTime, and protocol', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(null, true); + }); + + const result = await pingService.pingTCP('example.com', 80, Date.now()); + + expect(result).toHaveProperty('success'); + expect(result).toHaveProperty('responseTime'); + expect(result).toHaveProperty('protocol'); + }); + + it('should include error message when ping fails', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + callback(new Error('Network error'), false); + }); + + const result = await pingService.pingTCP('example.com', 80, Date.now()); + + expect(result).toHaveProperty('error'); + expect(typeof result.error).toBe('string'); + }); + + it('should measure response time accurately', async () => { + tcpPing.probe.mockImplementation((host, port, callback) => { + setTimeout(() => callback(null, true), 10); + }); + + const startTime = Date.now(); + const result = await pingService.pingTCP('example.com', 80, startTime); + + expect(result.responseTime).toBeGreaterThanOrEqual(10); + }); + }); +}); diff --git a/ecosystem.config.js b/ecosystem.config.js new file mode 100644 index 0000000..6494683 --- /dev/null +++ b/ecosystem.config.js @@ -0,0 +1,31 @@ +module.exports = { + apps: [ + { + name: 'localping', + script: './src/app.js', + args: '--mode all', + instances: 1, + exec_mode: 'fork', + env: { + NODE_ENV: 'production', + API_PORT: 8000, + ADMIN_PORT: 8000, + PUBLIC_PORT: 8000, + }, + error_file: './logs/error.log', + out_file: './logs/out.log', + log_date_format: 'YYYY-MM-DD HH:mm:ss Z', + merge_logs: true, + autorestart: true, + ignore_watch: [ + 'logs', + 'node_modules', + 'data', + 'prisma', + 'scripts', + '.git', + ], + max_memory_restart: '512M', + }, + ], +}; diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..97e8d3c --- /dev/null +++ b/install.sh @@ -0,0 +1,420 @@ +#!/bin/bash + +set -e + +echo "πŸš€ LocalPing Installation Script" +echo "==================================" + +# Check for the privileges required to install packages and manage systemd. +if [[ $EUID -ne 0 ]]; then + echo "❌ This script must be run as root" + exit 1 +fi + +# Parse arguments +REPO_URL="${1:-https://github.com/YOUR-ORG/localping.git}" +BRANCH="${2:-main}" +INSTALL_DIR="${3:-/opt/localping}" +SKIP_UPDATE="${4:-false}" + +echo "πŸ“‹ Installation Configuration:" +echo " Repository: $REPO_URL" +echo " Branch: $BRANCH" +echo " Install Path: $INSTALL_DIR" +echo "" + +# Detect if already installed +IS_UPDATE=false +if [ -d "$INSTALL_DIR" ]; then + if [ -f "$INSTALL_DIR/.env" ] && [ -f "$INSTALL_DIR/package.json" ]; then + echo "βœ“ Existing LocalPing installation detected at $INSTALL_DIR" + echo "" + echo "What will be updated:" + echo " β€’ Source code (latest version from $BRANCH branch)" + echo " β€’ Dependencies (npm packages)" + echo " β€’ Systemd service configuration" + echo "" + echo "What will be preserved:" + echo " β€’ PostgreSQL database" + echo " β€’ Configuration (.env file)" + echo " β€’ Admin credentials" + echo "" + + # Only ask for confirmation if running in interactive terminal and not skipping confirmation + if [ "$SKIP_UPDATE" != "true" ] && [ -t 0 ]; then + read -p "Continue with update? (y/n) " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + echo "❌ Update cancelled." + exit 0 + fi + fi + IS_UPDATE=true + else + echo "⚠️ Directory exists at $INSTALL_DIR but is not a valid LocalPing installation" + echo "❌ Please remove the directory or use a different path" + exit 1 + fi +fi + +echo "πŸ“¦ Installing system dependencies..." +apt-get update -qq 2>/dev/null || apt-get update + +# Install minimal dependencies +apt-get install -y -qq \ + curl \ + git \ + build-essential \ + python3 \ + libnotify-bin \ + 2>/dev/null || apt-get install -y \ + curl \ + git \ + build-essential \ + python3 \ + libnotify-bin + +# Install Node.js if not present +if ! command -v node &> /dev/null; then + echo "πŸ“¦ Installing Node.js v20..." + curl -fsSL https://deb.nodesource.com/setup_20.x | bash - 2>/dev/null + apt-get install -y -qq nodejs 2>/dev/null || apt-get install -y nodejs +fi + +# Install git if not present (shouldn't happen but just in case) +if ! command -v git &> /dev/null; then + echo "πŸ“¦ Installing git..." + apt-get install -y -qq git 2>/dev/null || apt-get install -y git +fi + +echo "βœ… System dependencies installed" + +# Clone or update repository +if [ "$IS_UPDATE" = false ]; then + echo "πŸ“₯ Cloning LocalPing repository..." + mkdir -p "$(dirname "$INSTALL_DIR")" + git clone --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR" +else + echo "πŸ”„ Updating LocalPing repository..." + cd "$INSTALL_DIR" + # Fetch the requested branch and make the working tree exactly match it. + # `checkout -B` only changes tracked files, so the installation's .env, + # data, and logs remain untouched. + git fetch --prune origin "$BRANCH" + git checkout -B "$BRANCH" "origin/$BRANCH" +fi + +cd "$INSTALL_DIR" + +# Validate required files exist +if [ ! -f ".env.example" ]; then + echo "❌ .env.example not found at $INSTALL_DIR" + echo "The repository may be corrupted. Please try again." + exit 1 +fi + +echo "πŸ“₯ Installing npm dependencies..." +npm install --silent 2>/dev/null || npm install + +echo "πŸ“ Creating data directory..." +mkdir -p "$INSTALL_DIR/data" + +echo "πŸ—„οΈ Setting up PostgreSQL..." +# Install PostgreSQL if not present +if ! command -v psql &> /dev/null; then + echo "πŸ“¦ Installing PostgreSQL..." + apt-get install -y -qq postgresql postgresql-contrib 2>/dev/null || apt-get install -y postgresql postgresql-contrib + systemctl enable postgresql + systemctl start postgresql + echo "βœ… PostgreSQL installed" +else + echo "βœ“ PostgreSQL already installed" + # Ensure PostgreSQL is running + systemctl start postgresql 2>/dev/null || true +fi + +# Wait for PostgreSQL to be ready +sleep 2 + +# Reuse database settings from an existing installation. This prevents an +# update from generating a new password that does not match the existing +# PostgreSQL role. +EXISTING_DATABASE_URL="" +if [ -f ".env" ]; then + # .env is the installation's own configuration file and is needed here so + # Prisma and the service use the same credentials as the database setup. + set -a + # shellcheck disable=SC1091 + . ./.env + set +a + EXISTING_DATABASE_URL="${DATABASE_URL:-}" +fi + +DB_HOST="${DB_HOST:-localhost}" +DB_PORT="${DB_PORT:-5432}" +DB_NAME="${DB_NAME:-localping}" +DB_USER="${DB_USER:-localping}" +GENERATED_DB_PASSWORD=false +if [ -z "${DB_PASSWORD:-}" ]; then + DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24) + GENERATED_DB_PASSWORD=true +fi + +case "$DB_NAME" in + ""|*[!A-Za-z0-9_]* ) echo "❌ DB_NAME may only contain letters, numbers, and underscores"; exit 1 ;; +esac +case "$DB_USER" in + ""|*[!A-Za-z0-9_]* ) echo "❌ DB_USER may only contain letters, numbers, and underscores"; exit 1 ;; +esac + +run_as_postgres() { + if ! command -v runuser >/dev/null 2>&1; then + echo "❌ runuser is required to configure PostgreSQL as the postgres user" + exit 1 + fi + runuser -u postgres -- "$@" +} + +# Create database and user if they don't exist +echo "πŸ”§ Configuring PostgreSQL database..." +if ! run_as_postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q '^1$'; then + run_as_postgres psql -v ON_ERROR_STOP=1 -v db_password="$DB_PASSWORD" -c "CREATE USER \"$DB_USER\" WITH PASSWORD :'db_password';" +elif [ "$GENERATED_DB_PASSWORD" = true ] && [ -z "$EXISTING_DATABASE_URL" ]; then + # A partially completed installation may have a role but no saved + # connection URL. Make the generated credentials usable before saving them. + run_as_postgres psql -v ON_ERROR_STOP=1 -v db_password="$DB_PASSWORD" -c "ALTER ROLE \"$DB_USER\" WITH PASSWORD :'db_password';" +fi + +if ! run_as_postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q '^1$'; then + run_as_postgres psql -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$DB_NAME\" OWNER \"$DB_USER\";" +fi +run_as_postgres psql -v ON_ERROR_STOP=1 -c "GRANT ALL PRIVILEGES ON DATABASE \"$DB_NAME\" TO \"$DB_USER\";" + +# Configure PostgreSQL for local-only access (security) +PG_MAJOR_VERSION=$(run_as_postgres psql -tAc "SHOW server_version;" | xargs | cut -d. -f1) +PG_HBA_FILE="/etc/postgresql/$PG_MAJOR_VERSION/main/pg_hba.conf" + +if [ -f "$PG_HBA_FILE" ]; then + # Ensure local connections use md5 (password) authentication + if ! grep -q "^local.*$DB_NAME.*$DB_USER.*md5" "$PG_HBA_FILE"; then + # Add local connection rule if it doesn't exist + printf 'local %s %s md5\n' "$DB_NAME" "$DB_USER" >> "$PG_HBA_FILE" + fi + # Ensure host connections are restricted to localhost only + if ! grep -q "^host.*$DB_NAME.*$DB_USER.*127.0.0.1/32.*md5" "$PG_HBA_FILE"; then + printf 'host %s %s 127.0.0.1/32 md5\n' "$DB_NAME" "$DB_USER" >> "$PG_HBA_FILE" + fi + # Reload PostgreSQL configuration + systemctl reload postgresql 2>/dev/null || run_as_postgres pg_ctl reload -D "/var/lib/postgresql/$PG_MAJOR_VERSION/main" 2>/dev/null || true +fi + +echo "βœ… PostgreSQL database configured" + +echo "πŸ”§ Setting up environment file..." +if [ ! -f ".env" ]; then + # Generate secure random strings + SESSION_SECRET=$(openssl rand -base64 32) + ADMIN_API_KEY=$(openssl rand -hex 16) + + cat > .env << EOF +# Server Configuration +API_PORT=8000 +NODE_ENV=production +SESSION_SECRET=$SESSION_SECRET + +# Database Configuration +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=$DB_NAME +DB_USER=$DB_USER +DB_PASSWORD=$DB_PASSWORD +DATABASE_URL=postgresql://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME + +# Notification Settings +NOTIFICATION_ENABLED=true +NOTIFICATION_METHOD=dbus + +# Monitoring +PING_INTERVAL=60 +ALERT_COOLDOWN=300 + +# API Authentication +ADMIN_API_KEY=$ADMIN_API_KEY + +# Admin Credentials (set during first-time setup) +# ADMIN_PASSWORD= +# ADMIN_USERNAME= +EOF + echo "βœ… .env file created with secure values" +else + if [ "$IS_UPDATE" = true ]; then + echo "βœ“ Preserving existing .env file" + # Add database settings required by Prisma to older installations + # without replacing any existing application configuration. + if ! grep -q "^DB_HOST=" .env; then + { + echo "" + echo "# Database Configuration" + echo "DB_HOST=$DB_HOST" + echo "DB_PORT=$DB_PORT" + echo "DB_NAME=$DB_NAME" + echo "DB_USER=$DB_USER" + echo "DB_PASSWORD=$DB_PASSWORD" + } >> .env + echo "βœ… Added database configuration to .env" + else + grep -q "^DB_PORT=" .env || echo "DB_PORT=$DB_PORT" >> .env + grep -q "^DB_NAME=" .env || echo "DB_NAME=$DB_NAME" >> .env + grep -q "^DB_USER=" .env || echo "DB_USER=$DB_USER" >> .env + grep -q "^DB_PASSWORD=" .env || echo "DB_PASSWORD=$DB_PASSWORD" >> .env + fi + if [ -z "$EXISTING_DATABASE_URL" ] && ! grep -q "^DATABASE_URL=" .env; then + echo "DATABASE_URL=postgresql://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME" >> .env + echo "βœ… Added DATABASE_URL for Prisma to .env" + fi + else + echo "⚠️ .env already exists, skipping creation" + fi +fi + +echo "πŸ”„ Syncing database schema with Prisma..." +npx prisma generate +npx prisma db push --skip-generate + +echo "πŸ” Setting ICMP capabilities for Node.js..." +NODE_PATH=$(which node) +setcap cap_net_raw=ep "$NODE_PATH" 2>/dev/null || true + +# Run the service as the invoking user when available; root is the fallback. +SERVICE_USER="${SUDO_USER:-root}" +SERVICE_NAME="localping" + +echo "πŸ› οΈ Creating systemd service..." + +# Get Node.js path +NODE_BIN=$(which node) + +# Create systemd service file to run Node.js directly (production-optimized) +cat > "/etc/systemd/system/${SERVICE_NAME}.service" << SYSTEMD_EOF +[Unit] +Description=LocalPing - System Uptime Monitor +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=$SERVICE_USER +WorkingDirectory=$INSTALL_DIR +Environment="PATH=/usr/local/bin:/usr/bin:/bin" +Environment="NODE_ENV=production" +EnvironmentFile=-$INSTALL_DIR/.env + +# Start Node.js app directly +ExecStart=$NODE_BIN $INSTALL_DIR/src/app.js + +# Restart automatically on failure +Restart=on-failure +RestartSec=10 + +# Grant ICMP permissions for ping functionality +AmbientCapabilities=CAP_NET_RAW +CapabilityBoundingSet=CAP_NET_RAW + +# Security settings +ProtectHome=true +NoNewPrivileges=true +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes + +# Process management +StandardOutput=journal +StandardError=journal +SyslogIdentifier=$SERVICE_NAME + +[Install] +WantedBy=multi-user.target +SYSTEMD_EOF + +# Set permissions +chown root:root "/etc/systemd/system/${SERVICE_NAME}.service" +chmod 644 "/etc/systemd/system/${SERVICE_NAME}.service" + +# Reload systemd +systemctl daemon-reload + +# Enable and start/restart the service +echo "πŸš€ Starting LocalPing service..." +systemctl enable "$SERVICE_NAME" +systemctl restart "$SERVICE_NAME" + +# Wait for service to start +sleep 3 + +if ! systemctl is-active --quiet "$SERVICE_NAME"; then + echo "❌ LocalPing failed to start after the update" + systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -n 40 || true + exit 1 +fi + +echo "βœ… Systemd service configured" +echo "" + +# Show status +echo "πŸ“Š Service Status:" +systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -n 20 || true + +echo "" +if [ "$IS_UPDATE" = true ]; then + echo "βœ… Update complete!" + echo "" + echo "What was updated:" + echo " βœ“ Source code to latest version" + echo " βœ“ Dependencies (npm packages)" + echo " βœ“ Systemd service configuration" + echo "" + echo "What was preserved:" + echo " βœ“ PostgreSQL database" + echo " βœ“ Configuration (.env file)" + echo " βœ“ Admin credentials and monitors" +else + echo "βœ… Installation complete!" + echo "" +fi + +# Get the IPv4 address +IP_ADDR=$(hostname -I | awk '{print $1}') +if [ -z "$IP_ADDR" ]; then + IP_ADDR="localhost" +fi + +echo "πŸ“Š Access LocalPing:" +echo " Public Page: http://$IP_ADDR:8000" +echo " API: http://$IP_ADDR:8000/api" +echo "" + +if [ "$IS_UPDATE" = false ]; then + echo "πŸ”§ First Time Setup:" + echo " 1. Visit http://$IP_ADDR:8000/setup to complete configuration" + echo " 2. Create admin credentials and configure gateway IP" + echo " 3. You'll be redirected to login at http://$IP_ADDR:8000/admin/login" + echo " 4. Login to access the admin panel" + echo "" +else + echo "πŸ”„ Service has been restarted with the latest code" + echo " Login at http://$IP_ADDR:8000/admin/login" + echo "" +fi +echo "" +echo "πŸ“– Useful Commands:" +echo " View logs: journalctl -u $SERVICE_NAME -f" +echo " Service status: systemctl status $SERVICE_NAME" +echo " Start service: systemctl start $SERVICE_NAME" +echo " Stop service: systemctl stop $SERVICE_NAME" +echo " Restart service: systemctl restart $SERVICE_NAME" +echo " Install directory: $INSTALL_DIR" +echo "" +echo "ℹ️ The service will auto-start on system boot." +echo "ℹ️ Environment file located at: $INSTALL_DIR/.env" +echo "" diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..c55ef77 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,19 @@ +module.exports = { + testEnvironment: 'node', + testMatch: ['**/__tests__/**/*.test.js', '**/*.test.js'], + collectCoverageFrom: [ + 'src/**/*.js', + '!src/app.js', + '!src/cli/**', + '!src/electron/**', + '!src/public/**', + ], + coveragePathIgnorePatterns: [ + '/node_modules/', + '/tests/', + ], + transformIgnorePatterns: [ + 'node_modules/(?!(default-gateway)/)', + ], + testTimeout: 10000, +}; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..6197793 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,9090 @@ +{ + "name": "localping", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "localping", + "version": "0.1.0", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@prisma/client": "^6.8.2", + "axios": "^1.13.2", + "better-sqlite3": "^12.4.5", + "chalk": "^5.6.2", + "cors": "^2.8.5", + "default-gateway": "^7.2.2", + "dotenv": "^17.2.3", + "ejs": "^3.1.10", + "electron-is-dev": "^3.0.1", + "express": "^5.1.0", + "express-session": "^1.17.3", + "express-ws": "^5.0.2", + "inquirer": "^13.0.1", + "isomorphic-form-data": "^2.0.0", + "nodemon": "^3.1.11", + "pg": "^8.13.1", + "pm2": "^6.0.13", + "shell-escape": "^0.2.0", + "tcp-ping": "^0.1.1", + "uuid": "^13.0.0", + "yargs": "^18.0.0" + }, + "devDependencies": { + "@babel/preset-env": "^7.28.5", + "@babel/preset-typescript": "^7.28.5", + "jest": "^29.7.0", + "prisma": "^6.8.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-module-transforms": "^7.28.3", + "@babel/helpers": "^7.28.4", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.27.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.27.3" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.27.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.27.2", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/yallist": { + "version": "3.1.1", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-member-expression-to-functions": "^7.28.5", + "@babel/helper-optimise-call-expression": "^7.27.1", + "@babel/helper-replace-supers": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", + "@babel/traverse": "^7.28.5", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "regexpu-core": "^6.3.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-define-polyfill-provider": { + "version": "0.6.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-plugin-utils": "^7.27.1", + "debug": "^4.4.1", + "lodash.debounce": "^4.0.8", + "resolve": "^1.22.10" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.27.1", + "@babel/helper-validator-identifier": "^7.27.1", + "@babel/traverse": "^7.28.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.1", + "@babel/helper-wrap-function": "^7.27.1", + "@babel/traverse": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-member-expression-to-functions": "^7.27.1", + "@babel/helper-optimise-call-expression": "^7.27.1", + "@babel/traverse": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-wrap-function": { + "version": "7.28.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.3", + "@babel/types": "^7.28.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.28.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/traverse": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-class-field-initializer-scope": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", + "@babel/plugin-transform-optional-chaining": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.13.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { + "version": "7.28.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/traverse": "^7.28.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-assertions": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-unicode-sets-regex": { + "version": "7.18.6", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.18.6", + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-generator-functions": { + "version": "7.28.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-remap-async-to-generator": "^7.27.1", + "@babel/traverse": "^7.28.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-remap-async-to-generator": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-properties": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-static-block": { + "version": "7.28.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.28.3", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0" + } + }, + "node_modules/@babel/plugin-transform-classes": { + "version": "7.28.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-globals": "^7.28.0", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-replace-supers": "^7.27.1", + "@babel/traverse": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/template": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/traverse": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-dynamic-import": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-explicit-resource-management": { + "version": "7.28.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/plugin-transform-destructuring": "^7.28.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-export-namespace-from": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-for-of": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-function-name": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/traverse": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-json-strings": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-literals": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-logical-assignment-operators": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.28.3", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-new-target": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-numeric-separator": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-rest-spread": { + "version": "7.28.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/plugin-transform-destructuring": "^7.28.0", + "@babel/plugin-transform-parameters": "^7.27.7", + "@babel/traverse": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-super": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-replace-supers": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-catch-binding": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-chaining": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-parameters": { + "version": "7.27.7", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-methods": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-property-in-object": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.1", + "@babel/helper-create-class-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-property-literals": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regenerator": { + "version": "7.28.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regexp-modifiers": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-spread": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-template-literals": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typeof-symbol": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-create-class-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", + "@babel/plugin-syntax-typescript": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-escapes": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-property-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-sets-regex": { + "version": "7.27.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.27.1", + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/preset-env": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.5", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-validator-option": "^7.27.1", + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.28.5", + "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^7.27.1", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.27.1", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.27.1", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.28.3", + "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", + "@babel/plugin-syntax-import-assertions": "^7.27.1", + "@babel/plugin-syntax-import-attributes": "^7.27.1", + "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", + "@babel/plugin-transform-arrow-functions": "^7.27.1", + "@babel/plugin-transform-async-generator-functions": "^7.28.0", + "@babel/plugin-transform-async-to-generator": "^7.27.1", + "@babel/plugin-transform-block-scoped-functions": "^7.27.1", + "@babel/plugin-transform-block-scoping": "^7.28.5", + "@babel/plugin-transform-class-properties": "^7.27.1", + "@babel/plugin-transform-class-static-block": "^7.28.3", + "@babel/plugin-transform-classes": "^7.28.4", + "@babel/plugin-transform-computed-properties": "^7.27.1", + "@babel/plugin-transform-destructuring": "^7.28.5", + "@babel/plugin-transform-dotall-regex": "^7.27.1", + "@babel/plugin-transform-duplicate-keys": "^7.27.1", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-dynamic-import": "^7.27.1", + "@babel/plugin-transform-explicit-resource-management": "^7.28.0", + "@babel/plugin-transform-exponentiation-operator": "^7.28.5", + "@babel/plugin-transform-export-namespace-from": "^7.27.1", + "@babel/plugin-transform-for-of": "^7.27.1", + "@babel/plugin-transform-function-name": "^7.27.1", + "@babel/plugin-transform-json-strings": "^7.27.1", + "@babel/plugin-transform-literals": "^7.27.1", + "@babel/plugin-transform-logical-assignment-operators": "^7.28.5", + "@babel/plugin-transform-member-expression-literals": "^7.27.1", + "@babel/plugin-transform-modules-amd": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.27.1", + "@babel/plugin-transform-modules-systemjs": "^7.28.5", + "@babel/plugin-transform-modules-umd": "^7.27.1", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-new-target": "^7.27.1", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.27.1", + "@babel/plugin-transform-numeric-separator": "^7.27.1", + "@babel/plugin-transform-object-rest-spread": "^7.28.4", + "@babel/plugin-transform-object-super": "^7.27.1", + "@babel/plugin-transform-optional-catch-binding": "^7.27.1", + "@babel/plugin-transform-optional-chaining": "^7.28.5", + "@babel/plugin-transform-parameters": "^7.27.7", + "@babel/plugin-transform-private-methods": "^7.27.1", + "@babel/plugin-transform-private-property-in-object": "^7.27.1", + "@babel/plugin-transform-property-literals": "^7.27.1", + "@babel/plugin-transform-regenerator": "^7.28.4", + "@babel/plugin-transform-regexp-modifiers": "^7.27.1", + "@babel/plugin-transform-reserved-words": "^7.27.1", + "@babel/plugin-transform-shorthand-properties": "^7.27.1", + "@babel/plugin-transform-spread": "^7.27.1", + "@babel/plugin-transform-sticky-regex": "^7.27.1", + "@babel/plugin-transform-template-literals": "^7.27.1", + "@babel/plugin-transform-typeof-symbol": "^7.27.1", + "@babel/plugin-transform-unicode-escapes": "^7.27.1", + "@babel/plugin-transform-unicode-property-regex": "^7.27.1", + "@babel/plugin-transform-unicode-regex": "^7.27.1", + "@babel/plugin-transform-unicode-sets-regex": "^7.27.1", + "@babel/preset-modules": "0.1.6-no-external-plugins", + "babel-plugin-polyfill-corejs2": "^0.4.14", + "babel-plugin-polyfill-corejs3": "^0.13.0", + "babel-plugin-polyfill-regenerator": "^0.6.5", + "core-js-compat": "^3.43.0", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-env/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/preset-modules": { + "version": "0.1.6-no-external-plugins", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/preset-typescript": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-validator-option": "^7.27.1", + "@babel/plugin-syntax-jsx": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.27.1", + "@babel/plugin-transform-typescript": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.27.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/parser": "^7.27.2", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.28.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.5", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "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", + "dev": true, + "license": "MIT" + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.1", + "@inquirer/core": "^11.0.1", + "@inquirer/figures": "^2.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "11.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.1", + "@inquirer/figures": "^2.0.1", + "@inquirer/type": "^4.0.1", + "cli-width": "^4.1.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0", + "wrap-ansi": "^9.0.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core/node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@inquirer/editor": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/external-editor": "^2.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor/node_modules/iconv-lite": { + "version": "0.7.0", + "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/@inquirer/figures": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.1", + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "8.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.0.1", + "@inquirer/confirm": "^6.0.1", + "@inquirer/editor": "^5.0.1", + "@inquirer/expand": "^5.0.1", + "@inquirer/input": "^5.0.1", + "@inquirer/number": "^4.0.1", + "@inquirer/password": "^5.0.1", + "@inquirer/rawlist": "^5.0.1", + "@inquirer/search": "^4.0.1", + "@inquirer/select": "^5.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.0.1", + "@inquirer/figures": "^2.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.1", + "@inquirer/core": "^11.0.1", + "@inquirer/figures": "^2.0.1", + "@inquirer/type": "^4.0.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.0.1", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.14.2", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/sprintf-js": { + "version": "1.0.3", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/console/node_modules/ansi-styles": { + "version": "4.3.0", + "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/@jest/console/node_modules/chalk": { + "version": "4.1.2", + "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/@jest/console/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/core": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/core/node_modules/ansi-regex": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/core/node_modules/ansi-styles": { + "version": "4.3.0", + "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/@jest/core/node_modules/chalk": { + "version": "4.1.2", + "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/@jest/core/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/core/node_modules/strip-ansi": { + "version": "6.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/core/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/environment": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/reporters/node_modules/ansi-regex": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/ansi-styles": { + "version": "4.3.0", + "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/@jest/reporters/node_modules/chalk": { + "version": "4.1.2", + "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/@jest/reporters/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/strip-ansi": { + "version": "6.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform/node_modules/ansi-styles": { + "version": "4.3.0", + "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/@jest/transform/node_modules/chalk": { + "version": "4.1.2", + "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/@jest/transform/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/transform/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types/node_modules/ansi-styles": { + "version": "4.3.0", + "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/@jest/types/node_modules/chalk": { + "version": "4.1.2", + "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/@jest/types/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/types/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@pm2/agent": { + "version": "2.1.1", + "license": "AGPL-3.0", + "dependencies": { + "async": "~3.2.0", + "chalk": "~3.0.0", + "dayjs": "~1.8.24", + "debug": "~4.3.1", + "eventemitter2": "~5.0.1", + "fast-json-patch": "^3.1.0", + "fclone": "~1.0.11", + "pm2-axon": "~4.0.1", + "pm2-axon-rpc": "~0.7.0", + "proxy-agent": "~6.4.0", + "semver": "~7.5.0", + "ws": "~7.5.10" + } + }, + "node_modules/@pm2/agent/node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@pm2/agent/node_modules/chalk": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@pm2/agent/node_modules/dayjs": { + "version": "1.8.36", + "license": "MIT" + }, + "node_modules/@pm2/agent/node_modules/debug": { + "version": "4.3.7", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@pm2/agent/node_modules/has-flag": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@pm2/agent/node_modules/lru-cache": { + "version": "6.0.0", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@pm2/agent/node_modules/semver": { + "version": "7.5.4", + "license": "ISC", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@pm2/agent/node_modules/supports-color": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@pm2/blessed": { + "version": "0.1.81", + "license": "MIT", + "bin": { + "blessed": "bin/tput.js" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/@pm2/io": { + "version": "6.1.0", + "license": "Apache-2", + "dependencies": { + "async": "~2.6.1", + "debug": "~4.3.1", + "eventemitter2": "^6.3.1", + "require-in-the-middle": "^5.0.0", + "semver": "~7.5.4", + "shimmer": "^1.2.0", + "signal-exit": "^3.0.3", + "tslib": "1.9.3" + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/@pm2/io/node_modules/async": { + "version": "2.6.4", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/@pm2/io/node_modules/debug": { + "version": "4.3.7", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@pm2/io/node_modules/eventemitter2": { + "version": "6.4.9", + "license": "MIT" + }, + "node_modules/@pm2/io/node_modules/lru-cache": { + "version": "6.0.0", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@pm2/io/node_modules/semver": { + "version": "7.5.4", + "license": "ISC", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@pm2/js-api": { + "version": "0.8.0", + "license": "Apache-2", + "dependencies": { + "async": "^2.6.3", + "debug": "~4.3.1", + "eventemitter2": "^6.3.1", + "extrareqp2": "^1.0.0", + "ws": "^7.0.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/@pm2/js-api/node_modules/async": { + "version": "2.6.4", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/@pm2/js-api/node_modules/debug": { + "version": "4.3.7", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@pm2/js-api/node_modules/eventemitter2": { + "version": "6.4.9", + "license": "MIT" + }, + "node_modules/@pm2/pm2-version-check": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@pm2/pm2-version-check/-/pm2-version-check-1.0.4.tgz", + "integrity": "sha512-SXsM27SGH3yTWKc2fKR4SYNxsmnvuBQ9dd6QHtEWmiZ/VqaOYPAIlS8+vMcn27YLtAEBGvNRSh3TPNvtjZgfqA==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.1" + } + }, + "node_modules/@prisma/client": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.19.0.tgz", + "integrity": "sha512-QXFT+N/bva/QI2qoXmjBzL7D6aliPffIwP+81AdTGq0FXDoLxLkWivGMawG8iM5B9BKfxLIXxfWWAF6wbuJU6g==", + "hasInstallScript": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "prisma": "*", + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@prisma/config": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.19.0.tgz", + "integrity": "sha512-zwCayme+NzI/WfrvFEtkFhhOaZb/hI+X8TTjzjJ252VbPxAl2hWHK5NMczmnG9sXck2lsXrxIZuK524E25UNmg==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "c12": "3.1.0", + "deepmerge-ts": "7.1.5", + "effect": "3.18.4", + "empathic": "2.0.0" + } + }, + "node_modules/@prisma/debug": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.19.0.tgz", + "integrity": "sha512-8hAdGG7JmxrzFcTzXZajlQCidX0XNkMJkpqtfbLV54wC6LSSX6Vni25W/G+nAANwLnZ2TmwkfIuWetA7jJxJFA==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.19.0.tgz", + "integrity": "sha512-pMRJ+1S6NVdXoB8QJAPIGpKZevFjxhKt0paCkRDTZiczKb7F4yTgRP8M4JdVkpQwmaD4EoJf6qA+p61godDokw==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0", + "@prisma/engines-version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "@prisma/fetch-engine": "6.19.0", + "@prisma/get-platform": "6.19.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773.tgz", + "integrity": "sha512-gV7uOBQfAFlWDvPJdQxMT1aSRur3a0EkU/6cfbAC5isV67tKDWUrPauyaHNpB+wN1ebM4A9jn/f4gH+3iHSYSQ==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.19.0.tgz", + "integrity": "sha512-OOx2Lda0DGrZ1rodADT06ZGqHzr7HY7LNMaFE2Vp8dp146uJld58sRuasdX0OiwpHgl8SqDTUKHNUyzEq7pDdQ==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0", + "@prisma/engines-version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "@prisma/get-platform": "6.19.0" + } + }, + "node_modules/@prisma/get-platform": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.19.0.tgz", + "integrity": "sha512-ym85WDO2yDhC3fIXHWYpG3kVMBA49cL1XD2GCsCF8xbwoy2OkDQY44gEbAt2X46IQ4Apq9H6g0Ex1iFfPqEkHA==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "dev": true, + "license": "MIT" + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", + "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "license": "MIT" + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.9", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/node": { + "version": "24.10.1", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/accepts": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/amp": { + "version": "0.3.1", + "license": "MIT" + }, + "node_modules/amp-message": { + "version": "0.1.2", + "license": "MIT", + "dependencies": { + "amp": "0.3.1" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ansis": { + "version": "4.0.0-node10", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "license": "Python-2.0" + }, + "node_modules/ast-types": { + "version": "0.13.4", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ast-types/node_modules/tslib": { + "version": "2.8.1", + "license": "0BSD" + }, + "node_modules/async": { + "version": "3.2.6", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.13.2", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/babel-jest": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/transform": "^29.7.0", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-jest/node_modules/ansi-styles": { + "version": "4.3.0", + "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/babel-jest/node_modules/chalk": { + "version": "4.1.2", + "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/babel-jest/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-jest/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-plugin-polyfill-corejs2": { + "version": "0.4.14", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.27.7", + "@babel/helper-define-polyfill-provider": "^0.6.5", + "semver": "^6.3.1" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.13.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.5", + "core-js-compat": "^3.43.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-regenerator": { + "version": "0.6.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.5" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" + }, + "peerDependencies": { + "@babel/core": "^7.0.0 || ^8.0.0-0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "dependencies": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.8.30", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/basic-ftp": { + "version": "5.0.5", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/better-sqlite3": { + "version": "12.4.5", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.4.5.tgz", + "integrity": "sha512-4NejwX2llfdKYK7Tzwwre/qKzTXiqcbycIagtqMH9oE7Es3LCUGGGXvhw8rWbZ2alx1C/Nh0MeJyYEZKUFs4sw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bodec": { + "version": "0.1.0", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.0", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.8.25", + "caniuse-lite": "^1.0.30001754", + "electron-to-chromium": "^1.5.249", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.1.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/c12": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz", + "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "chokidar": "^4.0.3", + "confbox": "^0.2.2", + "defu": "^6.1.4", + "dotenv": "^16.6.1", + "exsolve": "^1.0.7", + "giget": "^2.0.0", + "jiti": "^2.4.2", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^1.0.0", + "pkg-types": "^2.2.0", + "rc9": "^2.1.2" + }, + "peerDependencies": { + "magicast": "^0.3.5" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, + "node_modules/c12/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/c12/node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "devOptional": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/c12/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "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", + "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", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001756", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "5.6.2", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/chardet": { + "version": "2.1.1", + "license": "MIT" + }, + "node_modules/charm": { + "version": "0.1.2", + "license": "MIT/X11" + }, + "node_modules/chokidar": { + "version": "3.6.0", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/ci-info": { + "version": "3.9.0", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/citty": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", + "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-tableau": { + "version": "2.0.1", + "dependencies": { + "chalk": "3.0.0" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/cli-tableau/node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cli-tableau/node_modules/chalk": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-tableau/node_modules/has-flag": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-tableau/node_modules/supports-color": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "9.0.1", + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/co": { + "version": "4.6.0", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "2.15.1", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz", + "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.7.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/core-js-compat": { + "version": "3.47.0", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/create-jest": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/create-jest/node_modules/ansi-styles": { + "version": "4.3.0", + "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/create-jest/node_modules/chalk": { + "version": "4.1.2", + "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/create-jest/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/create-jest/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/croner": { + "version": "4.1.97", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/culvert": { + "version": "0.1.2", + "license": "MIT" + }, + "node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/dayjs": { + "version": "1.11.15", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dedent": { + "version": "1.7.0", + "dev": true, + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deepmerge-ts": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", + "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", + "devOptional": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/default-gateway": { + "version": "7.2.2", + "license": "BSD-2-Clause", + "dependencies": { + "execa": "^7.1.1" + }, + "engines": { + "node": ">= 16" + } + }, + "node_modules/defu": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz", + "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/degenerator": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "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", + "license": "MIT" + }, + "node_modules/effect": { + "version": "3.18.4", + "resolved": "https://registry.npmjs.org/effect/-/effect-3.18.4.tgz", + "integrity": "sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "fast-check": "^3.23.1" + } + }, + "node_modules/ejs": { + "version": "3.1.10", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/electron-is-dev": { + "version": "3.0.1", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.258", + "dev": true, + "license": "ISC" + }, + "node_modules/emittery": { + "version": "0.13.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "license": "MIT" + }, + "node_modules/empathic": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", + "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/enquirer": { + "version": "2.3.6", + "license": "MIT", + "dependencies": { + "ansi-colors": "^4.1.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/escodegen": { + "version": "2.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter2": { + "version": "5.0.1", + "license": "MIT" + }, + "node_modules/execa": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.1", + "human-signals": "^4.3.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^3.0.7", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": "^14.18.0 || ^16.14.0 || >=18.0.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/expect": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/express": { + "version": "5.1.0", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.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-session": { + "version": "1.18.2", + "license": "MIT", + "dependencies": { + "cookie": "0.7.2", + "cookie-signature": "1.0.7", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.1.0", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/express-session/node_modules/cookie-signature": { + "version": "1.0.7", + "license": "MIT" + }, + "node_modules/express-session/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express-session/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/express-ws": { + "version": "5.0.2", + "license": "BSD-2-Clause", + "dependencies": { + "ws": "^7.4.6" + }, + "engines": { + "node": ">=4.5.0" + }, + "peerDependencies": { + "express": "^4.0.0 || ^5.0.0-alpha.1" + } + }, + "node_modules/exsolve": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", + "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/extrareqp2": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.14.0" + } + }, + "node_modules/fast-check": { + "version": "3.23.2", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", + "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "dependencies": { + "pure-rand": "^6.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fast-json-patch": { + "version": "3.1.1", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/fclone": { + "version": "1.0.11", + "license": "MIT" + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/filelist": { + "version": "1.0.4", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.6", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "2.1.0", + "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": ">= 0.8" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.5", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "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==", + "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", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "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-package-type": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-uri": { + "version": "6.0.5", + "license": "MIT", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/giget": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", + "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.0", + "defu": "^6.1.4", + "node-fetch-native": "^1.6.6", + "nypm": "^0.6.0", + "pathe": "^2.0.3" + }, + "bin": { + "giget": "dist/cli.mjs" + } + }, + "node_modules/git-node-fs": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/git-sha1": { + "version": "0.1.2", + "license": "MIT" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob": { + "version": "7.2.3", + "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": "5.1.2", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "dev": true, + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/human-signals": { + "version": "4.3.1", + "license": "Apache-2.0", + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "license": "ISC" + }, + "node_modules/import-local": { + "version": "3.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "license": "ISC" + }, + "node_modules/inquirer": { + "version": "13.0.1", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.1", + "@inquirer/core": "^11.0.1", + "@inquirer/prompts": "^8.0.1", + "@inquirer/type": "^4.0.1", + "mute-stream": "^3.0.0", + "run-async": "^4.0.6", + "rxjs": "^7.8.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/ip-address": { + "version": "10.1.0", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "dev": true, + "license": "MIT" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "license": "MIT" + }, + "node_modules/is-stream": { + "version": "3.0.0", + "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", + "license": "ISC" + }, + "node_modules/isomorphic-form-data": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "form-data": "^2.3.2" + } + }, + "node_modules/isomorphic-form-data/node_modules/form-data": { + "version": "2.5.5", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/isomorphic-form-data/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/isomorphic-form-data/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "6.0.3", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "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-report/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jake": { + "version": "10.9.4", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-changed-files/node_modules/execa": { + "version": "5.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/jest-changed-files/node_modules/human-signals": { + "version": "2.1.0", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/jest-changed-files/node_modules/is-stream": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-changed-files/node_modules/mimic-fn": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/jest-changed-files/node_modules/npm-run-path": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-changed-files/node_modules/onetime": { + "version": "5.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-changed-files/node_modules/strip-final-newline": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-circus/node_modules/chalk": { + "version": "4.1.2", + "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/jest-circus/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-circus/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-cli/node_modules/ansi-regex": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-cli/node_modules/chalk": { + "version": "4.1.2", + "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/jest-cli/node_modules/cliui": { + "version": "8.0.1", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-cli/node_modules/emoji-regex": { + "version": "8.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-cli/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli/node_modules/string-width": { + "version": "4.2.3", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli/node_modules/strip-ansi": { + "version": "6.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-cli/node_modules/wrap-ansi": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/jest-cli/node_modules/yargs": { + "version": "17.7.2", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-cli/node_modules/yargs-parser": { + "version": "21.1.1", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-config/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-config/node_modules/chalk": { + "version": "4.1.2", + "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/jest-config/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-config/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-diff": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-diff/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-diff/node_modules/chalk": { + "version": "4.1.2", + "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/jest-diff/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-diff/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-each/node_modules/chalk": { + "version": "4.1.2", + "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/jest-each/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-each/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-matcher-utils/node_modules/chalk": { + "version": "4.1.2", + "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/jest-matcher-utils/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-matcher-utils/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-message-util": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-message-util/node_modules/chalk": { + "version": "4.1.2", + "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/jest-message-util/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-message-util/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-mock": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.6.3", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-resolve/node_modules/chalk": { + "version": "4.1.2", + "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/jest-resolve/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-resolve/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-runner/node_modules/chalk": { + "version": "4.1.2", + "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/jest-runner/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runner/node_modules/source-map-support": { + "version": "0.5.13", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/jest-runner/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-runtime/node_modules/chalk": { + "version": "4.1.2", + "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/jest-runtime/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-runtime/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-snapshot": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "natural-compare": "^1.4.0", + "pretty-format": "^29.7.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-snapshot/node_modules/chalk": { + "version": "4.1.2", + "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/jest-snapshot/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-snapshot/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-util/node_modules/chalk": { + "version": "4.1.2", + "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/jest-util/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-util/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-validate": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-validate/node_modules/chalk": { + "version": "4.1.2", + "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/jest-validate/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-validate/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-watcher": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-watcher/node_modules/ansi-styles": { + "version": "4.3.0", + "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/jest-watcher/node_modules/chalk": { + "version": "4.1.2", + "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/jest-watcher/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-watcher/node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker": { + "version": "29.7.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "devOptional": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-git": { + "version": "0.7.8", + "license": "MIT", + "dependencies": { + "bodec": "^0.1.0", + "culvert": "^0.1.2", + "git-sha1": "^0.1.2", + "pako": "^0.2.5" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "license": "ISC", + "optional": true + }, + "node_modules/json5": { + "version": "2.2.3", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "dev": true, + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "7.18.3", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/makeerror": { + "version": "1.0.12", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "license": "MIT" + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "dev": true, + "license": "MIT" + }, + "node_modules/needle": { + "version": "2.4.0", + "license": "MIT", + "dependencies": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + }, + "bin": { + "needle": "bin/needle" + }, + "engines": { + "node": ">= 4.4.x" + } + }, + "node_modules/needle/node_modules/debug": { + "version": "3.2.7", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/needle/node_modules/iconv-lite": { + "version": "0.4.24", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/netmask": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/node-abi": { + "version": "3.85.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.85.0.tgz", + "integrity": "sha512-zsFhmbkAzwhTft6nd3VxcG0cvJsT70rL+BIGHWVq5fi6MwGrHwzqKaxXE+Hl2GmnGItnDKPPkO5/LQqjVkIdFg==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/node-int64": { + "version": "0.4.0", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.27", + "dev": true, + "license": "MIT" + }, + "node_modules/nodemon": { + "version": "3.1.11", + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "5.3.0", + "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", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nypm": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.2.tgz", + "integrity": "sha512-7eM+hpOtrKrBDCh7Ypu2lJ9Z7PNZBdi/8AT3AX8xoCj43BBVHD0hPSTEvMtkMpfs8FCqBGhxB+uToIQimA111g==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.2", + "pathe": "^2.0.3", + "pkg-types": "^2.3.0", + "tinyexec": "^1.0.1" + }, + "bin": { + "nypm": "dist/cli.mjs" + }, + "engines": { + "node": "^14.16.0 || >=16.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ohash": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", + "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.4.1", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "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": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pac-proxy-agent": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.6", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "license": "MIT", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pako": { + "version": "0.2.9", + "license": "MIT" + }, + "node_modules/parse-json": { + "version": "5.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "license": "MIT" + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pg": { + "version": "8.16.3", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz", + "integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.9.1", + "pg-pool": "^3.10.1", + "pg-protocol": "^1.10.3", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.2.7" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.7.tgz", + "integrity": "sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.9.1.tgz", + "integrity": "sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.10.1.tgz", + "integrity": "sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.10.3.tgz", + "integrity": "sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pidusage": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-types": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", + "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/pm2": { + "version": "6.0.13", + "license": "AGPL-3.0", + "dependencies": { + "@pm2/agent": "~2.1.1", + "@pm2/blessed": "0.1.81", + "@pm2/io": "~6.1.0", + "@pm2/js-api": "~0.8.0", + "@pm2/pm2-version-check": "latest", + "ansis": "4.0.0-node10", + "async": "3.2.6", + "chokidar": "3.6.0", + "cli-tableau": "2.0.1", + "commander": "2.15.1", + "croner": "4.1.97", + "dayjs": "1.11.15", + "debug": "4.4.3", + "enquirer": "2.3.6", + "eventemitter2": "5.0.1", + "fclone": "1.0.11", + "js-yaml": "4.1.0", + "mkdirp": "1.0.4", + "needle": "2.4.0", + "pidusage": "3.0.2", + "pm2-axon": "~4.0.1", + "pm2-axon-rpc": "~0.7.1", + "pm2-deploy": "~1.0.2", + "pm2-multimeter": "^0.1.2", + "promptly": "2.2.0", + "semver": "7.7.2", + "source-map-support": "0.5.21", + "sprintf-js": "1.1.2", + "vizion": "~2.2.1" + }, + "bin": { + "pm2": "bin/pm2", + "pm2-dev": "bin/pm2-dev", + "pm2-docker": "bin/pm2-docker", + "pm2-runtime": "bin/pm2-runtime" + }, + "engines": { + "node": ">=16.0.0" + }, + "optionalDependencies": { + "pm2-sysmonit": "^1.2.8" + } + }, + "node_modules/pm2-axon": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "amp": "~0.3.1", + "amp-message": "~0.1.1", + "debug": "^4.3.1", + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=5" + } + }, + "node_modules/pm2-axon-rpc": { + "version": "0.7.1", + "license": "MIT", + "dependencies": { + "debug": "^4.3.1" + }, + "engines": { + "node": ">=5" + } + }, + "node_modules/pm2-deploy": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "run-series": "^1.1.8", + "tv4": "^1.3.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pm2-multimeter": { + "version": "0.1.2", + "license": "MIT/X11", + "dependencies": { + "charm": "~0.1.1" + } + }, + "node_modules/pm2-sysmonit": { + "version": "1.2.8", + "license": "Apache", + "optional": true, + "dependencies": { + "async": "^3.2.0", + "debug": "^4.3.1", + "pidusage": "^2.0.21", + "systeminformation": "^5.7", + "tx2": "~1.0.4" + } + }, + "node_modules/pm2-sysmonit/node_modules/pidusage": { + "version": "2.0.21", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pm2/node_modules/semver": { + "version": "7.7.2", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "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", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prisma": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.19.0.tgz", + "integrity": "sha512-F3eX7K+tWpkbhl3l4+VkFtrwJlLXbAM+f9jolgoUZbFcm1DgHZ4cq9AgVEgUym2au5Ad/TDLN8lg83D+M10ycw==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/config": "6.19.0", + "@prisma/engines": "6.19.0" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/promptly": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "read": "^1.0.4" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-agent": { + "version": "6.4.0", + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.0.1", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", + "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.14.0", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/random-bytes": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.7.0", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.7.0", + "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/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/rc/node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rc9": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", + "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "defu": "^6.1.4", + "destr": "^2.0.3" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "dev": true, + "license": "MIT" + }, + "node_modules/read": { + "version": "1.0.7", + "license": "ISC", + "dependencies": { + "mute-stream": "~0.0.4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/read/node_modules/mute-stream": { + "version": "0.0.8", + "license": "ISC" + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/regenerate": { + "version": "1.4.2", + "dev": true, + "license": "MIT" + }, + "node_modules/regenerate-unicode-properties": { + "version": "10.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regexpu-core": { + "version": "6.4.0", + "dev": true, + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^10.2.2", + "regjsgen": "^0.8.0", + "regjsparser": "^0.13.0", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.2.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regjsgen": { + "version": "0.8.0", + "dev": true, + "license": "MIT" + }, + "node_modules/regjsparser": { + "version": "0.13.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "jsesc": "~3.1.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-in-the-middle": { + "version": "5.2.0", + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/router": { + "version": "2.2.0", + "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/run-async": { + "version": "4.0.6", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/run-series": { + "version": "1.1.9", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/rxjs": { + "version": "7.8.2", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/rxjs/node_modules/tslib": { + "version": "2.8.1", + "license": "0BSD" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.4.3", + "license": "BlueOak-1.0.0" + }, + "node_modules/semver": { + "version": "7.7.3", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-escape": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/shimmer": { + "version": "1.2.1", + "license": "BSD-2-Clause" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "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", + "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", + "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", + "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/signal-exit": { + "version": "3.0.7", + "license": "ISC" + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "dev": true, + "license": "MIT" + }, + "node_modules/slash": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.2", + "license": "BSD-3-Clause" + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-length/node_modules/ansi-regex": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-length/node_modules/strip-ansi": { + "version": "6.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/systeminformation": { + "version": "5.27.11", + "license": "MIT", + "optional": true, + "os": [ + "darwin", + "linux", + "win32", + "freebsd", + "openbsd", + "netbsd", + "sunos", + "android" + ], + "bin": { + "systeminformation": "lib/cli.js" + }, + "engines": { + "node": ">=8.0.0" + }, + "funding": { + "type": "Buy me a coffee", + "url": "https://www.buymeacoffee.com/systeminfo" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tcp-ping": { + "version": "0.1.1", + "license": "MIT" + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tmpl": { + "version": "1.0.5", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tslib": { + "version": "1.9.3", + "license": "Apache-2.0" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tv4": { + "version": "1.3.0", + "license": [ + { + "type": "Public Domain", + "url": "http://geraintluff.github.io/tv4/LICENSE.txt" + }, + { + "type": "MIT", + "url": "http://jsonary.com/LICENSE.txt" + } + ], + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/tx2": { + "version": "1.0.5", + "license": "MIT", + "optional": true, + "dependencies": { + "json-stringify-safe": "^5.0.1" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uid-safe": { + "version": "2.1.5", + "license": "MIT", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.16.0", + "devOptional": true, + "license": "MIT" + }, + "node_modules/unicode-canonical-property-names-ecmascript": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-ecmascript": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-value-ecmascript": { + "version": "2.2.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-property-aliases-ecmascript": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.4", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "13.0.0", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "dev": true, + "license": "ISC", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vizion": { + "version": "2.2.1", + "license": "Apache-2.0", + "dependencies": { + "async": "^2.6.3", + "git-node-fs": "^1.0.0", + "ini": "^1.3.5", + "js-git": "^0.7.8" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/vizion/node_modules/async": { + "version": "2.6.4", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/walker": { + "version": "1.0.8", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/which": { + "version": "2.0.2", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/ws": { + "version": "7.5.10", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "18.0.0", + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^7.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs-parser": { + "version": "22.0.0", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..45ab95f --- /dev/null +++ b/package.json @@ -0,0 +1,67 @@ +{ + "name": "localping", + "version": "0.1.0", + "description": "A local system uptime monitor - Quick-fix your homelab remotely", + "main": "src/app.js", + "scripts": { + "start": "node src/app.js", + "dev": "nodemon src/app.js", + "gui": "electron src/electron/main.js", + "web": "node src/app.js --mode web", + "pm2:start": "pm2 start ecosystem.config.js", + "pm2:stop": "pm2 stop all", + "pm2:logs": "pm2 logs", + "pm2:restart": "pm2 restart all", + "test": "jest", + "test:watch": "jest --watch", + "test:coverage": "jest --coverage", + "test:backup": "jest __tests__/services/backupService.test.js", + "test:backup:watch": "jest __tests__/services/backupService.test.js --watch", + "verify:ping": "node scripts/verify-ping-data.js", + "prisma:generate": "prisma generate", + "prisma:push": "prisma db push", + "prisma:studio": "prisma studio", + "postinstall": "prisma generate" + }, + "keywords": [ + "uptime", + "monitoring", + "homelab", + "ping", + "dashboard" + ], + "author": "Your Name", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + }, + "dependencies": { + "@prisma/client": "^6.8.2", + "axios": "^1.13.2", + "better-sqlite3": "^12.4.5", + "chalk": "^5.6.2", + "cors": "^2.8.5", + "default-gateway": "^7.2.2", + "dotenv": "^17.2.3", + "ejs": "^3.1.10", + "electron-is-dev": "^3.0.1", + "express": "^5.1.0", + "express-session": "^1.17.3", + "express-ws": "^5.0.2", + "inquirer": "^13.0.1", + "isomorphic-form-data": "^2.0.0", + "nodemon": "^3.1.11", + "pg": "^8.13.1", + "pm2": "^6.0.13", + "shell-escape": "^0.2.0", + "tcp-ping": "^0.1.1", + "uuid": "^13.0.0", + "yargs": "^18.0.0" + }, + "devDependencies": { + "@babel/preset-env": "^7.28.5", + "@babel/preset-typescript": "^7.28.5", + "jest": "^29.7.0", + "prisma": "^6.8.2" + } +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000..a32a529 --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,227 @@ +// Prisma Schema for LocalPing +// Run `npx prisma generate` after changes +// Run `npx prisma db push` to sync with database + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model Target { + id String @id @default(uuid()) @map("_id") + name String @unique + host String + protocol String + port Int? + path String? + enabled Boolean @default(true) + publicVisible Boolean @default(true) + publicShowDetails Boolean @default(false) + publicShowStatus Boolean @default(true) + publicShowAppLink Boolean @default(true) + interval Int @default(60) + retries Int @default(0) + retryInterval Int @default(5) + timeout Int @default(30) + httpMethod String @default("GET") + statusCodes String @default("200-299") + maxRedirects Int @default(5) + ignoreSsl Boolean @default(false) + upsideDown Boolean @default(false) + important Boolean @default(false) + auth Json? + appUrl String? + appIcon String? + position Int @default(0) + group String? + quickCommands Json? + description String? + tier String @default("normal") // featured | normal | background + linkPublic Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + pingResults PingResult[] + alerts Alert[] + statistics Statistic[] + actions Action[] + + @@map("targets") +} + +model PingResult { + id String @id @default(uuid()) @map("_id") + targetId String + success Boolean + responseTime Int? + timestamp DateTime @default(now()) + statusCode Int? + error String? + protocol String? + + target Target @relation(fields: [targetId], references: [id], onDelete: Cascade) + + @@index([targetId]) + @@index([timestamp]) + @@index([targetId, timestamp]) + @@map("pingResults") +} + +model Alert { + id String @id @default(uuid()) @map("_id") + targetId String + type String + timestamp DateTime @default(now()) + message String? + + target Target @relation(fields: [targetId], references: [id], onDelete: Cascade) + + @@index([targetId]) + @@index([timestamp]) + @@map("alerts") +} + +model Statistic { + id String @id @default(uuid()) @map("_id") + targetId String + date DateTime @db.Date + totalPings Int @default(0) + successfulPings Int @default(0) + failedPings Int @default(0) + uptime Float @default(0) + lastResponseTime Int @default(0) + avgResponseTime Float @default(0) + minResponseTime Int? + maxResponseTime Int? + + target Target @relation(fields: [targetId], references: [id], onDelete: Cascade) + + @@unique([targetId, date]) + @@index([targetId]) + @@index([date]) + @@map("statistics") +} + +model Incident { + id String @id @default(uuid()) @map("_id") + title String + description String? + severity String @default("major") + status String @default("investigating") + affectedServices Json? + updates Json? + resolvedAt DateTime? + isScheduled Boolean @default(false) + scheduledStart DateTime? + scheduledEnd DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([status]) + @@index([isScheduled, scheduledStart]) + @@map("incidents") +} + +model EventRule { + id String @id @default(uuid()) @map("_id") + name String + eventType String + enabled Boolean @default(true) + conditions Json + incidentTitle String + incidentDescription String + incidentSeverity String @default("major") + incidentStatus String @default("investigating") + autoResolve Boolean @default(false) + autoResolveMessage String? + cooldownMinutes Int @default(0) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([enabled]) + @@map("eventRules") +} + +model Action { + id String @id @default(uuid()) @map("_id") + targetId String + name String + type String + command String? + createdAt DateTime @default(now()) + + target Target @relation(fields: [targetId], references: [id], onDelete: Cascade) + + @@unique([targetId, name]) + @@index([targetId]) + @@map("actions") +} + +model Favicon { + id String @id @default(uuid()) @map("_id") + appUrl String @unique + favicon String? + updatedAt DateTime @updatedAt + + @@map("favicons") +} + +model SiteBrand { + id String @id @default("brand") @map("_id") + name String? + accent String? + tagline String? + iconData Bytes? + iconType String? + updatedAt DateTime @updatedAt + + @@map("siteBrand") +} + +model PublicUISettings { + id String @id @default("settings") @map("_id") + title String @default("Homelab") + subtitle String @default("System Status & Application Dashboard") + customCSS String? + updatedAt DateTime @updatedAt + + @@map("publicUISettings") +} + +model AdminSettings { + id String @id @default("settings") @map("_id") + sessionDurationDays Int @default(30) + dataRetentionDays Int @default(30) + debugLogging Boolean @default(false) + updatedAt DateTime @updatedAt + + @@map("adminSettings") +} + +model NotificationSettings { + id String @id @default("settings") @map("_id") + enabled Boolean @default(false) + discord Json? + events Json? + monitorDownDelayMinutes Int @default(5) + updatedAt DateTime @updatedAt + + @@map("notificationSettings") +} + +model Post { + id String @id @default(uuid()) @map("_id") + title String + content String + published Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([published]) + @@index([createdAt]) + @@map("posts") +} diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000..7f151fb --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,38 @@ +# CDN Library Download Scripts + +These scripts download all external CDN libraries locally to make the project self-sustainable and work offline. + +## Usage + +### Option 1: Bash Script (Linux/macOS) + +```bash +./scripts/download-cdn-libs.sh +``` + +### Option 2: Node.js Script (Cross-platform) + +```bash +node scripts/download-cdn-libs.js +``` + +## What Gets Downloaded + +The scripts will download the following libraries to `src/public/vendor/`: + +1. **Tailwind CSS** β†’ `vendor/tailwindcss.js` +2. **Chart.js** β†’ `vendor/chart.js` +3. **Axios** β†’ `vendor/axios.min.js` +4. **Marked** (Markdown parser) β†’ `vendor/marked.min.js` +5. **Font Awesome** β†’ `vendor/font-awesome/all.min.css` + webfonts + +## After Running + +All view files have already been updated to use local paths instead of CDN URLs. The libraries will be served from `/vendor/` when the application runs. + +## Notes + +- Make sure you have an internet connection when running these scripts +- The scripts will create the necessary directory structure automatically +- Font Awesome CSS paths are automatically updated to point to local webfonts + diff --git a/scripts/create-db-user.sh b/scripts/create-db-user.sh new file mode 100755 index 0000000..48fb706 --- /dev/null +++ b/scripts/create-db-user.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Create PostgreSQL user and database for localping + +echo "πŸ”§ Creating PostgreSQL user and database..." + +# Check if PostgreSQL is running +if ! pg_isready > /dev/null 2>&1; then + echo "❌ PostgreSQL is not running. Start it with: sudo systemctl start postgresql" + exit 1 +fi + +# Create user if it doesn't exist +echo "πŸ‘€ Creating user 'localping'..." +sudo -u postgres psql -c "SELECT 1 FROM pg_roles WHERE rolname='localping';" | grep -q 1 || \ + sudo -u postgres psql -c "CREATE USER localping WITH PASSWORD 'localping';" + +if [ $? -eq 0 ]; then + echo "βœ… User 'localping' created or already exists" +else + echo "⚠️ User creation may have failed (might already exist)" +fi + +# Create database if it doesn't exist +echo "πŸ—„οΈ Creating database 'localping'..." +sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname='localping';" | grep -q 1 || \ + sudo -u postgres psql -c "CREATE DATABASE localping OWNER localping;" + +if [ $? -eq 0 ]; then + echo "βœ… Database 'localping' created or already exists" +else + echo "⚠️ Database creation may have failed (might already exist)" +fi + +# Grant privileges +echo "πŸ” Granting privileges..." +sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE localping TO localping;" + +echo "" +echo "βœ… Setup complete! The app should now be able to connect." +echo "" +echo "πŸ’‘ If you want to use a different password, update your .env file:" +echo " DB_PASSWORD=your_password_here" +echo "" +echo " Then run this script again with the new password in the CREATE USER command." + diff --git a/scripts/download-cdn-libs.js b/scripts/download-cdn-libs.js new file mode 100755 index 0000000..cc19eee --- /dev/null +++ b/scripts/download-cdn-libs.js @@ -0,0 +1,204 @@ +#!/usr/bin/env node + +/** + * Script to download all CDN libraries locally for offline use + * This makes the project self-sustainable without internet connection + */ + +const https = require('https'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const { URL } = require('url'); + +const PROJECT_ROOT = path.join(__dirname, '..'); +const VENDOR_DIR = path.join(PROJECT_ROOT, 'src', 'public', 'vendor'); +const FONTAWESOME_DIR = path.join(VENDOR_DIR, 'font-awesome'); + +// Colors for console output +const colors = { + green: '\x1b[32m', + yellow: '\x1b[33m', + reset: '\x1b[0m' +}; + +function log(message, color = 'reset') { + console.log(`${colors[color]}${message}${colors.reset}`); +} + +// Create directories +function ensureDir(dir) { + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } +} + +// Download file function +function downloadFile(url, outputPath, maxRedirects = 5) { + return new Promise((resolve, reject) => { + if (maxRedirects <= 0) { + reject(new Error('Too many redirects')); + return; + } + + const parsedUrl = new URL(url); + const protocol = parsedUrl.protocol === 'https:' ? https : http; + + const file = fs.createWriteStream(outputPath); + + const request = protocol.get(url, (response) => { + if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307 || response.statusCode === 308) { + file.close(); + if (fs.existsSync(outputPath)) { + fs.unlinkSync(outputPath); + } + + // Handle redirects - resolve relative URLs + let redirectUrl = response.headers.location; + if (!redirectUrl) { + reject(new Error(`Redirect without location header from ${url}`)); + return; + } + + // Resolve relative URLs + if (redirectUrl.startsWith('/')) { + redirectUrl = `${parsedUrl.protocol}//${parsedUrl.host}${redirectUrl}`; + } else if (!redirectUrl.startsWith('http://') && !redirectUrl.startsWith('https://')) { + redirectUrl = new URL(redirectUrl, url).href; + } + + return downloadFile(redirectUrl, outputPath, maxRedirects - 1) + .then(resolve) + .catch(reject); + } + + if (response.statusCode !== 200) { + file.close(); + if (fs.existsSync(outputPath)) { + fs.unlinkSync(outputPath); + } + reject(new Error(`Failed to download ${url}: ${response.statusCode}`)); + return; + } + + response.pipe(file); + + file.on('finish', () => { + file.close(); + resolve(); + }); + }); + + request.on('error', (err) => { + file.close(); + if (fs.existsSync(outputPath)) { + fs.unlinkSync(outputPath); + } + reject(err); + }); + + file.on('error', (err) => { + file.close(); + if (fs.existsSync(outputPath)) { + fs.unlinkSync(outputPath); + } + reject(err); + }); + }); +} + +async function main() { + log('Starting CDN library download...', 'green'); + + // Create directories + ensureDir(VENDOR_DIR); + ensureDir(FONTAWESOME_DIR); + ensureDir(path.join(FONTAWESOME_DIR, 'webfonts')); + + const downloads = [ + { + name: 'Tailwind CSS', + url: 'https://cdn.tailwindcss.com', + output: path.join(VENDOR_DIR, 'tailwindcss.js') + }, + { + name: 'Chart.js', + url: 'https://cdn.jsdelivr.net/npm/chart.js', + output: path.join(VENDOR_DIR, 'chart.js') + }, + { + name: 'Axios', + url: 'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js', + output: path.join(VENDOR_DIR, 'axios.min.js') + }, + { + name: 'Marked', + url: 'https://cdn.jsdelivr.net/npm/marked/marked.min.js', + output: path.join(VENDOR_DIR, 'marked.min.js') + }, + { + name: 'Font Awesome CSS', + url: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css', + output: path.join(FONTAWESOME_DIR, 'all.min.css') + } + ]; + + // Download main libraries + for (let i = 0; i < downloads.length; i++) { + const item = downloads[i]; + log(`[${i + 1}/${downloads.length}] Downloading ${item.name}...`, 'green'); + log(` URL: ${item.url}`, 'yellow'); + + try { + await downloadFile(item.url, item.output); + log(` βœ“ Saved to: ${item.output}`, 'green'); + } catch (error) { + log(` βœ— Failed: ${error.message}`, 'yellow'); + throw error; + } + } + + // Download Font Awesome fonts + log('\nDownloading Font Awesome webfonts...', 'yellow'); + const fontFiles = [ + 'fa-solid-900.woff2', + 'fa-regular-400.woff2', + 'fa-brands-400.woff2', + 'fa-v4compatibility.woff2' + ]; + + for (const font of fontFiles) { + const url = `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/webfonts/${font}`; + const output = path.join(FONTAWESOME_DIR, 'webfonts', font); + + log(` Downloading ${font}...`, 'yellow'); + try { + await downloadFile(url, output); + log(` βœ“ Saved: ${font}`, 'green'); + } catch (error) { + log(` βœ— Failed to download ${font}: ${error.message}`, 'yellow'); + } + } + + // Update Font Awesome CSS to use local paths + log('\nUpdating Font Awesome CSS paths...', 'yellow'); + const cssPath = path.join(FONTAWESOME_DIR, 'all.min.css'); + let cssContent = fs.readFileSync(cssPath, 'utf8'); + + // Replace relative paths with absolute paths + cssContent = cssContent.replace(/url\(\.\.\/webfonts\//g, 'url(/vendor/font-awesome/webfonts/'); + cssContent = cssContent.replace(/url\(webfonts\//g, 'url(/vendor/font-awesome/webfonts/'); + + fs.writeFileSync(cssPath, cssContent); + log(' βœ“ Updated CSS paths', 'green'); + + log('\nβœ“ All libraries downloaded successfully!', 'green'); + log(`Files saved to: ${VENDOR_DIR}`, 'green'); + log('\nNext step: Update view files to use local paths instead of CDN URLs', 'yellow'); +} + +main().catch((error) => { + console.error('Error:', error); + process.exit(1); +}); + diff --git a/scripts/download-cdn-libs.sh b/scripts/download-cdn-libs.sh new file mode 100755 index 0000000..6f1cd9f --- /dev/null +++ b/scripts/download-cdn-libs.sh @@ -0,0 +1,81 @@ +#!/bin/bash + +# Script to download all CDN libraries locally for offline use +# This makes the project self-sustainable without internet connection + +set -e + +# Colors for output +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Base directories +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" +VENDOR_DIR="$PROJECT_ROOT/src/public/vendor" +FONTAWESOME_DIR="$VENDOR_DIR/font-awesome" + +echo -e "${GREEN}Starting CDN library download...${NC}" + +# Create vendor directory +mkdir -p "$VENDOR_DIR" +mkdir -p "$FONTAWESOME_DIR" + +# Function to download file +download_file() { + local url=$1 + local output=$2 + echo -e "${YELLOW}Downloading: $url${NC}" + curl -L -f -s "$url" -o "$output" || { + echo "Failed to download $url" + return 1 + } + echo -e "${GREEN}βœ“ Saved to: $output${NC}" +} + +# 1. Download Tailwind CSS (standalone build) +echo -e "\n${GREEN}[1/5] Downloading Tailwind CSS...${NC}" +download_file "https://cdn.tailwindcss.com" "$VENDOR_DIR/tailwindcss.js" + +# 2. Download Chart.js +echo -e "\n${GREEN}[2/5] Downloading Chart.js...${NC}" +download_file "https://cdn.jsdelivr.net/npm/chart.js" "$VENDOR_DIR/chart.js" + +# 3. Download Axios +echo -e "\n${GREEN}[3/5] Downloading Axios...${NC}" +download_file "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" "$VENDOR_DIR/axios.min.js" + +# 4. Download Marked (Markdown parser) +echo -e "\n${GREEN}[4/5] Downloading Marked...${NC}" +download_file "https://cdn.jsdelivr.net/npm/marked/marked.min.js" "$VENDOR_DIR/marked.min.js" + +# 5. Download Font Awesome CSS and fonts +echo -e "\n${GREEN}[5/5] Downloading Font Awesome...${NC}" +download_file "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" "$FONTAWESOME_DIR/all.min.css" + +# Download Font Awesome fonts (webfonts) +echo -e "${YELLOW}Downloading Font Awesome webfonts...${NC}" +mkdir -p "$FONTAWESOME_DIR/webfonts" + +# Get the font file URLs from the CSS +FONT_FILES=( + "fa-solid-900.woff2" + "fa-regular-400.woff2" + "fa-brands-400.woff2" + "fa-v4compatibility.woff2" +) + +for font in "${FONT_FILES[@]}"; do + download_file "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/webfonts/$font" "$FONTAWESOME_DIR/webfonts/$font" +done + +# Update Font Awesome CSS to use local paths +echo -e "${YELLOW}Updating Font Awesome CSS paths...${NC}" +sed -i "s|url(../webfonts/|url(/vendor/font-awesome/webfonts/|g" "$FONTAWESOME_DIR/all.min.css" +sed -i "s|url(webfonts/|url(/vendor/font-awesome/webfonts/|g" "$FONTAWESOME_DIR/all.min.css" + +echo -e "\n${GREEN}βœ“ All libraries downloaded successfully!${NC}" +echo -e "${GREEN}Files saved to: $VENDOR_DIR${NC}" +echo -e "\n${YELLOW}Next step: Update view files to use local paths instead of CDN URLs${NC}" + diff --git a/scripts/init-postgres.sh b/scripts/init-postgres.sh new file mode 100755 index 0000000..0b2d35d --- /dev/null +++ b/scripts/init-postgres.sh @@ -0,0 +1,95 @@ +#!/bin/bash + +# Initialize PostgreSQL database cluster for Arch Linux + +echo "πŸ—„οΈ Initializing PostgreSQL database cluster..." + +# Check if PostgreSQL is installed +if ! command -v psql &> /dev/null; then + echo "❌ PostgreSQL is not installed. Please install it first:" + echo " sudo pacman -S postgresql" + exit 1 +fi + +# Check if data directory exists and is empty +DATA_DIR="/var/lib/postgres/data" + +if [ -d "$DATA_DIR" ] && [ "$(ls -A $DATA_DIR 2>/dev/null)" ]; then + echo "βœ“ PostgreSQL data directory already exists and is not empty" + echo " If you want to reinitialize, remove it first: sudo rm -rf $DATA_DIR" +else + echo "πŸ“¦ Initializing PostgreSQL data directory..." + sudo -u postgres initdb --locale=C.UTF-8 --encoding=UTF8 -D "$DATA_DIR" + + if [ $? -eq 0 ]; then + echo "βœ… PostgreSQL database cluster initialized" + else + echo "❌ Failed to initialize PostgreSQL" + exit 1 + fi +fi + +# Start PostgreSQL service +echo "πŸš€ Starting PostgreSQL service..." +sudo systemctl start postgresql +sudo systemctl enable postgresql + +# Wait for PostgreSQL to be ready +echo "⏳ Waiting for PostgreSQL to be ready..." +sleep 2 + +# Check if PostgreSQL is running +if pg_isready > /dev/null 2>&1; then + echo "βœ… PostgreSQL is running" +else + echo "❌ PostgreSQL failed to start. Check logs with: sudo journalctl -u postgresql" + exit 1 +fi + +# Create database and user if they don't exist +DB_NAME="localping" +DB_USER="localping" + +echo "πŸ”§ Creating database and user..." + +# Generate secure password if .env doesn't exist or DB_PASSWORD is not set +if [ ! -f .env ] || ! grep -q "DB_PASSWORD" .env; then + DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24) + echo "πŸ“ Generated database password: $DB_PASSWORD" + echo " Add this to your .env file: DB_PASSWORD=$DB_PASSWORD" +else + # Extract password from .env file + DB_PASSWORD=$(grep "DB_PASSWORD" .env | cut -d '=' -f2 | tr -d '"' | tr -d "'") + if [ -z "$DB_PASSWORD" ]; then + DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24) + echo "πŸ“ Generated database password: $DB_PASSWORD" + fi +fi + +# Create user if it doesn't exist +sudo -u postgres psql -c "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1 || \ + sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';" + +# Create database if it doesn't exist +sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1 || \ + sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;" + +# Grant privileges +sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" + +echo "βœ… PostgreSQL setup complete!" +echo "" +echo "πŸ“‹ Database connection info:" +echo " Host: localhost" +echo " Port: 5432" +echo " Database: $DB_NAME" +echo " User: $DB_USER" +echo " Password: $DB_PASSWORD" +echo "" +echo "πŸ’‘ Make sure your .env file contains:" +echo " DB_HOST=localhost" +echo " DB_PORT=5432" +echo " DB_NAME=$DB_NAME" +echo " DB_USER=$DB_USER" +echo " DB_PASSWORD=$DB_PASSWORD" + diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh new file mode 100755 index 0000000..a1f95d4 --- /dev/null +++ b/scripts/run-tests.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +# Run all unit tests and report results +# This script should be run after making changes to ensure everything still works + +echo "==========================================" +echo "Running All Unit Tests" +echo "==========================================" +echo "" + +# Run all tests +npm test + +# Check exit code +if [ $? -eq 0 ]; then + echo "" + echo "==========================================" + echo "βœ“ All tests passed!" + echo "==========================================" + exit 0 +else + echo "" + echo "==========================================" + echo "βœ— Some tests failed. Please fix errors above." + echo "==========================================" + exit 1 +fi + diff --git a/scripts/test-backup.sh b/scripts/test-backup.sh new file mode 100755 index 0000000..af4c623 --- /dev/null +++ b/scripts/test-backup.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +# Test script for backup/import functionality +# This script runs the backup service tests and reports any errors + +echo "==========================================" +echo "Running Backup Service Tests" +echo "==========================================" +echo "" + +# Run the tests +npm test -- __tests__/services/backupService.test.js + +# Check exit code +if [ $? -eq 0 ]; then + echo "" + echo "==========================================" + echo "βœ“ All backup service tests passed!" + echo "==========================================" + exit 0 +else + echo "" + echo "==========================================" + echo "βœ— Some tests failed. Please fix errors above." + echo "==========================================" + exit 1 +fi + diff --git a/scripts/verify-ping-data.js b/scripts/verify-ping-data.js new file mode 100755 index 0000000..7ddd7ae --- /dev/null +++ b/scripts/verify-ping-data.js @@ -0,0 +1,113 @@ +#!/usr/bin/env node + +/** + * Verification script to check if ping data is being saved to the database + * Run this script to verify that ping results and statistics are being stored correctly + */ + +require('dotenv').config(); +const { connectDB, getDB } = require('../src/config/db'); +const chalk = require('../src/utils/colors'); + +async function verifyPingData() { + try { + console.log(chalk.cyan('Connecting to database...')); + await connectDB(); + const db = getDB(); + + console.log(chalk.cyan('\n=== Verifying Ping Data ===\n')); + + // Check targets + const targets = await db.collection('targets').find({ enabled: true }).toArray(); + console.log(chalk.yellow(`Found ${targets.length} enabled target(s)\n`)); + + if (targets.length === 0) { + console.log(chalk.red('βœ— No enabled targets found. Please create and enable at least one target.')); + process.exit(1); + } + + // Check ping results for each target + for (const target of targets) { + console.log(chalk.cyan(`\n--- Target: ${target.name} (${target._id}) ---`)); + + // Get recent ping results (last 24 hours) + const oneDayAgo = new Date(); + oneDayAgo.setHours(oneDayAgo.getHours() - 24); + + const recentPings = await db.collection('pingResults').find({ + targetId: target._id, + timestamp: { $gte: oneDayAgo } + }).toArray(); + + console.log(` Recent ping results (last 24h): ${recentPings.length}`); + + if (recentPings.length > 0) { + const latest = recentPings[recentPings.length - 1]; + const latestTime = new Date(latest.timestamp); + const minutesAgo = Math.floor((Date.now() - latestTime.getTime()) / 1000 / 60); + console.log(chalk.green(` βœ“ Latest ping: ${minutesAgo} minutes ago`)); + console.log(` Success: ${latest.success}, Response Time: ${latest.responseTime || 'N/A'}ms`); + } else { + console.log(chalk.red(` βœ— No ping results found in last 24 hours`)); + } + + // Get total ping results + const totalPings = await db.collection('pingResults').find({ + targetId: target._id + }).toArray(); + console.log(` Total ping results: ${totalPings.length}`); + + // Check statistics + const today = new Date(); + today.setHours(0, 0, 0, 0); + const todayStats = await db.collection('statistics').findOne({ + targetId: target._id, + date: today + }); + + if (todayStats) { + console.log(chalk.green(` βœ“ Today's statistics:`)); + console.log(` Total Pings: ${todayStats.totalPings}`); + console.log(` Successful: ${todayStats.successfulPings}`); + console.log(` Failed: ${todayStats.failedPings}`); + console.log(` Avg Response Time: ${Math.round(todayStats.avgResponseTime || 0)}ms`); + console.log(` Uptime: ${todayStats.uptime?.toFixed(2) || 0}%`); + } else { + console.log(chalk.yellow(` ⚠ No statistics found for today`)); + } + } + + // Overall summary + const allPings = await db.collection('pingResults').find({}).toArray(); + const allStats = await db.collection('statistics').find({}).toArray(); + + console.log(chalk.cyan('\n=== Summary ===')); + console.log(`Total ping results in database: ${allPings.length}`); + console.log(`Total statistics records: ${allStats.length}`); + + if (allPings.length === 0) { + console.log(chalk.red('\nβœ— WARNING: No ping results found in database!')); + console.log(chalk.yellow(' This could mean:')); + console.log(chalk.yellow(' 1. Monitoring is not running')); + console.log(chalk.yellow(' 2. Targets are not enabled')); + console.log(chalk.yellow(' 3. Database writes are failing (check logs)')); + process.exit(1); + } else { + console.log(chalk.green('\nβœ“ Ping data is being saved to the database')); + } + + } catch (error) { + console.error(chalk.red('\nβœ— Error verifying ping data:'), error.message); + console.error(error); + process.exit(1); + } +} + +// Run verification +verifyPingData().then(() => { + process.exit(0); +}).catch(err => { + console.error(chalk.red('Fatal error:'), err); + process.exit(1); +}); + diff --git a/src/app.js b/src/app.js new file mode 100644 index 0000000..c13eae7 --- /dev/null +++ b/src/app.js @@ -0,0 +1,240 @@ +require('dotenv').config(); +const express = require('express'); +const expressWs = require('express-ws'); +const session = require('express-session'); +const cors = require('cors'); +const path = require('path'); +const yargs = require('yargs/yargs'); +const { hideBin } = require('yargs/helpers'); +const chalk = require('./utils/colors'); + +const { connectDB, disconnectDB, getPrisma } = require('./config/prisma'); +const SQLiteSessionStore = require('./config/sessionStore'); +const monitorService = require('./services/monitorService'); +const gatewayService = require('./services/gatewayService'); +// sqliteService removed - using PostgreSQL via db.js now +const dataRetentionService = require('./services/dataRetentionService'); +const { apiKeyAuth, createRateLimiter, validateTargetInput } = require('./middleware/auth'); +const { setupCheckMiddleware, isSetupComplete } = require('./middleware/setupCheck'); + +// Parse command line arguments +const argv = yargs(hideBin(process.argv)) + .option('mode', { + describe: 'Application mode', + choices: ['api', 'admin', 'public', 'all'], + default: 'all', + }) + .parse(); + +const app = express(); +app.set('trust proxy', true); +expressWs(app); + +// Middleware +const compression = require('compression'); +app.use(compression()); +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); +app.use(cors()); + +// Initialize persistent session store +const sessionStore = new SQLiteSessionStore(); + +// Helper function to get session duration from database (defaults to 30 days) +const getSessionDuration = async () => { + try { + const prisma = getPrisma(); + const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + const days = settings?.sessionDurationDays || 30; + return days * 24 * 60 * 60 * 1000; // Convert days to milliseconds + } catch (error) { + // If DB not ready, return default + return 30 * 24 * 60 * 60 * 1000; // 30 days default + } +}; + +// Session middleware for admin authentication +// Note: maxAge will be updated dynamically in login route based on settings +const sessionMiddleware = session({ + store: sessionStore, + secret: process.env.SESSION_SECRET || 'localping-dev-secret', + resave: false, + saveUninitialized: false, // Don't save uninitialized sessions + cookie: { + secure: false, // Allow HTTP cookies for development - can be set via SECURE_COOKIES env var + httpOnly: true, + sameSite: 'lax', // Use 'lax' instead of 'strict' to allow cross-site requests with cookies + maxAge: 30 * 24 * 60 * 60 * 1000 // Default 30 days, will be updated on login + } +}); + +app.use(sessionMiddleware); + +// Rate limiting middleware (skip for localhost development) +const apiRateLimiter = (req, res, next) => { + const isLocalhost = req.ip === '127.0.0.1' || req.ip === '::1' || req.ip === '::ffff:127.0.0.1'; + if (isLocalhost && process.env.NODE_ENV !== 'production') { + // Skip rate limiting for localhost in development + return next(); + } + // Apply rate limiter for production or remote IPs + createRateLimiter(15 * 60 * 1000, 100)(req, res, next); +}; +app.use('/api/', apiRateLimiter); + +// Set view engine +app.set('view engine', 'ejs'); +app.set('views', path.join(__dirname, 'views')); + +// Static files +app.use(express.static(path.join(__dirname, "public"), { maxAge: "7d" })); + +// Serve favicon.ico (browser default) +app.get('/favicon.ico', (req, res) => { + res.sendFile(path.join(__dirname, 'public', 'favicon.ico')); +}); + +// Health check endpoint (must be before setup check middleware) +app.get('/health', (req, res) => { + res.json({ + status: 'ok', + timestamp: new Date(), + uptime: process.uptime(), + mode: argv.mode, + }); +}); + +// Setup routes - must be registered BEFORE setup check middleware +const setupRoutes = require('./routes/setup'); +app.use('/setup', setupRoutes); +console.log(chalk.cyan('βœ“ Setup routes loaded')); + +// Setup check middleware - redirect to setup if not configured +// This checks after setup routes are registered +app.use(setupCheckMiddleware); + +// Initialize database +let prisma = null; + +const startServer = async () => { + try { + // Connect to PostgreSQL database via Prisma + prisma = await connectDB(); + + // Detect gateway + await gatewayService.detectAllGateways(); + + // Set up periodic cleanup of old data (handled by dataRetentionService) + + // Set up periodic data retention processing + // Run once on startup, then every 6 hours + (async () => { + try { + await dataRetentionService.processRetentionForAllTargets(); + } catch (error) { + console.error(chalk.red('Error processing initial data retention:'), error.message); + } + })(); + + setInterval(async () => { + try { + await dataRetentionService.processRetentionForAllTargets(); + } catch (error) { + console.error(chalk.red('Error processing data retention:'), error.message); + } + }, 6 * 60 * 60 * 1000); // Run every 6 hours + + // Set up periodic processing of scheduled incidents + const IncidentService = require('./services/incidentService'); + const incidentService = new IncidentService(prisma); + setInterval(async () => { + try { + await incidentService.processScheduledIncidents(); + } catch (error) { + console.error(chalk.red('Error processing scheduled incidents:'), error.message); + } + }, 60 * 1000); // Check every minute + + // Check if setup is needed + if (!isSetupComplete()) { + console.log(chalk.yellow('\n⚠️ LocalPing setup incomplete!')); + console.log(chalk.yellow(' Visit http://localhost:8000/setup to complete setup\n')); + } + + // Static public site (src/site, or SITE_DIR to override with your own theme). + // SITE_HOSTS (comma-separated) limits it to specific Host headers; unset = all hosts. + if (argv.mode === 'public' || argv.mode === 'all') { + const siteDir = process.env.SITE_DIR || path.join(__dirname, 'site'); + if (require('fs').existsSync(path.join(siteDir, 'index.html'))) { + const hosts = (process.env.SITE_HOSTS || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean); + const onlyHosts = (mw) => (req, res, next) => (!hosts.length || hosts.includes(req.hostname.toLowerCase())) ? mw(req, res, next) : next(); + const spa = (req, res) => res.sendFile(path.join(siteDir, 'index.html'), { headers: { 'Cache-Control': 'no-cache' } }); + app.use('/', onlyHosts(require('./routes/site'))); + app.use('/s', onlyHosts(express.static(siteDir, { maxAge: '1h' }))); + app.use(onlyHosts(express.static(siteDir, { maxAge: '1h', index: false }))); + ['/', '/status', '/news', '/tools', '/about'].forEach((r) => app.get(r, onlyHosts(spa))); + console.log(chalk.cyan('βœ“ Static site loaded from ' + siteDir + (hosts.length ? ' for ' + hosts.join(',') : ''))); + } + } + + // Public routes - load FIRST so they don't get caught by authenticated API routes + if (argv.mode === 'public' || argv.mode === 'all') { + const publicRoutes = require('./routes/public'); + app.use('/', publicRoutes); + console.log(chalk.cyan('βœ“ Public routes loaded')); + } + + // Admin routes - must be before authenticated API routes + if (argv.mode === 'admin' || argv.mode === 'all') { + const adminRoutes = require('./routes/admin'); + app.use('/admin', adminRoutes); + console.log(chalk.cyan('βœ“ Admin routes loaded')); + } + + // Authenticated API routes - load LAST so public routes are matched first + if (argv.mode === 'api' || argv.mode === 'all') { + const apiRoutes = require('./routes/api'); + // Apply API key authentication to API routes + app.use('/api', apiKeyAuth, apiRoutes); + console.log(chalk.cyan('βœ“ API routes loaded with authentication')); + } + + // Start monitoring (non-blocking - runs in background) + monitorService.startMonitoring(); + + // Listen on port (starts immediately, doesn't wait for monitoring) + const port = process.env.API_PORT || 3000; + app.listen(port, () => { + console.log(chalk.green(`βœ“ Server running on http://localhost:${port}`)); + console.log(chalk.cyan(` Mode: ${argv.mode}`)); + }); + } catch (error) { + console.error(chalk.red('Failed to start server:'), error.message); + process.exit(1); + } +}; + +// Graceful shutdown +const shutdown = async (signal) => { + console.log(chalk.yellow(`\nβœ“ Received ${signal}, shutting down gracefully...`)); + + try { + monitorService.stopAllMonitoring(); + const pingService = require('./services/pingService'); + await pingService.shutdown(); + await disconnectDB(); + console.log(chalk.green('βœ“ Server shut down successfully')); + process.exit(0); + } catch (error) { + console.error(chalk.red('Error during shutdown:'), error.message); + process.exit(1); + } +}; + +process.on('SIGTERM', () => shutdown('SIGTERM')); +process.on('SIGINT', () => shutdown('SIGINT')); + +// Start server +startServer(); + +module.exports = app; diff --git a/src/cli/localping.js b/src/cli/localping.js new file mode 100644 index 0000000..27fb287 --- /dev/null +++ b/src/cli/localping.js @@ -0,0 +1,228 @@ +#!/usr/bin/env node + +require('dotenv').config(); +const chalk = require('../utils/colors'); +const yargs = require('yargs/yargs'); +const { hideBin } = require('yargs/helpers'); +const inquirer = require('inquirer'); +const { connectDB, getDB, closeDB } = require('../config/db'); +const pingService = require('../services/pingService'); +const gatewayService = require('../services/gatewayService'); + +const argv = yargs(hideBin(process.argv)) + .command('status', 'Show system status') + .command('test ', 'Test ping a host') + .command('config', 'Configure targets') + .command('list', 'List all targets') + .command('notify', 'Send test notification') + .command('gateway', 'Show detected gateway') + .command('monitor', 'Start interactive monitor (for terminal)') + .help() + .alias('h', 'help') + .version() + .alias('v', 'version') + .parse(); + +const command = argv._[0]; + +async function main() { + try { + switch (command) { + case 'status': + await showStatus(); + break; + case 'test': + await testHost(argv.host); + break; + case 'config': + await configureTargets(); + break; + case 'list': + await listTargets(); + break; + case 'notify': + await sendTestNotification(); + break; + case 'gateway': + await showGateway(); + break; + case 'monitor': + await interactiveMonitor(); + break; + default: + showHelp(); + } + } catch (error) { + console.error(chalk.red('Error:'), error.message); + process.exit(1); + } finally { + await closeDB(); + } +} + +async function showStatus() { + const db = await connectDB(); + + const targets = await db.collection('targets').find({}).toArray(); + const upTargets = targets.filter((t) => t.enabled).length; + + console.log(chalk.cyan('\nπŸ“Š LocalPing Status\n')); + console.log(`Total Targets: ${chalk.bold(targets.length)}`); + console.log(`Enabled Targets: ${chalk.bold(upTargets)}`); + console.log(); + + if (targets.length === 0) { + console.log(chalk.yellow('No targets configured. Use "localping config" to add targets.')); + } else { + console.log(chalk.cyan('\nRecent Alerts:')); + const alerts = await db.collection('alerts').find({}).sort({ timestamp: -1 }).limit(5).toArray(); + + if (alerts.length === 0) { + console.log(chalk.green('βœ“ No alerts')); + } else { + alerts.forEach((alert) => { + const icon = alert.type === 'down' ? 'βœ—' : 'βœ“'; + const color = alert.type === 'down' ? chalk.red : chalk.green; + console.log(color(`${icon} ${alert.message}`)); + }); + } + } + + console.log(); +} + +async function testHost(host) { + console.log(chalk.cyan(`\nπŸ” Testing ${host}...\n`)); + + const tests = [ + { protocol: 'ICMP', host }, + { protocol: 'TCP', host, port: 80 }, + { protocol: 'UDP', host, port: 53 }, + { protocol: 'HTTP', host, port: 80, path: '/' }, + { protocol: 'HTTPS', host, port: 443, path: '/' }, + ]; + + for (const test of tests) { + const result = await pingService.ping(test); + const status = result.success ? chalk.green('βœ“ UP') : chalk.red('βœ— DOWN'); + const time = result.responseTime ? ` (${result.responseTime}ms)` : ''; + console.log(`${test.protocol.padEnd(8)} ${status}${time}`); + } + + console.log(); +} + +async function configureTargets() { + const db = await connectDB(); + + const answers = await inquirer.prompt([ + { + type: 'list', + name: 'action', + message: 'What would you like to do?', + choices: [ + { name: 'Add target', value: 'add' }, + { name: 'Edit target', value: 'edit' }, + { name: 'Delete target', value: 'delete' }, + { name: 'Back', value: 'back' }, + ], + }, + ]); + + if (answers.action === 'add') { + const target = await inquirer.prompt([ + { type: 'input', name: 'name', message: 'Target name:' }, + { type: 'input', name: 'host', message: 'Host/IP:' }, + { + type: 'list', + name: 'protocol', + message: 'Protocol:', + choices: ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS'], + }, + { type: 'input', name: 'port', message: 'Port (optional):', default: '' }, + { type: 'input', name: 'interval', message: 'Ping interval (seconds):', default: '60' }, + ]); + + await db.collection('targets').insertOne({ + ...target, + port: target.port ? parseInt(target.port) : null, + interval: parseInt(target.interval), + enabled: true, + createdAt: new Date(), + }); + + console.log(chalk.green('βœ“ Target added successfully!')); + } +} + +async function listTargets() { + const db = await connectDB(); + + const targets = await db.collection('targets').find({}).toArray(); + + console.log(chalk.cyan('\nπŸ“‹ Configured Targets\n')); + + if (targets.length === 0) { + console.log(chalk.yellow('No targets configured.')); + } else { + targets.forEach((target, i) => { + console.log(`${i + 1}. ${target.name}`); + console.log(` Host: ${target.host}${target.port ? ':' + target.port : ''}`); + console.log(` Protocol: ${target.protocol}`); + console.log(` Interval: ${target.interval}s`); + console.log(` Status: ${target.enabled ? chalk.green('Enabled') : chalk.yellow('Disabled')}\n`); + }); + } +} + +async function sendTestNotification() { + console.log(chalk.cyan('\nπŸ“’ Browser notifications are available in the public UI\n')); + console.log(chalk.yellow('Desktop notifications have been removed for containerized environments.')); + console.log(chalk.green('Visit the public dashboard to enable browser notifications.')); + console.log(); +} + +async function showGateway() { + await gatewayService.detectAllGateways(); + + console.log(chalk.cyan('\n🌐 Gateway Information\n')); + + const gateways = gatewayService.getAllGateways(); + + if (gateways.length === 0) { + console.log(chalk.yellow('No gateway detected.')); + } else { + gateways.forEach((gw) => { + console.log(`IPv${gw.version}: ${gw.ip} (${gw.interface})`); + }); + } + + console.log(); +} + +async function interactiveMonitor() { + const db = await connectDB(); + + console.log(chalk.cyan('\nπŸ“‘ LocalPing Interactive Monitor\n')); + console.log(chalk.gray('Press Ctrl+C to exit\n')); + + // Placeholder for terminal UI implementation + console.log(chalk.yellow('⚠ Terminal UI not yet implemented.')); + console.log('Use the web admin panel instead: http://\n'); +} + +function showHelp() { + console.log(chalk.cyan('\nLocalPing CLI - Local System Uptime Monitor\n')); + console.log('Commands:'); + console.log(' localping status - Show system status'); + console.log(' localping test - Test ping a host'); + console.log(' localping config - Configure targets'); + console.log(' localping list - List all targets'); + console.log(' localping notify - Send test notification'); + console.log(' localping gateway - Show detected gateway'); + console.log(' localping monitor - Start interactive monitor'); + console.log(); +} + +// Run CLI +main(); diff --git a/src/config/db.js b/src/config/db.js new file mode 100644 index 0000000..94f552e --- /dev/null +++ b/src/config/db.js @@ -0,0 +1,880 @@ +require('dotenv').config(); +const { Pool } = require('pg'); +const chalk = require('../utils/colors'); +const cacheService = require('../services/cacheService'); + +let pool = null; + +const connectDB = async (retries = 5, delay = 2000) => { + // Get database connection details from environment or use defaults + const dbConfig = { + host: process.env.DB_HOST || 'localhost', + port: process.env.DB_PORT || 5432, + database: process.env.DB_NAME || 'localping', + user: process.env.DB_USER || 'localping', + password: process.env.DB_PASSWORD || 'localping', + max: 20, // Maximum number of clients in the pool + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 2000, + }; + + for (let attempt = 1; attempt <= retries; attempt++) { + try { + // Close existing pool if it exists + if (pool) { + try { + await pool.end(); + } catch (e) { + // Ignore errors when closing + } + pool = null; + } + + pool = new Pool(dbConfig); + + // Test connection + const client = await pool.connect(); + await client.query('SELECT NOW()'); + client.release(); + + // Initialize tables + await initializeTables(); + + console.log(chalk.green('βœ“ PostgreSQL database connected')); + + // Return a minimal object compatible with the rest of the code + return { + collection: (name) => createCollectionWrapper(name), + admin: () => ({ + ping: async () => { + try { + const client = await pool.connect(); + await client.query('SELECT 1'); + client.release(); + return true; + } catch (error) { + return false; + } + } + }) + }; + } catch (error) { + if (attempt === retries) { + console.error(chalk.red('βœ— PostgreSQL connection failed after'), retries, 'attempts:', error.message); + console.error(chalk.yellow(' Please check:')); + console.error(chalk.yellow(' - PostgreSQL is running: systemctl status postgresql')); + console.error(chalk.yellow(' - Database credentials in .env file')); + console.error(chalk.yellow(' - Connection settings:'), `host=${dbConfig.host}, port=${dbConfig.port}, database=${dbConfig.database}, user=${dbConfig.user}`); + process.exit(1); + } else { + const waitTime = delay * Math.pow(2, attempt - 1); // Exponential backoff + console.error(chalk.yellow(`⚠ PostgreSQL connection failed (attempt ${attempt}/${retries}):`), error.message); + console.error(chalk.yellow(` Retrying in ${waitTime / 1000} seconds...`)); + await new Promise(resolve => setTimeout(resolve, waitTime)); + } + } + } +}; + +const executeQuery = async (text, params) => { + const client = await pool.connect(); + try { + const result = await client.query(text, params); + return result; + } finally { + client.release(); + } +}; + +const initializeTables = async () => { + try { + // Targets table + await executeQuery(` + CREATE TABLE IF NOT EXISTS targets ( + _id TEXT PRIMARY KEY, + name TEXT UNIQUE NOT NULL, + host TEXT NOT NULL, + protocol TEXT NOT NULL, + port INTEGER, + path TEXT, + enabled BOOLEAN DEFAULT true, + "publicVisible" BOOLEAN DEFAULT true, + "publicShowDetails" BOOLEAN DEFAULT false, + "publicShowStatus" BOOLEAN DEFAULT true, + "publicShowAppLink" BOOLEAN DEFAULT true, + interval INTEGER DEFAULT 60, + retries INTEGER DEFAULT 0, + "retryInterval" INTEGER DEFAULT 5, + timeout INTEGER DEFAULT 30, + "httpMethod" TEXT DEFAULT 'GET', + "statusCodes" TEXT DEFAULT '200-299', + "maxRedirects" INTEGER DEFAULT 5, + "ignoreSsl" BOOLEAN DEFAULT false, + "upsideDown" BOOLEAN DEFAULT false, + auth TEXT, + "appUrl" TEXT, + "appIcon" TEXT, + position INTEGER DEFAULT 0, + "group" TEXT, + "quickCommands" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Migration: Add publicVisible column if it doesn't exist + try { + await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicVisible" BOOLEAN DEFAULT true`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add publicShowDetails column if it doesn't exist + try { + await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowDetails" BOOLEAN DEFAULT false`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add publicShowStatus column if it doesn't exist + try { + await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowStatus" BOOLEAN DEFAULT true`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add publicShowAppLink column if it doesn't exist + try { + await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowAppLink" BOOLEAN DEFAULT true`); + } catch (error) { + // Column already exists, ignore + } + + // Ping results table + await executeQuery(` + CREATE TABLE IF NOT EXISTS "pingResults" ( + _id TEXT PRIMARY KEY, + "targetId" TEXT NOT NULL, + success BOOLEAN NOT NULL, + "responseTime" INTEGER, + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "statusCode" INTEGER, + error TEXT, + protocol TEXT, + FOREIGN KEY("targetId") REFERENCES targets(_id) + ) + `); + + // Alerts table + await executeQuery(` + CREATE TABLE IF NOT EXISTS alerts ( + _id TEXT PRIMARY KEY, + "targetId" TEXT NOT NULL, + type TEXT NOT NULL, + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + message TEXT, + FOREIGN KEY("targetId") REFERENCES targets(_id) + ) + `); + + // Statistics table + await executeQuery(` + CREATE TABLE IF NOT EXISTS statistics ( + _id TEXT PRIMARY KEY, + "targetId" TEXT NOT NULL, + date DATE NOT NULL, + "totalPings" INTEGER DEFAULT 0, + "successfulPings" INTEGER DEFAULT 0, + "failedPings" INTEGER DEFAULT 0, + uptime REAL DEFAULT 0, + "lastResponseTime" INTEGER DEFAULT 0, + "avgResponseTime" REAL DEFAULT 0, + "minResponseTime" INTEGER, + "maxResponseTime" INTEGER, + FOREIGN KEY("targetId") REFERENCES targets(_id), + UNIQUE("targetId", date) + ) + `); + + // Incidents table + await executeQuery(` + CREATE TABLE IF NOT EXISTS incidents ( + _id TEXT PRIMARY KEY, + title TEXT NOT NULL, + description TEXT, + severity TEXT DEFAULT 'major', + status TEXT DEFAULT 'investigating', + "affectedServices" TEXT, + updates TEXT, + "resolvedAt" TIMESTAMP, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Migration: Add affectedServices column if it doesn't exist + try { + await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS "affectedServices" TEXT`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add updates column if it doesn't exist + try { + await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS updates TEXT`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add resolvedAt column if it doesn't exist + try { + await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS "resolvedAt" TIMESTAMP`); + } catch (error) { + // Column already exists, ignore + } + + // Event Rules table + await executeQuery(` + CREATE TABLE IF NOT EXISTS "eventRules" ( + _id TEXT PRIMARY KEY, + name TEXT NOT NULL, + "eventType" TEXT NOT NULL, + enabled BOOLEAN DEFAULT true, + conditions TEXT NOT NULL, + "incidentTitle" TEXT NOT NULL, + "incidentDescription" TEXT NOT NULL, + "incidentSeverity" TEXT DEFAULT 'major', + "incidentStatus" TEXT DEFAULT 'investigating', + "autoResolve" BOOLEAN DEFAULT false, + "autoResolveMessage" TEXT, + "cooldownMinutes" INTEGER DEFAULT 0, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Actions table + await executeQuery(` + CREATE TABLE IF NOT EXISTS actions ( + _id TEXT PRIMARY KEY, + "targetId" TEXT NOT NULL, + name TEXT NOT NULL, + type TEXT NOT NULL, + command TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY("targetId") REFERENCES targets(_id), + UNIQUE("targetId", name) + ) + `); + + // Favicons table + await executeQuery(` + CREATE TABLE IF NOT EXISTS favicons ( + _id TEXT PRIMARY KEY, + "appUrl" TEXT NOT NULL UNIQUE, + favicon TEXT, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Public UI Settings table + await executeQuery(` + CREATE TABLE IF NOT EXISTS "publicUISettings" ( + _id TEXT PRIMARY KEY DEFAULT 'settings', + title TEXT DEFAULT 'Homelab', + subtitle TEXT DEFAULT 'System Status & Application Dashboard', + "customCSS" TEXT, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Initialize default settings if not exists + await executeQuery(` + INSERT INTO "publicUISettings" (_id, title, subtitle, "customCSS") + VALUES ('settings', 'Homelab', 'System Status & Application Dashboard', NULL) + ON CONFLICT (_id) DO NOTHING + `); + + // Posts table (for blog/changelog) + await executeQuery(` + CREATE TABLE IF NOT EXISTS posts ( + _id TEXT PRIMARY KEY, + title TEXT NOT NULL, + content TEXT NOT NULL, + published BOOLEAN DEFAULT true, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Admin Settings table + await executeQuery(` + CREATE TABLE IF NOT EXISTS "adminSettings" ( + _id TEXT PRIMARY KEY DEFAULT 'settings', + "sessionDurationDays" INTEGER DEFAULT 30, + "dataRetentionDays" INTEGER DEFAULT 30, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Migration: Add dataRetentionDays column if it doesn't exist + try { + await executeQuery(`ALTER TABLE "adminSettings" ADD COLUMN IF NOT EXISTS "dataRetentionDays" INTEGER DEFAULT 30`); + } catch (error) { + // Column already exists, ignore + } + + // Migration: Add debugLogging column if it doesn't exist + try { + await executeQuery(`ALTER TABLE "adminSettings" ADD COLUMN IF NOT EXISTS "debugLogging" BOOLEAN DEFAULT false`); + } catch (error) { + // Column already exists, ignore + } + + // Initialize default admin settings if not exists + await executeQuery(` + INSERT INTO "adminSettings" (_id, "sessionDurationDays", "dataRetentionDays") + VALUES ('settings', 30, 30) + ON CONFLICT (_id) DO NOTHING + `); + + // Notification Settings table + await executeQuery(` + CREATE TABLE IF NOT EXISTS "notificationSettings" ( + _id TEXT PRIMARY KEY DEFAULT 'settings', + enabled BOOLEAN DEFAULT false, + discord TEXT, + events TEXT, + "monitorDownDelayMinutes" INTEGER DEFAULT 5, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Migration: add the sustained-outage notification delay to existing installs. + try { + await executeQuery(`ALTER TABLE "notificationSettings" ADD COLUMN IF NOT EXISTS "monitorDownDelayMinutes" INTEGER DEFAULT 5`); + } catch (error) { + // Column already exists, ignore. + } + + // Create indices + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_targets_enabled ON targets(enabled)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_pingResults_targetId ON "pingResults"("targetId")`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_pingResults_timestamp ON "pingResults"(timestamp)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_alerts_targetId ON alerts("targetId")`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_alerts_timestamp ON alerts(timestamp)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_statistics_targetId ON statistics("targetId")`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_statistics_date ON statistics(date)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_incidents_status ON incidents(status)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_eventRules_enabled ON "eventRules"(enabled)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_actions_targetId ON actions("targetId")`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_posts_published ON posts(published)`); + await executeQuery(`CREATE INDEX IF NOT EXISTS idx_posts_createdAt ON posts("createdAt")`); + + console.log(chalk.green('βœ“ PostgreSQL tables initialized')); + } catch (error) { + console.error(chalk.yellow('⚠ Warning initializing tables:'), error.message); + } +}; + +// Get TTL for different collections +const getTTL = (collectionName) => { + const ttlMap = { + 'adminSettings': 300000, // 5 minutes - rarely changes + 'publicUISettings': 300000, // 5 minutes - rarely changes + 'targets': 30000, // 30 seconds - may change more often + 'statistics': 120000, // 2 minutes - updated periodically + 'favicons': 600000, // 10 minutes - very rarely changes + 'posts': 60000, // 1 minute - may change occasionally + 'incidents': 60000, // 1 minute - may change occasionally + }; + return ttlMap[collectionName] || 60000; // Default 1 minute +}; + +const createCollectionWrapper = (name) => { + return { + find: (queryObj = {}) => { + // Store options for chaining + let sortOption = null; + let limitOption = null; + + const chainable = { + sort: (sortObj) => { + sortOption = sortObj; + return chainable; + }, + limit: (num) => { + limitOption = num; + return chainable; + }, + toArray: async () => { + try { + // Check cache first + const cacheKey = cacheService.generateKey(name, queryObj, { sort: sortOption, limit: limitOption }); + const cached = cacheService.get(cacheKey); + if (cached !== null) { + return cached; + } + + const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function'); + let sql = `SELECT * FROM "${name}"`; + const params = []; + let paramIndex = 1; + + if (keys.length > 0) { + const whereClauses = keys.map(k => { + const val = queryObj[k]; + // Handle MongoDB-style operators + if (typeof val === 'object' && val !== null && !(val instanceof Date)) { + if ('$gte' in val) { + const gteVal = val.$gte; + if (gteVal instanceof Date) { + params.push(gteVal.toISOString().split('T')[0]); + } else { + params.push(gteVal); + } + const idx = paramIndex++; + return `"${k}" >= $${idx}`; + } else if ('$lte' in val) { + const lteVal = val.$lte; + if (lteVal instanceof Date) { + params.push(lteVal.toISOString().split('T')[0]); + } else { + params.push(lteVal); + } + const idx = paramIndex++; + return `"${k}" <= $${idx}`; + } else if ('$gt' in val) { + const gtVal = val.$gt; + if (gtVal instanceof Date) { + params.push(gtVal.toISOString().split('T')[0]); + } else { + params.push(gtVal); + } + const idx = paramIndex++; + return `"${k}" > $${idx}`; + } else if ('$lt' in val) { + const ltVal = val.$lt; + if (ltVal instanceof Date) { + params.push(ltVal.toISOString().split('T')[0]); + } else { + params.push(ltVal); + } + const idx = paramIndex++; + return `"${k}" < $${idx}`; + } else { + // Fallback to JSON stringify for other objects + params.push(JSON.stringify(val)); + const idx = paramIndex++; + return `"${k}" = $${idx}`; + } + } + // Handle different types + if (typeof val === 'boolean') { + params.push(val); + } else if (val instanceof Date) { + // Convert Date to ISO date string (YYYY-MM-DD) + params.push(val.toISOString().split('T')[0]); + } else { + params.push(val); + } + const idx = paramIndex++; + return `"${k}" = $${idx}`; + }); + sql += ' WHERE ' + whereClauses.join(' AND '); + } + + // Add sorting + if (sortOption) { + const sortKey = Object.keys(sortOption)[0]; + const sortDir = sortOption[sortKey] === 1 ? 'ASC' : 'DESC'; + sql += ` ORDER BY "${sortKey}" ${sortDir}`; + } + + // Add limit + if (limitOption) { + sql += ` LIMIT ${limitOption}`; + } + + const result = await executeQuery(sql, params); + + // Convert boolean integers back to booleans for compatibility + const results = result.rows.map(row => { + const converted = {}; + for (const [key, value] of Object.entries(row)) { + // PostgreSQL returns booleans as booleans, but keep for consistency + converted[key] = value; + } + return converted; + }); + + // Cache the results + cacheService.set(cacheKey, results, getTTL(name)); + + return results; + } catch (error) { + console.error(chalk.red(`Error finding ${name}:`), error.message); + return []; + } + } + }; + + return chainable; + }, + findOne: async (queryObj = {}) => { + try { + // Check cache first + const cacheKey = cacheService.generateKey(name, queryObj, { findOne: true }); + const cached = cacheService.get(cacheKey); + if (cached !== null) { + return cached; + } + + const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function'); + let sql = `SELECT * FROM "${name}"`; + const params = []; + let paramIndex = 1; + + if (keys.length > 0) { + const whereClauses = keys.map(k => { + const val = queryObj[k]; + // Handle different types + if (typeof val === 'boolean') { + params.push(val); + } else if (val instanceof Date) { + // Convert Date to ISO date string (YYYY-MM-DD) for DATE columns + if (name === 'statistics' && k === 'date') { + params.push(val.toISOString().split('T')[0]); + } else { + params.push(val.toISOString().split('T')[0]); + } + } else if (typeof val === 'object' && val !== null) { + params.push(JSON.stringify(val)); + } else { + params.push(val); + } + const idx = paramIndex++; + return `"${k}" = $${idx}`; + }); + sql += ' WHERE ' + whereClauses.join(' AND '); + } + + sql += ' LIMIT 1'; + const result = await executeQuery(sql, params); + const row = result.rows[0] || null; + + // Cache the result + cacheService.set(cacheKey, row, getTTL(name)); + + return row; + } catch (error) { + console.error(chalk.red(`Error finding one ${name}:`), error.message); + return null; + } + }, + insertOne: async (doc) => { + try { + const id = doc._id || require('uuid').v4(); + const docWithId = { _id: id, ...doc }; + const fields = Object.keys(docWithId); + const placeholders = fields.map((_, i) => `$${i + 1}`).join(', '); + const quotedFields = fields.map(f => `"${f}"`).join(', '); + const values = fields.map(f => { + const val = docWithId[f]; + // PostgreSQL handles booleans natively + if (typeof val === 'boolean') { + return val; + } + // Convert Date to ISO timestamp string (YYYY-MM-DD HH:MM:SS) or date string for DATE columns + if (val instanceof Date) { + // For statistics table date column, use date format + if (name === 'statistics' && f === 'date') { + return val.toISOString().split('T')[0]; + } + return val.toISOString().replace('T', ' ').substring(0, 19); + } + // Convert arrays and objects to JSON strings + if (typeof val === 'object' && val !== null) { + return JSON.stringify(val); + } + return val; + }); + + // Use INSERT with ON CONFLICT for tables with unique constraints + let sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders})`; + + // Handle unique constraints with ON CONFLICT for specific tables + if (name === 'statistics') { + // Statistics has UNIQUE(targetId, date) - use ON CONFLICT to increment values atomically + // In ON CONFLICT, reference existing row columns directly (no qualifier needed) + // and new row columns with excluded. + const updateClauses = []; + // Increment counters + if (fields.includes('totalPings')) { + updateClauses.push(`"totalPings" = statistics."totalPings" + excluded."totalPings"`); + } + if (fields.includes('successfulPings')) { + updateClauses.push(`"successfulPings" = statistics."successfulPings" + excluded."successfulPings"`); + } + if (fields.includes('failedPings')) { + updateClauses.push(`"failedPings" = statistics."failedPings" + excluded."failedPings"`); + } + // Update latest values + if (fields.includes('lastResponseTime')) { + updateClauses.push(`"lastResponseTime" = excluded."lastResponseTime"`); + } + // Recalculate average: weighted average of existing and new + if (fields.includes('avgResponseTime')) { + updateClauses.push(`"avgResponseTime" = CASE + WHEN statistics."totalPings" + excluded."totalPings" > 0 + THEN (statistics."avgResponseTime" * statistics."totalPings" + excluded."avgResponseTime" * excluded."totalPings") / (statistics."totalPings" + excluded."totalPings") + ELSE excluded."avgResponseTime" + END`); + } + // Recalculate uptime percentage + if (fields.includes('uptime')) { + updateClauses.push(`"uptime" = CASE + WHEN statistics."totalPings" + excluded."totalPings" > 0 + THEN (CAST(statistics."successfulPings" + excluded."successfulPings" AS REAL) / CAST(statistics."totalPings" + excluded."totalPings" AS REAL)) * 100 + ELSE excluded."uptime" + END`); + } + // Update min/max response times + if (fields.includes('minResponseTime')) { + updateClauses.push(`"minResponseTime" = CASE + WHEN statistics."minResponseTime" IS NULL THEN excluded."minResponseTime" + WHEN excluded."minResponseTime" IS NULL THEN statistics."minResponseTime" + WHEN statistics."minResponseTime" < excluded."minResponseTime" THEN statistics."minResponseTime" + ELSE excluded."minResponseTime" + END`); + } + if (fields.includes('maxResponseTime')) { + updateClauses.push(`"maxResponseTime" = CASE + WHEN statistics."maxResponseTime" IS NULL THEN excluded."maxResponseTime" + WHEN excluded."maxResponseTime" IS NULL THEN statistics."maxResponseTime" + WHEN statistics."maxResponseTime" > excluded."maxResponseTime" THEN statistics."maxResponseTime" + ELSE excluded."maxResponseTime" + END`); + } + if (updateClauses.length > 0) { + sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("targetId", date) DO UPDATE SET ${updateClauses.join(', ')}`; + } + } else if (name === 'actions') { + // Actions has UNIQUE(targetId, name) - use ON CONFLICT to update instead + const updateFields = fields.filter(f => f !== '_id' && f !== 'targetId' && f !== 'name'); + const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', '); + sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("targetId", name) DO UPDATE SET ${updateClauses}`; + } else if (name === 'favicons') { + // Favicons has UNIQUE(appUrl) - use ON CONFLICT to update instead + const updateFields = fields.filter(f => f !== '_id' && f !== 'appUrl'); + const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', '); + sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("appUrl") DO UPDATE SET ${updateClauses}`; + } else if (name === 'targets') { + // Targets has UNIQUE(name) - use ON CONFLICT to update instead + const updateFields = fields.filter(f => f !== '_id' && f !== 'name'); + const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', '); + sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT(name) DO UPDATE SET ${updateClauses}`; + } + + await executeQuery(sql, values); + + // Invalidate cache for this collection + cacheService.invalidateCollection(name); + + return { insertedId: id }; + } catch (error) { + console.error(chalk.red(`Error inserting into ${name}:`), error.message); + throw error; + } + }, + updateOne: async (queryObj, update) => { + try { + const { $set } = update; + const setClauses = Object.keys($set).map((k, i) => `"${k}" = $${i + 1}`).join(', '); + const setValues = Object.values($set).map((v, idx) => { + if (typeof v === 'boolean') { + return v; + } + if (v instanceof Date) { + // For statistics table date column, use date format (YYYY-MM-DD) + const key = Object.keys($set)[idx]; + if (name === 'statistics' && key === 'date') { + return v.toISOString().split('T')[0]; + } + return v.toISOString().replace('T', ' ').substring(0, 19); + } + if (typeof v === 'object' && v !== null) { + return JSON.stringify(v); + } + return v; + }); + + const queryKeys = Object.keys(queryObj); + const whereClauses = queryKeys.map((k, i) => `"${k}" = $${setValues.length + i + 1}`).join(' AND '); + const whereValues = Object.values(queryObj).map((v, idx) => { + if (typeof v === 'boolean') { + return v; + } + if (v instanceof Date) { + // For statistics table date column, use date format (YYYY-MM-DD) + const key = Object.keys(queryObj)[idx]; + if (name === 'statistics' && key === 'date') { + return v.toISOString().split('T')[0]; + } + return v.toISOString().replace('T', ' ').substring(0, 19); + } + if (typeof v === 'object' && v !== null) { + return JSON.stringify(v); + } + return v; + }); + + const sql = `UPDATE "${name}" SET ${setClauses} WHERE ${whereClauses}`; + const result = await executeQuery(sql, [...setValues, ...whereValues]); + + // Invalidate cache for this collection + cacheService.invalidateCollection(name); + + return { modifiedCount: result.rowCount || 0 }; + } catch (error) { + console.error(chalk.red(`Error updating ${name}:`), error.message); + throw error; + } + }, + deleteOne: async (queryObj) => { + try { + const keys = Object.keys(queryObj); + const whereClauses = keys.map((k, i) => `"${k}" = $${i + 1}`).join(' AND '); + const values = Object.values(queryObj).map(v => { + if (typeof v === 'boolean') { + return v; + } + if (v instanceof Date) { + return v.toISOString().replace('T', ' ').substring(0, 19); + } + return v; + }); + + const sql = `DELETE FROM "${name}" WHERE ${whereClauses}`; + const result = await executeQuery(sql, values); + + // Invalidate cache for this collection + cacheService.invalidateCollection(name); + + return { deletedCount: result.rowCount || 0 }; + } catch (error) { + console.error(chalk.red(`Error deleting from ${name}:`), error.message); + throw error; + } + }, + deleteMany: async (queryObj = {}) => { + try { + const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function'); + let sql = `DELETE FROM "${name}"`; + const params = []; + let paramIndex = 1; + + if (keys.length > 0) { + const whereClauses = keys.map(k => { + const val = queryObj[k]; + if (typeof val === 'boolean') { + params.push(val); + } else if (val instanceof Date) { + params.push(val.toISOString().split('T')[0]); + } else { + params.push(val); + } + const idx = paramIndex++; + return `"${k}" = $${idx}`; + }); + sql += ' WHERE ' + whereClauses.join(' AND '); + } + + const result = await executeQuery(sql, params); + + // Invalidate cache for this collection + cacheService.invalidateCollection(name); + + return { deletedCount: result.rowCount || 0 }; + } catch (error) { + console.error(chalk.red(`Error deleting from ${name}:`), error.message); + throw error; + } + }, + countDocuments: async (queryObj = {}) => { + try { + // Check cache first + const cacheKey = cacheService.generateKey(name, queryObj, { count: true }); + const cached = cacheService.get(cacheKey); + if (cached !== null) { + return cached; + } + + const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function'); + let sql = `SELECT COUNT(*) as count FROM "${name}"`; + const params = []; + let paramIndex = 1; + + if (keys.length > 0) { + const whereClauses = keys.map(k => { + const val = queryObj[k]; + params.push(typeof val === 'boolean' ? val : val); + const idx = paramIndex++; + return `"${k}" = $${idx}`; + }); + sql += ' WHERE ' + whereClauses.join(' AND '); + } + + const result = await executeQuery(sql, params); + const count = result.rows[0] ? parseInt(result.rows[0].count) : 0; + + // Cache the count + cacheService.set(cacheKey, count, getTTL(name)); + + return count; + } catch (error) { + console.error(chalk.red(`Error counting ${name}:`), error.message); + return 0; + } + }, + createIndex: async () => true + }; +}; + +const getDB = () => { + if (!pool) { + throw new Error('Database not connected. Call connectDB() first.'); + } + return { + collection: (name) => createCollectionWrapper(name), + admin: () => ({ + ping: async () => { + try { + const client = await pool.connect(); + await client.query('SELECT 1'); + client.release(); + return true; + } catch (error) { + return false; + } + } + }), + // Direct query method for complex SQL queries + query: async (text, params) => { + return await executeQuery(text, params); + } + }; +}; + +const closeDB = async () => { + if (pool) { + await pool.end(); + console.log(chalk.green('βœ“ PostgreSQL connection closed')); + } +}; + +module.exports = { + connectDB, + getDB, + closeDB, +}; diff --git a/src/config/prisma.js b/src/config/prisma.js new file mode 100644 index 0000000..d299fbb --- /dev/null +++ b/src/config/prisma.js @@ -0,0 +1,91 @@ +const { PrismaClient } = require('@prisma/client'); +const chalk = require('../utils/colors'); + +// Singleton pattern for Prisma client +let prisma = null; + +/** + * Get or create the Prisma client instance + */ +const getPrisma = () => { + if (!prisma) { + prisma = new PrismaClient({ + log: process.env.NODE_ENV === 'development' + ? ['warn', 'error'] + : ['error'], + }); + } + return prisma; +}; + +/** + * Keep existing installations compatible with additive schema changes. The + * application is commonly upgraded in place, so relying only on a fresh + * `prisma db push` would leave the notification settings endpoint unusable on + * older databases. + */ +const ensureRuntimeSchema = async (client) => { + try { + await client.$executeRawUnsafe( + 'ALTER TABLE "notificationSettings" ADD COLUMN IF NOT EXISTS "monitorDownDelayMinutes" INTEGER NOT NULL DEFAULT 5', + ); + // The public uptime list aggregates recent ping results by monitor and + // time bucket. Keep the two predicates together in one index so that + // loading the compact graphs does not scan the complete ping history. + await client.$executeRawUnsafe( + 'CREATE INDEX IF NOT EXISTS idx_pingResults_targetId_timestamp ON "pingResults"("targetId", timestamp)', + ); + } catch (error) { + // A first-run database may not have been pushed yet. Prisma's normal + // schema deployment remains responsible for creating missing tables. + console.warn(chalk.yellow('⚠ Could not apply notification delay migration:'), error.message); + } +}; + +/** + * Connect to the database + */ +const connectDB = async () => { + try { + const client = getPrisma(); + await client.$connect(); + await ensureRuntimeSchema(client); + console.log(chalk.green('βœ“ PostgreSQL database connected via Prisma')); + return client; + } catch (error) { + console.error(chalk.red('βœ— PostgreSQL connection failed:'), error.message); + process.exit(1); + } +}; + +/** + * Disconnect from the database + */ +const disconnectDB = async () => { + if (prisma) { + await prisma.$disconnect(); + console.log(chalk.green('βœ“ PostgreSQL connection closed')); + prisma = null; + } +}; + +/** + * Execute raw SQL query + * @param {string} sql - SQL query with $1, $2, etc. placeholders + * @param {Array} params - Query parameters + */ +const executeRawQuery = async (sql, params = []) => { + const client = getPrisma(); + // Convert $1, $2 style to Prisma.sql template + // For now, use $queryRawUnsafe but be careful with SQL injection + const result = await client.$queryRawUnsafe(sql, ...params); + return { rows: result }; +}; + +module.exports = { + getPrisma, + connectDB, + disconnectDB, + executeRawQuery, + ensureRuntimeSchema, +}; diff --git a/src/config/sessionStore.js b/src/config/sessionStore.js new file mode 100644 index 0000000..c1c15ba --- /dev/null +++ b/src/config/sessionStore.js @@ -0,0 +1,136 @@ +const Database = require('better-sqlite3'); +const session = require('express-session'); +const path = require('path'); +const fs = require('fs'); + +let db = null; + +class SQLiteSessionStore extends session.Store { + constructor(options = {}) { + super(options); + const dbDir = path.join(process.cwd(), 'data'); + const dbPath = path.join(dbDir, 'localping.db'); + + // Ensure data directory exists + if (!fs.existsSync(dbDir)) { + fs.mkdirSync(dbDir, { recursive: true }); + } + + db = new Database(dbPath); + db.pragma('foreign_keys = ON'); + + // Create sessions table if it doesn't exist + db.exec(` + CREATE TABLE IF NOT EXISTS sessions ( + sid TEXT PRIMARY KEY, + sess TEXT NOT NULL, + expire INTEGER NOT NULL + ) + `); + + // Create index on expire for cleanup + db.exec(` + CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire) + `); + + // Clean up expired sessions periodically (every hour) + setInterval(() => { + this.cleanup(); + }, 60 * 60 * 1000); + } + + get(sid, callback) { + try { + const stmt = db.prepare('SELECT sess FROM sessions WHERE sid = ? AND expire > ?'); + const row = stmt.get(sid, Date.now()); + + if (row) { + callback(null, JSON.parse(row.sess)); + } else { + callback(null, null); + } + } catch (error) { + callback(error); + } + } + + set(sid, sess, callback) { + try { + const expire = sess.cookie && sess.cookie.expires + ? sess.cookie.expires.getTime() + : Date.now() + (24 * 60 * 60 * 1000); // Default 24 hours + + const stmt = db.prepare('INSERT OR REPLACE INTO sessions (sid, sess, expire) VALUES (?, ?, ?)'); + stmt.run(sid, JSON.stringify(sess), expire); + callback(null); + } catch (error) { + callback(error); + } + } + + destroy(sid, callback) { + try { + const stmt = db.prepare('DELETE FROM sessions WHERE sid = ?'); + stmt.run(sid); + callback(null); + } catch (error) { + callback(error); + } + } + + all(callback) { + try { + const stmt = db.prepare('SELECT sess FROM sessions WHERE expire > ?'); + const rows = stmt.all(Date.now()); + const sessions = rows.map(row => JSON.parse(row.sess)); + callback(null, sessions); + } catch (error) { + callback(error); + } + } + + length(callback) { + try { + const stmt = db.prepare('SELECT COUNT(*) as count FROM sessions WHERE expire > ?'); + const row = stmt.get(Date.now()); + callback(null, row ? row.count : 0); + } catch (error) { + callback(error); + } + } + + clear(callback) { + try { + db.exec('DELETE FROM sessions'); + callback(null); + } catch (error) { + callback(error); + } + } + + touch(sid, sess, callback) { + try { + const expire = sess.cookie && sess.cookie.expires + ? sess.cookie.expires.getTime() + : Date.now() + (24 * 60 * 60 * 1000); + + const stmt = db.prepare('UPDATE sessions SET sess = ?, expire = ? WHERE sid = ?'); + stmt.run(JSON.stringify(sess), expire, sid); + callback(null); + } catch (error) { + callback(error); + } + } + + cleanup() { + try { + const stmt = db.prepare('DELETE FROM sessions WHERE expire < ?'); + stmt.run(Date.now()); + } catch (error) { + console.error('Error cleaning up sessions:', error); + } + } +} + +module.exports = SQLiteSessionStore; + diff --git a/src/electron/main.js b/src/electron/main.js new file mode 100644 index 0000000..687835c --- /dev/null +++ b/src/electron/main.js @@ -0,0 +1,99 @@ +const { app, BrowserWindow, Menu, ipcMain } = require('electron'); +const path = require('path'); +const isDev = require('electron-is-dev'); + +let mainWindow; + +function createWindow() { + mainWindow = new BrowserWindow({ + width: 1400, + height: 900, + minWidth: 800, + minHeight: 600, + webPreferences: { + preload: path.join(__dirname, 'preload.js'), + contextIsolation: true, + enableRemoteModule: false, + nodeIntegration: false, + }, + }); + + const startURL = isDev + ? 'http://localhost:3001/admin' + : `file://${path.join(__dirname, '../views/admin/index.ejs')}`; + + mainWindow.loadURL(startURL); + + if (isDev) { + mainWindow.webContents.openDevTools(); + } + + mainWindow.on('closed', () => { + mainWindow = null; + }); +} + +// Create application menu +function createMenu() { + const template = [ + { + label: 'File', + submenu: [ + { + label: 'Exit', + accelerator: 'CmdOrCtrl+Q', + click: () => { + app.quit(); + }, + }, + ], + }, + { + label: 'View', + submenu: [ + { + label: 'Reload', + accelerator: 'CmdOrCtrl+R', + click: () => { + mainWindow.webContents.reload(); + }, + }, + { + label: 'Dev Tools', + accelerator: 'CmdOrCtrl+Shift+I', + click: () => { + mainWindow.webContents.toggleDevTools(); + }, + }, + ], + }, + ]; + + const menu = Menu.buildFromTemplate(template); + Menu.setApplicationMenu(menu); +} + +app.on('ready', () => { + createWindow(); + createMenu(); +}); + +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { + app.quit(); + } +}); + +app.on('activate', () => { + if (mainWindow === null) { + createWindow(); + } +}); + +// IPC handlers +ipcMain.handle('get-status', async (event) => { + // Implementation for getting status from API + return { status: 'ok' }; +}); + +module.exports = mainWindow; diff --git a/src/electron/preload.js b/src/electron/preload.js new file mode 100644 index 0000000..91f775e --- /dev/null +++ b/src/electron/preload.js @@ -0,0 +1,5 @@ +const { contextBridge, ipcMain } = require('electron'); + +contextBridge.exposeInMainWorld('api', { + getStatus: () => ipcMain.invoke('get-status'), +}); diff --git a/src/middleware/auth.js b/src/middleware/auth.js new file mode 100644 index 0000000..4bc8a35 --- /dev/null +++ b/src/middleware/auth.js @@ -0,0 +1,191 @@ +const chalk = require('../utils/colors'); + +/** + * API Key Authentication Middleware + * Checks for valid API key in Authorization header or X-API-Key header + */ +function apiKeyAuth(req, res, next) { + const apiKey = process.env.ADMIN_API_KEY; + + // If no API key is configured, skip authentication (unsafe - only for local dev) + if (!apiKey) { + console.warn(chalk.yellow('⚠ No ADMIN_API_KEY configured - authentication disabled')); + return next(); + } + + // Check for API key in headers + const authHeader = req.headers.authorization || ''; + const xApiKey = req.headers['x-api-key'] || ''; + + // Support both "Bearer " and direct key + const providedKey = authHeader.replace('Bearer ', '') || xApiKey; + + if (!providedKey || providedKey !== apiKey) { + return res.status(401).json({ + success: false, + error: 'Unauthorized: Invalid or missing API key', + }); + } + + next(); +} + +/** + * Admin Page Authentication Middleware + * Checks for admin password in session or cookie + */ +function adminPageAuth(req, res, next) { + const adminPassword = process.env.ADMIN_PASSWORD; + + // If no admin password is configured, skip authentication (shouldn't happen after setup) + if (!adminPassword || !adminPassword.trim()) { + console.warn(chalk.yellow('⚠ No ADMIN_PASSWORD configured - admin page authentication disabled')); + return next(); + } + + // Allow login page and login POST endpoint without authentication + if (req.path === '/login' || (req.method === 'POST' && req.path === '/login')) { + return next(); + } + + // Check if user has valid admin session + // Session expiration is handled automatically by the session store and cookie maxAge + if (req.session && req.session.adminAuthenticated) { + return next(); + } + + // Not authenticated - redirect to login + if (req.headers.accept && req.headers.accept.includes('application/json')) { + return res.status(401).json({ + success: false, + error: 'Unauthorized: Admin authentication required', + }); + } + + // For page requests, redirect to login + res.redirect('/admin/login'); +} + +/** + * Rate Limiting Middleware + * Prevents brute force attacks on API endpoints + */ +function createRateLimiter(windowMs = 15 * 60 * 1000, maxRequests = 100) { + const requests = new Map(); + + return (req, res, next) => { + const ip = req.ip || req.connection.remoteAddress; + const now = Date.now(); + + // Clean old entries + if (!requests.has(ip)) { + requests.set(ip, []); + } + + const userRequests = requests.get(ip); + + // Remove requests outside the window + const recentRequests = userRequests.filter((time) => now - time < windowMs); + requests.set(ip, recentRequests); + + // Check if over limit + if (recentRequests.length >= maxRequests) { + return res.status(429).json({ + success: false, + error: 'Too many requests, please try again later', + }); + } + + // Record this request + recentRequests.push(now); + next(); + }; +} + +/** + * Input Validation Middleware + * Validates that required fields are present and valid + * For PUT requests, allows partial updates (only validates provided fields) + */ +function validateTargetInput(req, res, next) { + const { name, host, protocol, port, interval } = req.body; + const isUpdate = req.method === 'PUT'; + + const errors = []; + + // For PUT requests, only validate fields that are provided + // For POST requests, validate all required fields + if (!isUpdate) { + // Validate name (required for POST) + if (!name || typeof name !== 'string' || name.trim().length === 0) { + errors.push('Target name is required and must be a non-empty string'); + } + + // Validate host (required for POST) + if (!host || typeof host !== 'string' || host.trim().length === 0) { + errors.push('Host is required and must be a non-empty string'); + } + + // Validate protocol (required for POST) + const validProtocols = ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS']; + if (!protocol || !validProtocols.includes(protocol.toUpperCase())) { + errors.push(`Protocol must be one of: ${validProtocols.join(', ')}`); + } + } else { + // For PUT requests, only validate provided fields + // Validate name if provided + if (name !== undefined) { + if (typeof name !== 'string' || name.trim().length === 0) { + errors.push('Target name must be a non-empty string'); + } + } + + // Validate host if provided + if (host !== undefined) { + if (typeof host !== 'string' || host.trim().length === 0) { + errors.push('Host must be a non-empty string'); + } + } + + // Validate protocol if provided + if (protocol !== undefined) { + const validProtocols = ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS']; + if (!validProtocols.includes(protocol.toUpperCase())) { + errors.push(`Protocol must be one of: ${validProtocols.join(', ')}`); + } + } + } + + // Validate port if provided (null means no custom port, which is valid) + if (port !== undefined && port !== null) { + const portNum = parseInt(port, 10); + if (isNaN(portNum) || portNum < 1 || portNum > 65535) { + errors.push('Port must be a number between 1 and 65535'); + } + } + + // Validate interval if provided (null means use default, which is valid) + if (interval !== undefined && interval !== null) { + const intervalNum = parseInt(interval, 10); + if (isNaN(intervalNum) || intervalNum < 5 || intervalNum > 3600) { + errors.push('Interval must be a number between 5 and 3600 seconds'); + } + } + + // If there are errors, return them + if (errors.length > 0) { + return res.status(400).json({ + success: false, + errors: errors, + }); + } + + next(); +} + +module.exports = { + apiKeyAuth, + adminPageAuth, + createRateLimiter, + validateTargetInput, +}; diff --git a/src/middleware/setupCheck.js b/src/middleware/setupCheck.js new file mode 100644 index 0000000..0fb65c3 --- /dev/null +++ b/src/middleware/setupCheck.js @@ -0,0 +1,42 @@ +/** + * Setup Check Middleware + * Checks if LocalPing has been configured (admin password set) + * Redirects to setup wizard if not configured + */ + +function isSetupComplete() { + const adminPassword = process.env.ADMIN_PASSWORD; + return !!(adminPassword && adminPassword.trim()); +} + +function setupCheckMiddleware(req, res, next) { + // Allow access to setup routes without checking + if (req.path.startsWith('/setup')) { + return next(); + } + + // Allow static assets + if (req.path.startsWith('/public') || req.path.startsWith('/vendor') || req.path.startsWith('/js') || req.path.startsWith('/css') || req.path.match(/\.(css|js|png|jpg|gif|svg|ico|woff|woff2|ttf|eot)$/)) { + return next(); + } + + // Check if setup is complete + if (!isSetupComplete()) { + // Allow public API access for status pages, but redirect web UI + if (req.path.startsWith('/api/') && req.headers.accept !== 'text/html') { + return next(); + } + + // Redirect web UI to setup + if (req.headers.accept && req.headers.accept.includes('text/html')) { + return res.redirect('/setup'); + } + } + + next(); +} + +module.exports = { + setupCheckMiddleware, + isSetupComplete, +}; diff --git a/src/public/android-icon-192x192.png b/src/public/android-icon-192x192.png new file mode 100644 index 0000000..0f6d43c Binary files /dev/null and b/src/public/android-icon-192x192.png differ diff --git a/src/public/apple-touch-icon.png b/src/public/apple-touch-icon.png new file mode 100644 index 0000000..ca27c42 Binary files /dev/null and b/src/public/apple-touch-icon.png differ diff --git a/src/public/browserconfig.xml b/src/public/browserconfig.xml new file mode 100644 index 0000000..7d453d3 --- /dev/null +++ b/src/public/browserconfig.xml @@ -0,0 +1,2 @@ + +#ffffff diff --git a/src/public/favicon-16x16.png b/src/public/favicon-16x16.png new file mode 100644 index 0000000..a761e90 Binary files /dev/null and b/src/public/favicon-16x16.png differ diff --git a/src/public/favicon-32x32.png b/src/public/favicon-32x32.png new file mode 100644 index 0000000..d94b92d Binary files /dev/null and b/src/public/favicon-32x32.png differ diff --git a/src/public/favicon.ico b/src/public/favicon.ico new file mode 100644 index 0000000..aa818b4 Binary files /dev/null and b/src/public/favicon.ico differ diff --git a/src/public/js/admin-new.js b/src/public/js/admin-new.js new file mode 100644 index 0000000..0821829 --- /dev/null +++ b/src/public/js/admin-new.js @@ -0,0 +1,3304 @@ +let currentMonitorId = null; +let statusChart = null; +let monitorSelectionVersion = 0; +let currentChartPeriod = '24h'; // Default period +let currentStartDate = null; +let currentEndDate = null; + +// Extend each outage to the edges of its bucket so the red fill reads as one +// connected interval between the surrounding response-time segments. +function buildDowntimeSeries(stats, maxValue) { + const downBuckets = stats.map(stat => Number(stat.successfulPings || 0) === 0); + return downBuckets.map((isDown, index) => ( + isDown || downBuckets[index - 1] || downBuckets[index + 1] ? maxValue : null + )); +} + +// Keep the graph visually minimal while retaining useful hover details. The +// downtime series has bridge points around outages for a continuous fill; +// those points are filtered out of the tooltip via the chart status map. +function buildGraphTooltipOptions() { + return { + enabled: true, + mode: 'index', + intersect: false, + displayColors: false, + backgroundColor: 'rgba(15, 23, 42, 0.96)', + titleColor: '#f8fafc', + bodyColor: '#e2e8f0', + borderColor: 'rgba(148, 163, 184, 0.25)', + borderWidth: 1, + callbacks: { + title: tooltipItems => tooltipItems[0]?.label || '', + label: context => { + if (context.datasetIndex === 1) return 'πŸ”΄ Service Down'; + const responseTime = Number(context.raw); + return Number.isFinite(responseTime) ? `${Math.round(responseTime)} ms` : ''; + }, + }, + filter: context => { + if (context.datasetIndex === 0) { + return context.raw !== null && context.raw !== undefined; + } + const downtimeAtIndex = context.chart?._downtimeAtIndex || []; + return Boolean(downtimeAtIndex[context.dataIndex]) + && context.raw !== null + && context.raw !== undefined; + }, + }; +} + +// Map URL paths to tab names +const urlToTabMap = { + '/admin': 'monitors', + '/admin/incidents': 'incidents', + '/admin/events': 'event-rules', + '/admin/blogs': 'posts', + '/admin/visibility': 'visibility', + '/admin/settings': 'settings', + '/admin/backup': 'backup' +}; + +// Map tab names to URLs +const tabToUrlMap = { + 'monitors': '/admin', + 'incidents': '/admin/incidents', + 'event-rules': '/admin/events', + 'posts': '/admin/blogs', + 'visibility': '/admin/visibility', + 'settings': '/admin/settings', + 'backup': '/admin/backup' +}; + +// Get current tab from URL +function getCurrentTabFromUrl() { + const path = window.location.pathname; + return urlToTabMap[path] || 'monitors'; +} + +// Tab switching with URL navigation +function switchTab(tabName, eventElement) { + if (tabName !== 'monitors') { + closeMobileMonitorView(); + } + + // Update URL without page reload + const url = tabToUrlMap[tabName] || '/admin'; + window.history.pushState({ tab: tabName }, '', url); + + // Hide all tabs + document.querySelectorAll('.tab-content').forEach(tab => { + tab.classList.remove('active'); + }); + + // Remove active class from all buttons + document.querySelectorAll('.tab-button').forEach(btn => { + btn.classList.remove('active'); + }); + + // Show selected tab + const tabElement = document.getElementById(tabName); + if (tabElement) { + tabElement.classList.add('active'); + } + + // Set active button - find by href + document.querySelectorAll('.tab-button').forEach(btn => { + if (btn.getAttribute('href') === url) { + btn.classList.add('active'); + } + }); + + // Load tab-specific data + if (tabName === 'monitors') { + loadMonitors(); + } else if (tabName === 'incidents') { + loadIncidents(); + } else if (tabName === 'event-rules') { + loadEventRules(); + } else if (tabName === 'posts') { + loadPosts(); + } else if (tabName === 'visibility') { + loadVisibility(); + } else if (tabName === 'settings') { + loadPublicUISettings(); + } else if (tabName === 'backup') { + // Backup tab doesn't need to load anything on switch + } +} + +// Initialize tab on page load +document.addEventListener('DOMContentLoaded', () => { + const currentTab = getCurrentTabFromUrl(); + switchTab(currentTab); +}); + +// Handle browser back/forward buttons +window.addEventListener('popstate', (event) => { + const currentTab = getCurrentTabFromUrl(); + switchTab(currentTab); +}); + +// Handle tab link clicks - prevent default and use pushState for smooth navigation +function handleTabClick(event, tabName) { + event.preventDefault(); + switchTab(tabName); +} + +// Load monitors list +async function loadMonitors() { + try { + const response = await axios.get('/admin/api/dashboard'); + const targets = response.data.dashboard.targets; + + const monitorList = document.getElementById('monitorList'); + monitorList.innerHTML = ''; + + if (targets.length === 0) { + monitorList.innerHTML = '

No monitors yet

'; + return; + } + + targets.forEach(target => { + const status = target.currentStatus === 'up' ? 'up' : 'down'; + const statusText = status === 'up' ? 'Up' : 'Down'; + + // Get favicon - prefer appIcon, then favicon from API, then try to get from appUrl + let faviconHtml = ''; + if (target.appIcon) { + // Proxy the icon URL + const proxyUrl = `/admin/api/proxy-icon?url=${encodeURIComponent(target.appIcon)}`; + faviconHtml = `${target.name}`; + } else if (target.favicon) { + // Use cached favicon from API - if it's base64, use directly, otherwise proxy + if (target.favicon.startsWith('data:')) { + faviconHtml = `${target.name}`; + } else { + const proxyUrl = `/admin/api/proxy-icon?url=${encodeURIComponent(target.favicon)}`; + faviconHtml = `${target.name}`; + } + } else if (target.appUrl) { + // Try to get favicon from appUrl + const faviconUrl = getFaviconUrl(target.appUrl); + if (faviconUrl) { + const proxyUrl = `/admin/api/proxy-icon?url=${encodeURIComponent(faviconUrl)}`; + faviconHtml = `${target.name}`; + } + } + + const card = document.createElement('div'); + card.className = 'monitor-card'; + card.dataset.monitorId = target._id; + card.innerHTML = ` +
+ ${faviconHtml ? `
${faviconHtml}
` : ''} +
+

${target.name}

+

${target.host}

+
+ + + ${statusText} + +
+ `; + card.setAttribute('role', 'button'); + card.tabIndex = 0; + card.onclick = () => selectMonitor(target, { openMobile: true }); + card.onkeydown = (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + selectMonitor(target, { openMobile: true }); + } + }; + + if (currentMonitorId === target._id) { + card.classList.add('selected'); + } + + monitorList.appendChild(card); + }); + + // Auto-select first monitor if none is selected + if (currentMonitorId === null && targets.length > 0) { + // Keep the monitor list as the mobile landing view. A detail surface + // opens only after an explicit card activation. + selectMonitor(targets[0], { openMobile: false }); + } + } catch (error) { + console.error('Error loading monitors:', error); + showNotification('Error loading monitors', 'error'); + } +} + +function isCurrentMonitorSelection(targetId, selectionVersion = null) { + return currentMonitorId === targetId + && (selectionVersion === null || selectionVersion === monitorSelectionVersion); +} + +function setMonitorActionVisibility(visible) { + ['editMonitorBtn', 'cloneMonitorBtn', 'clearPingDataBtn'].forEach((id) => { + const button = document.getElementById(id); + if (button) button.style.display = visible ? 'inline-flex' : 'none'; + }); +} + +function setMonitorLoadingState(isLoading) { + const skeleton = document.getElementById('monitorDetailSkeleton'); + const content = document.getElementById('monitorDetailContent'); + if (skeleton) skeleton.classList.toggle('hidden', !isLoading); + if (content) content.classList.toggle('hidden', isLoading); +} + +function isMobileMonitorViewport() { + return typeof window !== 'undefined' + && typeof window.matchMedia === 'function' + && window.matchMedia('(max-width: 1023px)').matches; +} + +function openMobileMonitorView() { + if (!isMobileMonitorViewport()) return; + + const details = document.getElementById('monitorDetails'); + if (!details) return; + + document.body.classList.add('monitor-detail-open'); + const backButton = document.getElementById('mobileMonitorBackBtn'); + if (backButton) { + // Focus the escape hatch without scrolling the underlying document. + setTimeout(() => backButton.focus({ preventScroll: true }), 0); + } +} + +function closeMobileMonitorView() { + if (typeof document === 'undefined') return; + const shouldRestoreFocus = document.activeElement?.id === 'mobileMonitorBackBtn'; + document.body.classList.remove('monitor-detail-open'); + + if (shouldRestoreFocus && currentMonitorId) { + const selectedCard = Array.from(document.querySelectorAll('.monitor-card')) + .find(card => card.dataset.monitorId === currentMonitorId); + if (selectedCard) setTimeout(() => selectedCard.focus({ preventScroll: true }), 0); + } +} + +if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { + window.addEventListener('resize', () => { + if (!isMobileMonitorViewport()) closeMobileMonitorView(); + }); +} + +function showMonitorSummary() { + const summary = document.getElementById('monitorSummaryPane'); + const editor = document.getElementById('monitorEditor'); + const content = document.getElementById('monitorDetailContent'); + if (content) content.classList.remove('hidden'); + if (summary) summary.classList.remove('hidden'); + if (editor) editor.classList.add('hidden'); +} + +function populateMonitorForm(fullMonitor) { + const values = { + editName: fullMonitor.name || '', + editHost: fullMonitor.host || '', + editProtocol: fullMonitor.protocol || 'ICMP', + editPort: fullMonitor.port || '', + editInterval: fullMonitor.interval || 60, + editGroup: fullMonitor.group || '', + editAppUrl: fullMonitor.appUrl || '', + editAppIcon: fullMonitor.appIcon || '', + editRetries: fullMonitor.retries || 0, + editRetryInterval: fullMonitor.retryInterval || 5, + editHttpMethod: fullMonitor.httpMethod || 'GET', + editTimeout: fullMonitor.timeout || 30, + editStatusCodes: fullMonitor.statusCodes || '200-299', + editMaxRedirects: fullMonitor.maxRedirects || 5, + editPosition: fullMonitor.position || 0, + editQuickCommands: (fullMonitor.quickCommands || []).join(', '), + }; + + Object.entries(values).forEach(([id, value]) => { + const element = document.getElementById(id); + if (element) element.value = value; + }); + + const checkedValues = { + editEnabled: fullMonitor.enabled !== false, + editIgnoreSsl: fullMonitor.ignoreSsl === true, + editUpsideDown: fullMonitor.upsideDown === true, + editImportant: fullMonitor.important === true, + editPublicVisible: fullMonitor.publicVisible !== false, + }; + Object.entries(checkedValues).forEach(([id, checked]) => { + const element = document.getElementById(id); + if (element) element.checked = checked; + }); + + const authMethod = document.getElementById('editAuthMethod'); + const authUsername = document.getElementById('editAuthUsername'); + const authPassword = document.getElementById('editAuthPassword'); + const authToken = document.getElementById('editAuthToken'); + if (authMethod) authMethod.value = 'none'; + if (authUsername) authUsername.value = ''; + if (authPassword) authPassword.value = ''; + if (authToken) authToken.value = ''; + + let auth = fullMonitor.auth; + if (typeof auth === 'string') { + try { auth = JSON.parse(auth); } catch (error) { auth = null; } + } + if (auth?.type === 'basic') { + if (authMethod) authMethod.value = 'basic'; + if (authUsername) authUsername.value = auth.username || ''; + if (authPassword) authPassword.value = auth.password || ''; + } else if (auth?.type === 'bearer') { + if (authMethod) authMethod.value = 'bearer'; + if (authToken) authToken.value = auth.token || ''; + } + + updateProtocolSettings(); + updateAuthFields(); + attachFormListeners(); +} + +function resetMonitorWorkspace() { + monitorSelectionVersion += 1; + currentMonitorId = null; + closeMobileMonitorView(); + setMonitorLoadingState(false); + setMonitorActionVisibility(false); + + const details = document.getElementById('monitorDetails'); + const emptyState = document.getElementById('emptyState'); + const summary = document.getElementById('monitorSummaryPane'); + const editor = document.getElementById('monitorEditor'); + if (details) details.classList.add('hidden'); + if (emptyState) emptyState.classList.remove('hidden'); + if (summary) summary.classList.remove('hidden'); + if (editor) editor.classList.add('hidden'); + + const form = document.getElementById('editForm'); + if (form) form.reset(); + document.querySelectorAll('.monitor-card').forEach(card => card.classList.remove('selected')); +} + +// Select monitor and show details +async function selectMonitor(monitor, options = {}) { + if (!monitor?._id) return; + + const openMobile = options.openMobile !== false; + + const selectionVersion = ++monitorSelectionVersion; + currentMonitorId = monitor._id; + + const details = document.getElementById('monitorDetails'); + const emptyState = document.getElementById('emptyState'); + const summary = document.getElementById('monitorSummaryPane'); + const editor = document.getElementById('monitorEditor'); + if (emptyState) emptyState.classList.add('hidden'); + if (details) details.classList.remove('hidden'); + if (summary) summary.classList.remove('hidden'); + if (editor) editor.classList.add('hidden'); + setMonitorActionVisibility(false); + setMonitorLoadingState(true); + if (openMobile) { + openMobileMonitorView(); + } else { + closeMobileMonitorView(); + } + + const mobileToolbarLabel = document.getElementById('mobileMonitorToolbarLabel'); + if (mobileToolbarLabel) mobileToolbarLabel.textContent = monitor.name || 'Monitor details'; + + // Highlight the selection immediately while the detail request is in flight. + document.querySelectorAll('.monitor-card').forEach(card => { + card.classList.toggle('selected', card.dataset.monitorId === monitor._id); + }); + + try { + const response = await axios.get(`/admin/api/targets/${monitor._id}`); + if (!isCurrentMonitorSelection(monitor._id, selectionVersion)) return; + const fullMonitor = response.data.target; + + populateMonitorForm(fullMonitor); + document.getElementById('monitorName').textContent = fullMonitor.name || monitor.name || 'Monitor'; + const mobileToolbarLabel = document.getElementById('mobileMonitorToolbarLabel'); + if (mobileToolbarLabel) mobileToolbarLabel.textContent = fullMonitor.name || monitor.name || 'Monitor details'; + + const status = fullMonitor.currentStatus === 'up' ? 'Up' : 'Down'; + const statusColor = fullMonitor.currentStatus === 'up' ? 'text-green-400' : 'text-red-400'; + document.getElementById('monitorStatus').textContent = status; + document.getElementById('monitorStatus').className = statusColor; + + // Keep the skeleton visible until both the monitor and its chart are ready. + await loadMonitorStatistics(fullMonitor._id, fullMonitor.timeout || 30, selectionVersion); + if (!isCurrentMonitorSelection(monitor._id, selectionVersion)) return; + + setMonitorLoadingState(false); + setMonitorActionVisibility(true); + } catch (error) { + if (!isCurrentMonitorSelection(monitor._id, selectionVersion)) return; + console.error('Error loading monitor details:', error); + setMonitorLoadingState(false); + showMonitorSummary(); + showNotification('Error loading monitor details', 'error'); + } +} + +// Switch chart period (matching public UI style) +async function switchChartPeriod(period) { + currentChartPeriod = period; + + // Update button states + const buttons = document.querySelectorAll('.period-btn'); + buttons.forEach(btn => { + if (btn.dataset.period === period) { + btn.className = 'period-btn px-4 py-2 rounded-lg text-xs font-medium bg-gradient-to-r from-cyan-600 to-cyan-500 text-white shadow-lg shadow-cyan-500/30 transition-all duration-200 border border-cyan-500/50'; + } else { + btn.className = 'period-btn px-4 py-2 rounded-lg text-xs font-medium bg-slate-700/50 hover:bg-slate-600/70 text-slate-300 transition-all duration-200 border border-slate-600/50'; + } + }); + + if (currentMonitorId) { + // Statistics endpoint now includes target details, so we only need one call + await loadMonitorStatistics(currentMonitorId, 30); + } +} + +// Apply custom date range +function applyCustomRange() { + const startDate = document.getElementById('startDate').value; + const endDate = document.getElementById('endDate').value; + + if (!startDate || !endDate) { + showNotification('Please select both start and end dates', 'error'); + return; + } + + if (new Date(startDate) > new Date(endDate)) { + showNotification('Start date must be before end date', 'error'); + return; + } + + currentStartDate = startDate; + currentEndDate = endDate; + currentTimePeriod = null; + + if (currentMonitorId) { + // Statistics endpoint now includes target details, so we only need one call + loadMonitorStatistics(currentMonitorId, 30); + } +} + +// Navigate time period (previous/next) +function navigateTimePeriod(direction) { + if (currentTimePeriod) { + // For fixed periods, shift the window + // This is a simple implementation - you could make it more sophisticated + showNotification('Time navigation for fixed periods coming soon', 'error'); + } else if (currentStartDate && currentEndDate) { + // For custom ranges, shift by the range duration + const start = new Date(currentStartDate); + const end = new Date(currentEndDate); + const duration = end - start; + + if (direction < 0) { + // Previous period + end.setTime(start.getTime() - 1); + start.setTime(start.getTime() - duration); + } else { + // Next period + start.setTime(end.getTime() + 1); + end.setTime(start.getTime() + duration); + } + + currentStartDate = start.toISOString().split('T')[0]; + currentEndDate = end.toISOString().split('T')[0]; + + document.getElementById('startDate').value = currentStartDate; + document.getElementById('endDate').value = currentEndDate; + + if (currentMonitorId) { + // Statistics endpoint now includes target details, so we only need one call + loadMonitorStatistics(currentMonitorId, 30); + } + } +} + +// Load monitor statistics and draw chart +async function loadMonitorStatistics(targetId, timeout = 30, selectionVersion = null) { + try { + // Determine period for chart (default to 24h if not set) + const period = currentChartPeriod || '24h'; + + // Load all data in one API call (target + statistics + uptime) + const statsResponse = await axios.get(`/admin/api/targets/${targetId}/statistics?period=${period}`); + if (!isCurrentMonitorSelection(targetId, selectionVersion)) return; + const stats = statsResponse.data.statistics || []; + const uptimeData = statsResponse.data.uptime || {}; + const dailyStats = statsResponse.data.dailyStats || []; + const monitor = statsResponse.data.target || {}; + const isUp = monitor.currentStatus === 'up'; + + const uptime24h = parseFloat(uptimeData['24h']?.uptime || 0); + const uptime30d = parseFloat(uptimeData['30d']?.uptime || 0); + const totalPings = uptimeData['30d']?.totalPings || 0; + const successfulPings = uptimeData['30d']?.successfulPings || 0; + const failedPings = uptimeData['30d']?.failedPings || 0; + + // Generate uptime blocks from daily statistics + if (dailyStats.length > 0) { + generateUptimeBlocksFromDailyStats(dailyStats, 30); + } else { + generateUptimeBlocks(stats); + } + + // Update stats displays + document.getElementById('currentStatusDisplay').textContent = isUp ? 'βœ“ UP' : 'βœ— DOWN'; + document.getElementById('currentStatusDisplay').className = `text-base font-bold leading-tight whitespace-nowrap ${isUp ? 'text-green-400' : 'text-red-400'}`; + document.getElementById('uptime24hDisplay').textContent = `${uptime24h.toFixed(2)}%`; + document.getElementById('uptime30dDisplay').textContent = `${uptime30d.toFixed(2)}%`; + document.getElementById('protocolDisplay').textContent = monitor.protocol || '--'; + document.getElementById('totalPingsDisplay').textContent = totalPings; + document.getElementById('successfulPingsDisplay').textContent = successfulPings; + document.getElementById('failedPingsDisplay').textContent = failedPings; + + // Update legacy displays + document.getElementById('monitorUptime').textContent = `${uptime24h.toFixed(2)}%`; + document.getElementById('monitorStatus').textContent = isUp ? 'Up' : 'Down'; + document.getElementById('monitorStatus').className = isUp ? 'text-green-400' : 'text-red-400'; + + const latestStat = stats.length > 0 ? stats[stats.length - 1] : null; + const currentPing = latestStat?.lastResponseTime || 0; + document.getElementById('monitorPing').textContent = currentPing > 0 ? `${Math.round(currentPing)} ms` : '--'; + + // Calculate average ping + let totalResponseTime = 0; + let responseTimeCount = 0; + stats.forEach(stat => { + if (stat.avgResponseTime && stat.totalPings) { + totalResponseTime += stat.avgResponseTime * stat.totalPings; + responseTimeCount += stat.totalPings; + } + }); + const avgPing = responseTimeCount > 0 ? totalResponseTime / responseTimeCount : 0; + document.getElementById('monitorAvgPing').textContent = avgPing > 0 ? `${Math.round(avgPing)} ms` : '--'; + + // Uptime blocks are generated from daily stats above + + // Draw chart (matching public UI style) + drawStatusChart(stats, null, timeout * 1000); + } catch (error) { + if (!isCurrentMonitorSelection(targetId, selectionVersion)) return; + console.error('Error loading statistics:', error); + document.getElementById('monitorUptime').textContent = '--'; + document.getElementById('monitorPing').textContent = '--'; + document.getElementById('monitorAvgPing').textContent = '--'; + document.getElementById('uptimeBlocksLabel').textContent = 'Error loading data'; + drawStatusChart([], null, 30000); + generateUptimeBlocks([]); + } +} + +// Generate uptime block indicator from daily statistics (accurate) +function generateUptimeBlocksFromDailyStats(dailyStats, days = 30) { + const blocksContainer = document.getElementById('uptimeBlocks'); + const labelElement = document.getElementById('uptimeBlocksLabel'); + const titleElement = document.getElementById('uptimeBlocksTitle'); + + blocksContainer.innerHTML = ''; + + // Create a map of date -> stats for quick lookup + const statsMap = new Map(); + dailyStats.forEach(stat => { + const dateKey = new Date(stat.date).toISOString().split('T')[0]; + statsMap.set(dateKey, stat); + }); + + const now = new Date(); + const blocks = []; + let upCount = 0; + let totalCount = 0; + + for (let i = days - 1; i >= 0; i--) { + const dayStart = new Date(now); + dayStart.setDate(now.getDate() - i); + dayStart.setHours(0, 0, 0, 0); + const dateKey = dayStart.toISOString().split('T')[0]; + + const stat = statsMap.get(dateKey); + let isUp = null; + + if (stat) { + const totalPings = stat.totalPings || 0; + const successfulPings = stat.successfulPings || 0; + // Day is considered "up" if >= 50% of pings were successful + isUp = totalPings === 0 ? null : (successfulPings / totalPings) >= 0.5; + } else if (dayStart > now) { + isUp = null; // Future day + } else { + isUp = null; // No data for past day + } + + blocks.push({ + period: dayStart, + isUp: isUp + }); + + if (isUp === true) upCount++; + if (isUp !== null) totalCount++; + } + + // Generate blocks + blocks.forEach((block) => { + const blockEl = document.createElement('div'); + blockEl.className = 'uptime-block'; + + const titleText = block.period.toLocaleDateString([], { month: 'short', day: 'numeric' }); + + if (block.isUp === null) { + blockEl.classList.add('unknown'); + blockEl.title = `${titleText} - No data`; + } else if (block.isUp) { + blockEl.classList.add('up'); + blockEl.title = `${titleText} - Up`; + } else { + blockEl.classList.add('down'); + blockEl.title = `${titleText} - Down`; + } + + blocksContainer.appendChild(blockEl); + }); + + // Update label + if (totalCount > 0) { + const uptimePercent = (upCount / totalCount) * 100; + labelElement.textContent = `${upCount}/${totalCount} days up (${uptimePercent.toFixed(1)}%)`; + } else { + labelElement.textContent = 'No data available'; + } + titleElement.textContent = `${days}-Day Uptime`; +} + +// Generate uptime block indicator (fallback - uses chart stats) +function generateUptimeBlocks(stats) { + const blocksContainer = document.getElementById('uptimeBlocks'); + const labelElement = document.getElementById('uptimeBlocksLabel'); + const titleElement = document.getElementById('uptimeBlocksTitle'); + + blocksContainer.innerHTML = ''; + + if (stats.length === 0) { + labelElement.textContent = 'No data available'; + titleElement.textContent = 'Uptime Overview'; + return; + } + + // Show last 30 days of uptime blocks + const now = new Date(); + const blocks = []; + let upCount = 0; + let totalCount = 0; + + for (let i = 29; i >= 0; i--) { + const dayStart = new Date(now); + dayStart.setDate(now.getDate() - i); + dayStart.setHours(0, 0, 0, 0); + const dayEnd = new Date(dayStart); + dayEnd.setDate(dayStart.getDate() + 1); + + // Find statistics for this day + const dayStats = stats.filter(stat => { + const statDate = new Date(stat.date); + return statDate >= dayStart && statDate < dayEnd; + }); + + let isUp = true; + if (dayStats.length > 0) { + const totalPings = dayStats.reduce((sum, s) => sum + (s.totalPings || 0), 0); + const successfulPings = dayStats.reduce((sum, s) => sum + (s.successfulPings || 0), 0); + isUp = totalPings === 0 || (successfulPings / totalPings) >= 0.5; + } else { + if (dayStart > now) { + isUp = null; // Future day + } else { + isUp = null; // No data + } + } + + blocks.push({ + period: dayStart, + isUp: isUp + }); + + if (isUp === true) upCount++; + if (isUp !== null) totalCount++; + } + + // Generate blocks + blocks.forEach((block) => { + const blockEl = document.createElement('div'); + blockEl.className = 'uptime-block'; + + const titleText = block.period.toLocaleDateString([], { month: 'short', day: 'numeric' }); + + if (block.isUp === null) { + blockEl.classList.add('unknown'); + blockEl.title = `${titleText} - No data`; + } else if (block.isUp) { + blockEl.classList.add('up'); + blockEl.title = `${titleText} - Up`; + } else { + blockEl.classList.add('down'); + blockEl.title = `${titleText} - Down`; + } + + blocksContainer.appendChild(blockEl); + }); + + // Update label + if (totalCount > 0) { + const uptimePercent = (upCount / totalCount) * 100; + labelElement.textContent = `${upCount}/${totalCount} days up (${uptimePercent.toFixed(1)}%)`; + } else { + labelElement.textContent = 'No data available'; + } + titleElement.textContent = '30-Day Uptime'; +} + +// Draw status chart with real data (matching public UI style) +// Data is displayed chronologically: left (oldest) to right (newest) +function drawStatusChart(stats, testResult = null, timeoutMs = 30000) { + const ctx = document.getElementById('statusChart').getContext('2d'); + + // Destroy existing chart + if (statusChart) { + statusChart.destroy(); + } + + if (stats.length === 0 && !testResult) { + statusChart = new Chart(ctx, { + type: 'line', + data: { labels: [], datasets: [] }, + options: { + responsive: true, + maintainAspectRatio: false, + plugins: { + legend: { display: false }, + tooltip: { enabled: false } + } + } + }); + return; + } + + // Parse and sort stats by date (oldest first = left to right) + const sortedStats = [...stats] + .map(stat => ({ + ...stat, + dateObj: new Date(stat.date) // Parse date once + })) + .sort((a, b) => a.dateObj.getTime() - b.dateObj.getTime()); // Sort chronologically (oldest first) + + // Generate labels based on period (formatted for readability) + const labels = sortedStats.map(stat => { + const date = stat.dateObj; + if (currentChartPeriod === '1h') { + // 1H: Show time only (HH:MM) + return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); + } else if (currentChartPeriod === '24h') { + // 24H: Show day and time (Mon 15, 14:30) + return date.toLocaleString([], { weekday: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + } else if (currentChartPeriod === '7d') { + // 7D: Show date and time (Nov 15, 14:30) + return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + } else if (currentChartPeriod === '30d') { + // 30D: Show date only (Nov 15) + return date.toLocaleString([], { month: 'short', day: 'numeric' }); + } else { + // Default: Show date and time + return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + } + }); + + const responseTimeData = []; + + sortedStats.forEach(stat => { + // Do not plot response time for an entirely failed bucket. A null value + // creates a real gap in Chart.js when spanGaps is disabled, leaving the + // red downtime series as the only signal for that interval. + const avgResponseTime = stat.avgResponseTime || 0; + const isDown = Number(stat.successfulPings || 0) === 0; + responseTimeData.push(isDown ? null : Math.round(avgResponseTime)); + + }); + + // Calculate max response time for scaling downtime indicator + const validResponseTimes = responseTimeData.filter(v => v > 0); + const maxResponseTime = validResponseTimes.length > 0 ? Math.max(...validResponseTimes) : 100; + const downtimeMaxValue = Math.round(Math.max(maxResponseTime * 1.1, 100)); // Add 10% padding, minimum 100, rounded + + // Scale downtime indicator to max Y value + const scaledDownData = buildDowntimeSeries(sortedStats, downtimeMaxValue); + + // The downtime series intentionally includes one bucket on either side of + // an outage to make the red fill meet the response-time line. Keep a + // separate status array so those visual bridge points do not appear as + // false outage values in the hover tooltip. + const downtimeAtIndex = sortedStats.map(stat => Number(stat.successfulPings || 0) === 0); + + // Add test result if provided + if (testResult && sortedStats.length > 0) { + const lastIndex = responseTimeData.length - 1; + if (testResult.success && testResult.responseTime) { + responseTimeData[lastIndex] = Math.round(testResult.responseTime); + scaledDownData[lastIndex] = null; + downtimeAtIndex[lastIndex] = false; + } else { + responseTimeData[lastIndex] = null; + scaledDownData[lastIndex] = downtimeMaxValue; + downtimeAtIndex[lastIndex] = true; + } + } + + statusChart = new Chart(ctx, { + type: 'line', + data: { + labels, + datasets: [ + { + label: 'Response Time (ms)', + data: responseTimeData, + borderColor: '#10b981', + backgroundColor: 'rgba(16, 185, 129, 0.15)', + fill: true, + tension: 0.5, + pointRadius: 0, + pointHoverRadius: 0, + pointHitRadius: 8, + borderWidth: 3, + spanGaps: false, + order: 1, + }, + { + label: 'Downtime', + data: scaledDownData, + borderColor: '#ef4444', + backgroundColor: 'rgba(239, 68, 68, 0.25)', + fill: true, + tension: 0.3, + pointRadius: 0, + pointHoverRadius: 0, + pointHitRadius: 8, + borderWidth: 0, + spanGaps: false, + order: 0, + }, + ], + }, + options: { + responsive: true, + maintainAspectRatio: false, + interaction: { + mode: 'index', + intersect: false, + }, + plugins: { + legend: { + display: false, + }, + tooltip: buildGraphTooltipOptions() + }, + scales: { + y: { + beginAtZero: true, + max: downtimeMaxValue, // Set max to ensure downtime indicator reaches top + grid: { + color: 'rgba(255, 255, 255, 0.08)', + drawBorder: false, + lineWidth: 1 + }, + ticks: { display: false }, + title: { + display: false + } + }, + x: { + type: 'category', + grid: { + color: 'rgba(255, 255, 255, 0.05)', + drawBorder: false + }, + ticks: { display: false }, + // Ensure chronological order (left = oldest, right = newest) + reverse: false + }, + }, + elements: { + point: { + radius: 0, + hoverRadius: 0, + hoverBorderWidth: 0, + } + }, + animation: { + duration: 1000, + easing: 'easeInOutQuart' + } + }, + }); + statusChart._downtimeAtIndex = downtimeAtIndex; +} + +// Update protocol settings visibility +function updateProtocolSettings() { + const protocolElement = getFormElement('editProtocol'); + if (!protocolElement) return; + + const protocol = protocolElement.value; + + const formContainer = protocolElement.closest('form') || document.getElementById('editFormContainer'); + if (!formContainer) return; + + const httpSection = formContainer.querySelector('#httpOptionsSection'); + const authSection = formContainer.querySelector('#authSection'); + + if (httpSection && authSection) { + if (protocol === 'HTTP' || protocol === 'HTTPS') { + httpSection.classList.remove('hidden'); + authSection.classList.remove('hidden'); + } else { + httpSection.classList.add('hidden'); + authSection.classList.add('hidden'); + } + } +} + +// Update auth fields visibility +function updateAuthFields() { + const authMethodElement = getFormElement('editAuthMethod'); + if (!authMethodElement) return; + + const authMethod = authMethodElement.value; + + const formContainer = authMethodElement.closest('form') || document.getElementById('editFormContainer'); + if (!formContainer) return; + + const basicFields = formContainer.querySelector('#basicAuthFields'); + const bearerFields = formContainer.querySelector('#bearerAuthFields'); + + if (basicFields && bearerFields) { + basicFields.classList.add('hidden'); + bearerFields.classList.add('hidden'); + + if (authMethod === 'basic') { + basicFields.classList.remove('hidden'); + } else if (authMethod === 'bearer') { + bearerFields.classList.remove('hidden'); + } + } +} + +// Delete monitor +async function deleteMonitor() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + if (!confirm('Are you sure you want to delete this monitor?')) { + return; + } + + try { + await axios.delete(`/admin/api/targets/${currentMonitorId}`); + showNotification('Monitor deleted successfully', 'success'); + currentMonitorId = null; + cancelEdit(); + await loadMonitors(); + } catch (error) { + console.error('Error deleting monitor:', error); + showNotification(error.response?.data?.error || 'Error deleting monitor', 'error'); + } +} + +// Add new monitor +function addNewMonitor() { + monitorSelectionVersion += 1; + currentMonitorId = null; + setMonitorLoadingState(false); + document.getElementById('monitorDetails')?.classList.remove('hidden'); + document.getElementById('emptyState')?.classList.add('hidden'); + document.getElementById('monitorSummaryPane')?.classList.add('hidden'); + document.getElementById('monitorEditor')?.classList.remove('hidden'); + document.getElementById('monitorEditorTitle').textContent = 'Add new monitor'; + document.getElementById('monitorName').textContent = 'New monitor'; + const mobileToolbarLabel = document.getElementById('mobileMonitorToolbarLabel'); + if (mobileToolbarLabel) mobileToolbarLabel.textContent = 'New monitor'; + openMobileMonitorView(); + + const form = document.getElementById('editForm'); + if (form) form.reset(); + + // Set defaults + const defaults = { + editProtocol: 'ICMP', + editInterval: '60', + editRetries: '0', + editRetryInterval: '5', + editHttpMethod: 'GET', + editTimeout: '30', + editStatusCodes: '200-299', + editMaxRedirects: '5', + editPosition: '0', + editAuthMethod: 'none', + }; + Object.entries(defaults).forEach(([id, value]) => { + const element = document.getElementById(id); + if (element) element.value = value; + }); + ['editEnabled', 'editPublicVisible'].forEach((id) => { + const element = document.getElementById(id); + if (element) element.checked = true; + }); + + // Update protocol settings + updateProtocolSettings(); + updateAuthFields(); + + // Update monitor list selection + document.querySelectorAll('.monitor-card').forEach(card => { + card.classList.remove('selected'); + }); + + // Hide clone and clear ping data buttons for new monitor + const cloneBtn = document.getElementById('cloneMonitorBtn'); + if (cloneBtn) { + cloneBtn.style.display = 'none'; + } + const clearPingDataBtn = document.getElementById('clearPingDataBtn'); + if (clearPingDataBtn) { + clearPingDataBtn.style.display = 'none'; + } + + setTimeout(() => document.getElementById('editName')?.focus(), 0); +} + +// Show clone monitor confirmation modal +function showCloneMonitorConfirm() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + const monitorName = document.getElementById('monitorName')?.textContent || 'Monitor'; + document.getElementById('cloneMonitorName').textContent = monitorName; + + const modal = document.getElementById('cloneMonitorModal'); + modal.classList.add('active'); +} + +// Close clone monitor modal +function closeCloneMonitorModal() { + const modal = document.getElementById('cloneMonitorModal'); + modal.classList.remove('active'); +} + +// Find available clone name +async function findAvailableCloneName(baseName, existingNames) { + let cloneName = `${baseName} (clone)`; + let counter = 1; + + while (existingNames.includes(cloneName)) { + counter++; + cloneName = `${baseName} (clone ${counter})`; + } + + return cloneName; +} + +// Confirm and clone monitor +async function confirmCloneMonitor() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + try { + // Get current monitor data + const response = await axios.get(`/admin/api/targets/${currentMonitorId}`); + const monitor = response.data.target; + + // Get all existing monitor names + const dashboardResponse = await axios.get('/admin/api/dashboard'); + const existingNames = dashboardResponse.data.dashboard.targets.map(t => t.name); + + // Find available clone name + const cloneName = await findAvailableCloneName(monitor.name, existingNames); + + // Prepare clone data (same settings, but disabled and no data points) + const cloneData = { + name: cloneName, + host: monitor.host || '', + protocol: monitor.protocol || 'ICMP', + port: monitor.port || null, + interval: monitor.interval || 60, + enabled: false, // Disabled by default + publicVisible: monitor.publicVisible !== false, + publicShowDetails: monitor.publicShowDetails === true, + group: monitor.group || null, + appUrl: monitor.appUrl || null, + appIcon: monitor.appIcon || null, + retries: monitor.retries || 0, + retryInterval: monitor.retryInterval || 5, + timeout: monitor.timeout || 30, + httpMethod: monitor.httpMethod || 'GET', + statusCodes: monitor.statusCodes || '200-299', + maxRedirects: monitor.maxRedirects || 5, + ignoreSsl: monitor.ignoreSsl || false, + upsideDown: monitor.upsideDown || false, + position: monitor.position || 0, + quickCommands: monitor.quickCommands || [], + auth: monitor.auth || null + }; + + // Create the cloned monitor + const createResponse = await axios.post('/admin/api/targets', cloneData); + const newMonitorId = createResponse.data.targetId; + + // Close modal + closeCloneMonitorModal(); + + // Show success notification + showNotification('Monitor cloned successfully', 'success'); + + // Reload monitors and select the new one + await loadMonitors(); + const newMonitorResponse = await axios.get(`/admin/api/targets/${newMonitorId}`); + await selectMonitor(newMonitorResponse.data.target); + } catch (error) { + console.error('Error cloning monitor:', error); + showNotification(error.response?.data?.error || 'Error cloning monitor', 'error'); + } +} + +// Helper to get form element (works for both desktop, mobile, and modal) +function getFormElement(id) { + return document.getElementById(id); +} + +// Handle edit button click - mobile uses panel, desktop uses modal +function handleEditClick() { + openEditMonitor(); +} + +// Open the inline monitor editor. +function openEditMonitor() { + const details = document.getElementById('monitorDetails'); + const emptyState = document.getElementById('emptyState'); + const summary = document.getElementById('monitorSummaryPane'); + const editor = document.getElementById('monitorEditor'); + if (!editor) return; + + details?.classList.remove('hidden'); + emptyState?.classList.add('hidden'); + summary?.classList.add('hidden'); + editor.classList.remove('hidden'); + + const editorTitle = document.getElementById('monitorEditorTitle'); + if (editorTitle) { + editorTitle.textContent = currentMonitorId + ? `Edit ${document.getElementById('monitorName')?.textContent || 'monitor'}` + : 'Add new monitor'; + } + + attachFormListeners(); + updateProtocolSettings(); + updateAuthFields(); + setTimeout(() => document.getElementById('editName')?.focus(), 0); +} + +// Save monitor +async function saveMonitor() { + const data = { + name: getFormElement('editName')?.value || '', + host: getFormElement('editHost')?.value || '', + protocol: getFormElement('editProtocol')?.value || 'ICMP', + port: getFormElement('editPort')?.value ? parseInt(getFormElement('editPort').value) : null, + interval: parseInt(getFormElement('editInterval')?.value) || 60, + enabled: getFormElement('editEnabled')?.checked !== false, + publicVisible: getFormElement('editPublicVisible')?.checked !== false, + group: getFormElement('editGroup')?.value || null, + appUrl: getFormElement('editAppUrl')?.value || null, + appIcon: getFormElement('editAppIcon')?.value || null, + retries: parseInt(getFormElement('editRetries')?.value) || 0, + retryInterval: parseInt(getFormElement('editRetryInterval')?.value) || 5, + timeout: parseInt(getFormElement('editTimeout')?.value) || 30, + httpMethod: getFormElement('editHttpMethod')?.value || 'GET', + statusCodes: getFormElement('editStatusCodes')?.value || '200-299', + maxRedirects: parseInt(getFormElement('editMaxRedirects')?.value) || 5, + ignoreSsl: getFormElement('editIgnoreSsl')?.checked || false, + upsideDown: getFormElement('editUpsideDown')?.checked || false, + important: getFormElement('editImportant')?.checked || false, + position: parseInt(getFormElement('editPosition')?.value) || 0, + quickCommands: getFormElement('editQuickCommands')?.value + ? getFormElement('editQuickCommands').value.split(',').map(cmd => cmd.trim()).filter(cmd => cmd) + : [] + }; + + // Add authentication if set + const authMethod = getFormElement('editAuthMethod')?.value; + if (authMethod === 'basic') { + data.auth = { + type: 'basic', + username: getFormElement('editAuthUsername')?.value || '', + password: getFormElement('editAuthPassword')?.value || '' + }; + } else if (authMethod === 'bearer') { + data.auth = { + type: 'bearer', + token: getFormElement('editAuthToken')?.value || '' + }; + } + + // Validate + if (!data.name || !data.host) { + showNotification('Please fill in all required fields', 'error'); + return; + } + + try { + if (currentMonitorId) { + // Update existing + await axios.put(`/admin/api/targets/${currentMonitorId}`, data); + showNotification('Monitor updated successfully', 'success'); + } else { + // Create new + const response = await axios.post('/admin/api/targets', data); + currentMonitorId = response.data.targetId; + showNotification('Monitor created successfully', 'success'); + } + + // Reload monitors and refresh the current selection in the same workspace. + await loadMonitors(); + if (currentMonitorId) { + const response = await axios.get(`/admin/api/targets/${currentMonitorId}`); + await selectMonitor(response.data.target); + } else { + resetMonitorWorkspace(); + } + } catch (error) { + console.error('Error saving monitor:', error); + showNotification(error.response?.data?.error || 'Error saving monitor', 'error'); + } +} + +// Helper to get favicon URL +function getFaviconUrl(appUrl) { + if (!appUrl) return null; + try { + const url = new URL(appUrl); + return `${url.protocol}//${url.host}/favicon.ico`; + } catch (e) { + return null; + } +} + +// Test monitor and update graph instantly +async function testMonitor() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + try { + // Collect form values from the modal + const testData = { + name: getFormElement('editName')?.value || '', + host: getFormElement('editHost')?.value || '', + protocol: getFormElement('editProtocol')?.value || 'ICMP', + port: getFormElement('editPort')?.value ? parseInt(getFormElement('editPort').value) : null, + timeout: parseInt(getFormElement('editTimeout')?.value) || 30, + httpMethod: getFormElement('editHttpMethod')?.value || 'GET', + statusCodes: getFormElement('editStatusCodes')?.value || '200-299', + maxRedirects: parseInt(getFormElement('editMaxRedirects')?.value) || 5, + ignoreSsl: getFormElement('editIgnoreSsl')?.checked || false, + upsideDown: getFormElement('editUpsideDown')?.checked || false, + }; + + // Add authentication if set + const authMethod = getFormElement('editAuthMethod')?.value; + if (authMethod === 'basic') { + testData.auth = { + type: 'basic', + username: getFormElement('editAuthUsername')?.value || '', + password: getFormElement('editAuthPassword')?.value || '' + }; + } else if (authMethod === 'bearer') { + testData.auth = { + type: 'bearer', + token: getFormElement('editAuthToken')?.value || '' + }; + } + + // Validate required fields + if (!testData.host) { + showNotification('Please enter a host address', 'error'); + return; + } + + const response = await axios.post(`/admin/api/targets/${currentMonitorId}/test`, testData); + const result = response.data.result; + + // Update status immediately + const status = result.success ? 'Up' : 'Down'; + const statusColor = result.success ? 'text-green-400' : 'text-red-400'; + document.getElementById('monitorStatus').textContent = status; + document.getElementById('monitorStatus').className = statusColor; + + // Update ping displays + if (result.success && result.responseTime) { + document.getElementById('monitorPing').textContent = `${Math.round(result.responseTime)} ms`; + // Update average if we have it + const currentAvg = document.getElementById('monitorAvgPing').textContent; + if (currentAvg !== '--') { + // Keep current average for now, or recalculate if needed + } + } else { + document.getElementById('monitorPing').textContent = '--'; + } + + // Reload statistics to get updated chart data (includes target details) + const statsResponse = await axios.get(`/admin/api/targets/${currentMonitorId}/statistics?period=1h`); + const stats = statsResponse.data.statistics || []; + const timeoutMs = (statsResponse.data.target?.timeout || 30) * 1000; + + // Draw chart with test result added + drawStatusChart(stats, result, timeoutMs); + + // Update monitor list status + const card = document.querySelector(`[data-monitor-id="${currentMonitorId}"]`); + if (card) { + const badge = card.querySelector('.status-badge'); + if (badge) { + badge.className = `status-badge ${result.success ? 'up' : 'down'}`; + badge.innerHTML = ` + + ${result.success ? 'Up' : 'Down'} + `; + } + } + + if (result.success) { + showNotification(`Test successful: ${Math.round(result.responseTime || 0)}ms`, 'success'); + } else { + showNotification(`Test failed: ${result.error || 'Connection failed'}`, 'error'); + } + } catch (error) { + console.error('Error testing monitor:', error); + showNotification('Error testing monitor', 'error'); + } +} + +// Cancel edit +function cancelEdit() { + if (currentMonitorId) { + showMonitorSummary(); + setMonitorActionVisibility(true); + return; + } + + resetMonitorWorkspace(); +} + +// Load incidents +async function loadIncidents() { + try { + const response = await axios.get('/admin/api/incidents'); + const incidents = response.data.incidents || []; + + const incidentsList = document.getElementById('incidentsList'); + incidentsList.innerHTML = ''; + + if (incidents.length === 0) { + incidentsList.innerHTML = '

No incidents recorded

'; + return; + } + + const severityColors = { + minor: 'bg-blue-900 text-blue-200', + major: 'bg-yellow-900 text-yellow-200', + critical: 'bg-red-900 text-red-200' + }; + + const statusColors = { + investigating: 'bg-yellow-900 text-yellow-200', + identified: 'bg-orange-900 text-orange-200', + monitoring: 'bg-blue-900 text-blue-200', + resolved: 'bg-green-900 text-green-200', + scheduled: 'bg-purple-900 text-purple-200' + }; + + incidents.forEach(incident => { + const card = document.createElement('div'); + card.className = 'bg-slate-900/50 backdrop-blur rounded-lg p-4 border border-slate-700/30'; + const date = new Date(incident.createdAt).toLocaleString(); + + let scheduledInfo = ''; + if (incident.isScheduled && incident.scheduledStart) { + const startDate = new Date(incident.scheduledStart).toLocaleString(); + const endDate = incident.scheduledEnd ? new Date(incident.scheduledEnd).toLocaleString() : null; + scheduledInfo = ` +
+

+ + Scheduled: ${startDate} + ${endDate ? ` - ${endDate}` : ''} +

+
+ `; + } + + card.innerHTML = ` +
+

${incident.title}

+
+ ${incident.severity.toUpperCase()} + ${incident.status.toUpperCase()} +
+
+

${incident.description}

+ ${scheduledInfo} +
+

${date}

+
+ + +
+
+ `; + incidentsList.appendChild(card); + }); + } catch (error) { + console.error('Error loading incidents:', error); + document.getElementById('incidentsList').innerHTML = '

Error loading incidents

'; + } +} + +let currentIncidentId = null; + +// Show create incident modal +function showCreateIncidentModal() { + currentIncidentId = null; + document.getElementById('incidentModalTitle').textContent = 'Create New Incident'; + document.getElementById('incidentTitle').value = ''; + document.getElementById('incidentDescription').value = ''; + document.getElementById('incidentSeverity').value = 'major'; + document.getElementById('incidentStatus').value = 'investigating'; + document.getElementById('incidentIsScheduled').checked = false; + document.getElementById('incidentScheduledStart').value = ''; + document.getElementById('incidentScheduledEnd').value = ''; + document.getElementById('scheduledFields').classList.add('hidden'); + document.getElementById('incidentModal').classList.add('active'); + + // Focus on title input + setTimeout(() => { + document.getElementById('incidentTitle').focus(); + }, 100); +} + +// Toggle scheduled fields visibility +function toggleScheduledFields() { + const isScheduled = document.getElementById('incidentIsScheduled').checked; + const scheduledFields = document.getElementById('scheduledFields'); + const scheduledStart = document.getElementById('incidentScheduledStart'); + const scheduledEnd = document.getElementById('incidentScheduledEnd'); + + if (isScheduled) { + scheduledFields.classList.remove('hidden'); + scheduledStart.required = true; + // Set default start time to 1 hour from now + const now = new Date(); + now.setHours(now.getHours() + 1); + scheduledStart.value = now.toISOString().slice(0, 16); + } else { + scheduledFields.classList.add('hidden'); + scheduledStart.required = false; + scheduledStart.value = ''; + scheduledEnd.value = ''; + } +} + +// Close incident modal +function closeIncidentModal() { + document.getElementById('incidentModal').classList.remove('active'); + currentIncidentId = null; + document.getElementById('incidentForm').reset(); +} + +// Edit incident +async function editIncident(incidentId) { + try { + const response = await axios.get(`/admin/api/incidents/${incidentId}`); + const incident = response.data.incident; + + currentIncidentId = incidentId; + document.getElementById('incidentModalTitle').textContent = 'Edit Incident'; + document.getElementById('incidentTitle').value = incident.title; + document.getElementById('incidentDescription').value = incident.description; + document.getElementById('incidentSeverity').value = incident.severity || 'major'; + document.getElementById('incidentStatus').value = incident.status || 'investigating'; + + // Handle scheduled maintenance fields + const isScheduled = incident.isScheduled || false; + document.getElementById('incidentIsScheduled').checked = isScheduled; + + if (incident.scheduledStart) { + const startDate = new Date(incident.scheduledStart); + document.getElementById('incidentScheduledStart').value = startDate.toISOString().slice(0, 16); + } else { + document.getElementById('incidentScheduledStart').value = ''; + } + + if (incident.scheduledEnd) { + const endDate = new Date(incident.scheduledEnd); + document.getElementById('incidentScheduledEnd').value = endDate.toISOString().slice(0, 16); + } else { + document.getElementById('incidentScheduledEnd').value = ''; + } + + toggleScheduledFields(); + document.getElementById('incidentModal').classList.add('active'); + + // Focus on title input + setTimeout(() => { + document.getElementById('incidentTitle').focus(); + }, 100); + } catch (error) { + console.error('Error loading incident:', error); + showNotification('Error loading incident: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Save incident +async function saveIncident(event) { + if (event) { + event.preventDefault(); + } + + const title = document.getElementById('incidentTitle').value.trim(); + const description = document.getElementById('incidentDescription').value.trim(); + const severity = document.getElementById('incidentSeverity').value; + const status = document.getElementById('incidentStatus').value; + const isScheduled = document.getElementById('incidentIsScheduled').checked; + const scheduledStart = document.getElementById('incidentScheduledStart').value; + const scheduledEnd = document.getElementById('incidentScheduledEnd').value; + + if (!title || !description) { + showNotification('Title and description are required', 'error'); + return; + } + + if (isScheduled && !scheduledStart) { + showNotification('Scheduled start time is required for scheduled maintenance', 'error'); + return; + } + + try { + const incidentData = { + title, + description, + severity, + status, + isScheduled, + scheduledStart: isScheduled && scheduledStart ? scheduledStart : null, + scheduledEnd: isScheduled && scheduledEnd ? scheduledEnd : null + }; + + if (currentIncidentId) { + // Update existing incident + await axios.put(`/admin/api/incidents/${currentIncidentId}`, incidentData); + showNotification('Incident updated successfully', 'success'); + } else { + // Create new incident + await axios.post('/admin/api/incidents', incidentData); + showNotification('Incident created successfully', 'success'); + } + + closeIncidentModal(); + loadIncidents(); + } catch (error) { + console.error('Error saving incident:', error); + showNotification('Error saving incident: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Delete incident +async function deleteIncident(incidentId) { + if (!confirm('Are you sure you want to delete this incident?')) return; + + try { + await axios.delete(`/admin/api/incidents/${incidentId}`); + showNotification('Incident deleted successfully', 'success'); + loadIncidents(); + } catch (error) { + console.error('Error deleting incident:', error); + showNotification('Error deleting incident: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Load posts +async function loadPosts() { + try { + const response = await axios.get('/admin/api/posts'); + const posts = response.data.posts || []; + + const postsList = document.getElementById('postsList'); + postsList.innerHTML = ''; + + if (posts.length === 0) { + postsList.innerHTML = '

No posts yet. Create your first post!

'; + return; + } + + posts.forEach(post => { + const card = document.createElement('div'); + card.className = 'bg-slate-900/50 backdrop-blur rounded-lg p-4 border border-slate-700/30'; + const date = new Date(post.createdAt).toLocaleDateString(undefined, { + year: 'numeric', + month: 'long', + day: 'numeric' + }); + const publishedBadge = post.published + ? 'Published' + : 'Draft'; + + card.innerHTML = ` +
+

${post.title}

+ ${publishedBadge} +
+

${post.content.substring(0, 150)}${post.content.length > 150 ? '...' : ''}

+
+

${date}

+
+ + +
+
+ `; + postsList.appendChild(card); + }); + } catch (error) { + console.error('Error loading posts:', error); + document.getElementById('postsList').innerHTML = '

Error loading posts

'; + } +} + +// Configure marked.js for markdown rendering +if (typeof marked !== 'undefined') { + marked.setOptions({ + breaks: true, + gfm: true, + }); +} + +let currentPostId = null; + +// Show create post modal +function showCreatePostModal() { + currentPostId = null; + document.getElementById('postModalTitle').textContent = 'Create New Post'; + document.getElementById('postTitle').value = ''; + document.getElementById('postContent').value = ''; + document.getElementById('postPublished').checked = true; + document.getElementById('markdownPreview').innerHTML = '

Preview will appear here...

'; + document.getElementById('postModal').classList.add('active'); + + // Focus on title input + setTimeout(() => { + document.getElementById('postTitle').focus(); + }, 100); + + // Setup markdown preview + setupMarkdownPreview(); +} + +// Show edit post modal +async function editPost(postId) { + try { + const response = await axios.get(`/admin/api/posts/${postId}`); + const post = response.data.post; + + currentPostId = postId; + document.getElementById('postModalTitle').textContent = 'Edit Post'; + document.getElementById('postTitle').value = post.title; + document.getElementById('postContent').value = post.content; + document.getElementById('postPublished').checked = post.published; + document.getElementById('postModal').classList.add('active'); + + // Update preview immediately + updateMarkdownPreview(); + + // Setup markdown preview + setupMarkdownPreview(); + } catch (error) { + console.error('Error loading post:', error); + showNotification('Error loading post: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Close post modal +function closePostModal() { + document.getElementById('postModal').classList.remove('active'); + currentPostId = null; + document.getElementById('postForm').reset(); +} + +// Setup markdown preview listener +function setupMarkdownPreview() { + const contentTextarea = document.getElementById('postContent'); + if (!contentTextarea) return; + + // Remove existing listener if any + const newTextarea = contentTextarea.cloneNode(true); + contentTextarea.parentNode.replaceChild(newTextarea, contentTextarea); + + // Add new listener + newTextarea.addEventListener('input', updateMarkdownPreview); + newTextarea.addEventListener('keyup', updateMarkdownPreview); +} + +// Update markdown preview +function updateMarkdownPreview() { + const content = document.getElementById('postContent').value; + const preview = document.getElementById('markdownPreview'); + + if (!content.trim()) { + preview.innerHTML = '

Preview will appear here...

'; + return; + } + + if (typeof marked !== 'undefined') { + preview.innerHTML = marked.parse(content); + } else { + // Fallback: simple line break conversion + preview.innerHTML = content + .replace(/\n\n/g, '

') + .replace(/\n/g, '
') + .replace(/^/, '

') + .replace(/$/, '

'); + } +} + +// Save post (create or update) +async function savePost(event) { + if (event) { + event.preventDefault(); + } + + const title = document.getElementById('postTitle').value.trim(); + const content = document.getElementById('postContent').value.trim(); + const published = document.getElementById('postPublished').checked; + + if (!title || !content) { + showNotification('Title and content are required', 'error'); + return; + } + + try { + if (currentPostId) { + // Update existing post + await axios.put(`/admin/api/posts/${currentPostId}`, { + title, + content, + published + }); + showNotification('Post updated successfully', 'success'); + } else { + // Create new post + await axios.post('/admin/api/posts', { + title, + content, + published + }); + showNotification('Post created successfully', 'success'); + } + + closePostModal(); + loadPosts(); + } catch (error) { + console.error('Error saving post:', error); + showNotification('Error saving post: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Setup form submission handler +document.addEventListener('DOMContentLoaded', () => { + const postForm = document.getElementById('postForm'); + if (postForm) { + postForm.addEventListener('submit', savePost); + } + + const incidentForm = document.getElementById('incidentForm'); + if (incidentForm) { + incidentForm.addEventListener('submit', saveIncident); + } +}); + +// Delete post +async function deletePost(postId) { + if (!confirm('Are you sure you want to delete this post?')) return; + + try { + await axios.delete(`/admin/api/posts/${postId}`); + showNotification('Post deleted successfully', 'success'); + loadPosts(); + } catch (error) { + console.error('Error deleting post:', error); + showNotification('Error deleting post: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Close modal on escape key +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + const modal = document.getElementById('postModal'); + if (modal && modal.classList.contains('active')) { + closePostModal(); + } + + const clearPingDataModal = document.getElementById('clearPingDataModal'); + if (clearPingDataModal && clearPingDataModal.classList.contains('active')) { + closeClearPingDataModal(); + } + + const clearMonitorPingDataModal = document.getElementById('clearMonitorPingDataModal'); + if (clearMonitorPingDataModal && clearMonitorPingDataModal.classList.contains('active')) { + closeClearMonitorPingDataModal(); + } + + const activeModal = document.querySelector('.post-modal.active'); + if (!activeModal && isMobileMonitorViewport() && document.body.classList.contains('monitor-detail-open')) { + closeMobileMonitorView(); + } + } +}); + +// Close modal when clicking outside +document.addEventListener('click', (e) => { + const modal = document.getElementById('postModal'); + if (modal && modal.classList.contains('active') && e.target === modal) { + closePostModal(); + } + + const clearPingDataModal = document.getElementById('clearPingDataModal'); + if (clearPingDataModal && clearPingDataModal.classList.contains('active') && e.target === clearPingDataModal) { + closeClearPingDataModal(); + } + + const clearMonitorPingDataModal = document.getElementById('clearMonitorPingDataModal'); + if (clearMonitorPingDataModal && clearMonitorPingDataModal.classList.contains('active') && e.target === clearMonitorPingDataModal) { + closeClearMonitorPingDataModal(); + } +}); + +// Change password +function changePassword() { + const newPassword = prompt('Enter new password:'); + if (!newPassword) return; + + const confirmPassword = prompt('Confirm password:'); + if (newPassword !== confirmPassword) { + showNotification('Passwords do not match', 'error'); + return; + } + + // Note: This would require a new API endpoint to be implemented + showNotification('Password change not yet implemented', 'error'); +} + +// Show notification +function showNotification(message, type = 'success') { + const notification = document.createElement('div'); + notification.className = `notification ${type}`; + notification.textContent = message; + + document.getElementById('notificationContainer').appendChild(notification); + + setTimeout(() => { + notification.style.animation = 'slideIn 0.3s ease-out reverse'; + setTimeout(() => notification.remove(), 300); + }, 3000); +} + +// Test all monitors +async function testAllMonitors() { + const testAllBtn = document.getElementById('testAllBtn'); + const originalText = testAllBtn.innerHTML; + + try { + // Clear cache to ensure live results + await axios.post('/admin/api/cache/clear'); + + // Get all monitors + const response = await axios.get('/admin/api/dashboard'); + const targets = response.data.dashboard.targets; + + if (targets.length === 0) { + showNotification('No monitors to test', 'error'); + return; + } + + // Disable button and show loading + testAllBtn.disabled = true; + testAllBtn.innerHTML = 'Testing...'; + + let successCount = 0; + let failCount = 0; + + // Test all monitors in parallel + const testPromises = targets.map(async (target) => { + try { + const testResponse = await axios.post(`/admin/api/targets/${target._id}/test`); + const result = testResponse.data.result; + + // Update the monitor card status + const card = document.querySelector(`[data-monitor-id="${target._id}"]`); + if (card) { + const badge = card.querySelector('.status-badge'); + if (badge) { + const isSuccess = result.success; + badge.className = `status-badge ${isSuccess ? 'up' : 'down'}`; + badge.innerHTML = ` + + ${isSuccess ? 'Up' : 'Down'} + `; + } + } + + // Update current monitor if it's selected + if (currentMonitorId === target._id) { + const status = result.success ? 'Up' : 'Down'; + const statusColor = result.success ? 'text-green-400' : 'text-red-400'; + document.getElementById('monitorStatus').textContent = status; + document.getElementById('monitorStatus').className = statusColor; + + if (result.success && result.responseTime) { + document.getElementById('monitorPing').textContent = `${result.responseTime.toFixed(2)} ms`; + } + + // Reload statistics and update chart (get timeout from monitor) + // Statistics endpoint now includes target details and daily stats, so we only need one call + await loadMonitorStatistics(target._id, 30); + } + + if (result.success) { + successCount++; + } else { + failCount++; + } + } catch (error) { + console.error(`Error testing monitor ${target.name}:`, error); + failCount++; + + // Update card to show error + const card = document.querySelector(`[data-monitor-id="${target._id}"]`); + if (card) { + const badge = card.querySelector('.status-badge'); + if (badge) { + badge.className = 'status-badge down'; + badge.innerHTML = ` + + Down + `; + } + } + } + }); + + await Promise.all(testPromises); + + // Clear cache again before reloading to ensure fresh data + await axios.post('/admin/api/cache/clear'); + + // Reload monitors list to refresh all statuses + await loadMonitors(); + + // Show summary notification + showNotification(`Tested ${targets.length} monitors: ${successCount} up, ${failCount} down`, + failCount === 0 ? 'success' : 'error'); + + } catch (error) { + console.error('Error testing all monitors:', error); + showNotification('Error testing monitors', 'error'); + } finally { + // Re-enable button + testAllBtn.disabled = false; + testAllBtn.innerHTML = originalText; + } +} + +// Load visibility settings +async function loadVisibility() { + try { + const response = await axios.get('/admin/api/targets'); + const targets = response.data.targets; + + const visibilityList = document.getElementById('visibilityList'); + visibilityList.innerHTML = ''; + + if (targets.length === 0) { + visibilityList.innerHTML = '

No monitors found

'; + return; + } + + // Sort by position, then by name + targets.sort((a, b) => { + const posA = a.position || 0; + const posB = b.position || 0; + if (posA !== posB) return posA - posB; + return (a.name || '').localeCompare(b.name || ''); + }); + + targets.forEach((target, index) => { + const isPublic = target.publicVisible !== false; // Default to true if not set + const showDetails = target.publicShowDetails === true; // Default to false + const showStatus = target.publicShowStatus !== false; // Default to true + const showAppLink = target.publicShowAppLink !== false; // Default to true + const hasAppUrl = target.appUrl && target.appUrl.trim() !== ''; + + const item = document.createElement('div'); + item.className = 'visibility-item flex flex-col gap-3 p-4 bg-slate-800/50 rounded-lg border border-slate-700/30 cursor-move'; + item.draggable = true; + item.innerHTML = ` +
+
+ +
+
+
+

${target.name}

+ ${hasAppUrl ? 'App Link' : ''} + ${!target.enabled ? 'Disabled' : ''} +
+

${target.host}${target.port ? ':' + target.port : ''} (${target.protocol})

+
+
+
+
+ + ${isPublic ? ` + + + ${hasAppUrl ? ` + + ` : ''} + ` : ''} +
+
+ `; + // Set dataset attributes after innerHTML to ensure they persist + item.dataset.targetId = target._id; + item.dataset.position = target.position || index; + visibilityList.appendChild(item); + }); + + // Setup drag and drop + setupDragAndDrop(); + } catch (error) { + console.error('Error loading visibility settings:', error); + showNotification('Error loading visibility settings', 'error'); + } +} + +// Setup drag and drop for reordering +function setupDragAndDrop() { + const visibilityList = document.getElementById('visibilityList'); + const items = document.querySelectorAll('.visibility-item'); + let draggedElement = null; + let hasMoved = false; + + items.forEach(item => { + item.addEventListener('dragstart', (e) => { + draggedElement = item; + hasMoved = false; + item.style.opacity = '0.5'; + item.classList.add('dragging'); + e.dataTransfer.effectAllowed = 'move'; + }); + + item.addEventListener('dragend', async (e) => { + item.style.opacity = '1'; + item.classList.remove('dragging'); + + if (hasMoved && draggedElement) { + // Update data-position attributes + const allItems = visibilityList.querySelectorAll('.visibility-item'); + allItems.forEach((item, index) => { + item.dataset.position = index; + }); + await savePositions(); + } + + draggedElement = null; + hasMoved = false; + }); + + item.addEventListener('dragover', (e) => { + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + + if (!draggedElement) return; + + const afterElement = getDragAfterElement(visibilityList, e.clientY); + if (afterElement == null) { + if (visibilityList.lastElementChild !== draggedElement) { + visibilityList.appendChild(draggedElement); + hasMoved = true; + } + } else { + if (afterElement !== draggedElement && afterElement.nextSibling !== draggedElement) { + visibilityList.insertBefore(draggedElement, afterElement); + hasMoved = true; + } + } + }); + + item.addEventListener('drop', (e) => { + e.preventDefault(); + }); + }); + + // Also handle drop on the container itself + visibilityList.addEventListener('drop', (e) => { + e.preventDefault(); + }); +} + +// Get element after which to insert dragged element +function getDragAfterElement(container, y) { + const draggableElements = [...container.querySelectorAll('.visibility-item:not(.dragging)')]; + + return draggableElements.reduce((closest, child) => { + const box = child.getBoundingClientRect(); + const offset = y - box.top - box.height / 2; + + if (offset < 0 && offset > closest.offset) { + return { offset: offset, element: child }; + } else { + return closest; + } + }, { offset: Number.NEGATIVE_INFINITY }).element; +} + +// Save positions after reordering +async function savePositions() { + try { + const items = document.querySelectorAll('.visibility-item'); + const positions = Array.from(items).map((item, index) => ({ + targetId: item.dataset.targetId, + position: index + })); + + // Validate all targetIds are present + const missingIds = positions.filter(p => !p.targetId); + if (missingIds.length > 0) { + console.error('Missing targetIds:', missingIds); + showNotification('Error: Some monitors are missing IDs', 'error'); + return; + } + + await axios.put('/admin/api/targets/positions', { positions }); + showNotification('Monitor order saved', 'success'); + } catch (error) { + console.error('Error saving positions:', error); + const errorMsg = error.response?.data?.error || error.message || 'Unknown error'; + showNotification(`Error saving monitor order: ${errorMsg}`, 'error'); + // Reload to reset positions + loadVisibility(); + } +} + +// Toggle visibility field (unified function for all visibility toggles) +async function toggleVisibilityField(targetId, field, value) { + try { + const updateData = {}; + updateData[field] = value; + + await axios.put(`/admin/api/targets/${targetId}`, updateData); + + const fieldNames = { + publicVisible: 'Public visibility', + publicShowDetails: 'Technical details', + publicShowStatus: 'Status monitor', + publicShowAppLink: 'App link' + }; + + showNotification(`${fieldNames[field] || field} ${value ? 'enabled' : 'disabled'}`, 'success'); + + // Reload to update UI (show/hide conditional checkboxes) + if (field === 'publicVisible') { + loadVisibility(); + } + } catch (error) { + console.error(`Error updating ${field}:`, error); + showNotification(error.response?.data?.error || `Error updating ${field}`, 'error'); + // Reload to reset checkbox state + loadVisibility(); + } +} + +// Logout +function logout() { + axios.get('/admin/logout').then(() => { + window.location.href = '/admin/login'; + }); +} + +// Load public UI settings +async function loadPublicUISettings() { + try { + const response = await axios.get('/admin/api/public-ui-settings'); + const settings = response.data.settings; + + if (settings) { + const title = settings.title || 'Homelab'; + const publicUITitleEl = document.getElementById('publicUITitle'); + if (publicUITitleEl) { + publicUITitleEl.value = title; + } + const publicUISubtitleEl = document.getElementById('publicUISubtitle'); + if (publicUISubtitleEl) { + publicUISubtitleEl.value = settings.subtitle || 'System Status & Application Dashboard'; + } + const publicUICustomCSSEl = document.getElementById('publicUICustomCSS'); + if (publicUICustomCSSEl) { + publicUICustomCSSEl.value = settings.customCSS || ''; + } + + // Update header title + updateAdminHeaderTitle(title); + } else { + // No settings, use default + updateAdminHeaderTitle('LocalPing'); + } + + // Also load admin settings and notification settings + await loadAdminSettings(); + await loadNotificationSettings(); + } catch (error) { + console.error('Error loading public UI settings:', error); + // Don't show notification on initial load error, just use default + updateAdminHeaderTitle('LocalPing'); + // Still try to load admin settings + await loadAdminSettings(); + } +} + +// Load admin settings +async function loadAdminSettings() { + try { + const response = await axios.get('/admin/api/admin-settings'); + const settings = response.data.settings; + const dbSize = response.data.dbSize || 0; + + if (settings) { + const sessionDurationEl = document.getElementById('sessionDurationDays'); + if (sessionDurationEl) { + sessionDurationEl.value = settings.sessionDurationDays || 30; + } + const dataRetentionEl = document.getElementById('dataRetentionDays'); + if (dataRetentionEl) { + dataRetentionEl.value = settings.dataRetentionDays || 30; + } + const debugLoggingEl = document.getElementById('debugLogging'); + if (debugLoggingEl) { + debugLoggingEl.checked = settings.debugLogging === true; + } + } + + // Update database size display + const dbSizeEl = document.getElementById('databaseSize'); + if (dbSizeEl) { + dbSizeEl.textContent = formatFileSize(dbSize); + } + } catch (error) { + console.error('Error loading admin settings:', error); + } +} + +// Format file size to human-readable format +function formatFileSize(bytes) { + if (bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; +} + +// Save admin settings +async function saveAdminSettings() { + try { + const sessionDurationEl = document.getElementById('sessionDurationDays'); + const dataRetentionEl = document.getElementById('dataRetentionDays'); + const debugLoggingEl = document.getElementById('debugLogging'); + const sessionDurationDays = sessionDurationEl ? parseInt(sessionDurationEl.value, 10) : 30; + const dataRetentionDays = dataRetentionEl ? parseInt(dataRetentionEl.value, 10) : 30; + const debugLogging = debugLoggingEl ? debugLoggingEl.checked : false; + + if (isNaN(sessionDurationDays) || sessionDurationDays < 1 || sessionDurationDays > 365) { + showNotification('Session duration must be between 1 and 365 days', 'error'); + return; + } + + if (isNaN(dataRetentionDays) || dataRetentionDays < 1 || dataRetentionDays > 3650) { + showNotification('Data retention must be between 1 and 3650 days', 'error'); + return; + } + + await axios.put('/admin/api/admin-settings', { + sessionDurationDays: sessionDurationDays, + dataRetentionDays: dataRetentionDays, + debugLogging: debugLogging + }); + + showNotification('Admin settings saved successfully', 'success'); + } catch (error) { + console.error('Error saving admin settings:', error); + showNotification(error.response?.data?.error || 'Error saving admin settings', 'error'); + } +} + +// Update admin header title +function updateAdminHeaderTitle(customTitle) { + const headerTitle = document.getElementById('adminHeaderTitle'); + if (headerTitle) { + if (customTitle && customTitle !== 'Homelab' && customTitle !== 'LocalPing') { + headerTitle.textContent = `${customTitle} Admin`; + } else { + headerTitle.textContent = 'LocalPing Admin'; + } + } +} + +// Save public UI settings +async function savePublicUISettings() { + try { + const data = { + title: document.getElementById('publicUITitle').value || 'Homelab', + subtitle: document.getElementById('publicUISubtitle').value || 'System Status & Application Dashboard', + customCSS: document.getElementById('publicUICustomCSS').value || null, + }; + + await axios.put('/admin/api/public-ui-settings', data); + showNotification('Public UI settings saved successfully', 'success'); + + // Update header title + updateAdminHeaderTitle(data.title); + } catch (error) { + console.error('Error saving public UI settings:', error); + showNotification(error.response?.data?.error || 'Error saving public UI settings', 'error'); + } +} + +// Preview public UI +function previewPublicUI() { + window.open('/', '_blank'); +} + +// Load notification settings +async function loadNotificationSettings() { + try { + const response = await axios.get('/admin/api/notification-settings'); + const settings = response.data.settings; + + if (settings) { + const enabledEl = document.getElementById('notificationEnabled'); + if (enabledEl) { + enabledEl.checked = settings.enabled === true; + } + + const delayEl = document.getElementById('monitorDownDelayMinutes'); + if (delayEl) { + delayEl.value = settings.monitorDownDelayMinutes || 5; + } + + const discordEnabledEl = document.getElementById('discordEnabled'); + if (discordEnabledEl) { + discordEnabledEl.checked = settings.discord?.enabled === true; + } + + const discordWebhookEl = document.getElementById('discordWebhookUrl'); + if (discordWebhookEl) { + discordWebhookEl.value = settings.discord?.webhookUrl || ''; + } + + const discordUsernameEl = document.getElementById('discordUsername'); + if (discordUsernameEl) { + discordUsernameEl.value = settings.discord?.username || 'LocalPing'; + } + + const discordAvatarEl = document.getElementById('discordAvatarUrl'); + if (discordAvatarEl) { + discordAvatarEl.value = settings.discord?.avatarUrl || ''; + } + + const eventMonitorDownEl = document.getElementById('eventMonitorDown'); + if (eventMonitorDownEl) { + eventMonitorDownEl.checked = settings.events?.monitorDown !== false; + } + + const eventMonitorUpEl = document.getElementById('eventMonitorUp'); + if (eventMonitorUpEl) { + eventMonitorUpEl.checked = settings.events?.monitorUp !== false; + } + + const eventIncidentCreatedEl = document.getElementById('eventIncidentCreated'); + if (eventIncidentCreatedEl) { + eventIncidentCreatedEl.checked = settings.events?.incidentCreated !== false; + } + + const eventIncidentUpdatedEl = document.getElementById('eventIncidentUpdated'); + if (eventIncidentUpdatedEl) { + eventIncidentUpdatedEl.checked = settings.events?.incidentUpdated !== false; + } + } + } catch (error) { + console.error('Error loading notification settings:', error); + } +} + +// Save notification settings +async function saveNotificationSettings() { + try { + const enabled = document.getElementById('notificationEnabled').checked; + const delayEl = document.getElementById('monitorDownDelayMinutes'); + const monitorDownDelayMinutes = parseInt(delayEl?.value, 10) || 5; + if (monitorDownDelayMinutes < 1 || monitorDownDelayMinutes > 1440) { + showNotification('Monitor notification delay must be between 1 and 1,440 minutes', 'error'); + return; + } + const discordEnabled = document.getElementById('discordEnabled').checked; + const discordWebhookUrl = document.getElementById('discordWebhookUrl').value.trim(); + const discordUsername = document.getElementById('discordUsername').value.trim() || 'LocalPing'; + const discordAvatarUrl = document.getElementById('discordAvatarUrl').value.trim() || null; + + // Validate Discord webhook URL if Discord is enabled + if (discordEnabled && !discordWebhookUrl) { + showNotification('Discord webhook URL is required when Discord notifications are enabled', 'error'); + return; + } + + if (discordWebhookUrl && !discordWebhookUrl.startsWith('https://discord.com/api/webhooks/')) { + showNotification('Invalid Discord webhook URL. It should start with https://discord.com/api/webhooks/', 'error'); + return; + } + + const data = { + enabled: enabled, + monitorDownDelayMinutes, + discord: { + enabled: discordEnabled, + webhookUrl: discordWebhookUrl || null, + username: discordUsername, + avatarUrl: discordAvatarUrl, + }, + events: { + monitorDown: document.getElementById('eventMonitorDown').checked, + monitorUp: document.getElementById('eventMonitorUp').checked, + incidentCreated: document.getElementById('eventIncidentCreated').checked, + incidentUpdated: document.getElementById('eventIncidentUpdated').checked, + }, + }; + + await axios.put('/admin/api/notification-settings', data); + showNotification('Notification settings saved successfully', 'success'); + } catch (error) { + console.error('Error saving notification settings:', error); + showNotification(error.response?.data?.error || 'Error saving notification settings', 'error'); + } +} + +// Test Discord notification +async function testDiscordNotification() { + try { + const discordEnabled = document.getElementById('discordEnabled').checked; + const discordWebhookUrl = document.getElementById('discordWebhookUrl').value.trim(); + + if (!discordEnabled) { + showNotification('Please enable Discord notifications first', 'error'); + return; + } + + if (!discordWebhookUrl) { + showNotification('Please enter a Discord webhook URL first', 'error'); + return; + } + + // Save settings first to ensure webhook URL is saved + await saveNotificationSettings(); + + showNotification('Sending test notification...', 'success'); + + const response = await axios.post('/admin/api/notification-settings/test', { + provider: 'discord', + }); + + if (response.data.success) { + showNotification('Test notification sent successfully! Check your Discord channel.', 'success'); + } else { + showNotification(response.data.error || 'Failed to send test notification', 'error'); + } + } catch (error) { + console.error('Error testing Discord notification:', error); + showNotification(error.response?.data?.error || 'Error testing notification', 'error'); + } +} + +// Show clear ping data warning modal +function showClearPingDataWarning() { + document.getElementById('clearPingDataModal').classList.add('active'); +} + +// Close clear ping data modal +function closeClearPingDataModal() { + document.getElementById('clearPingDataModal').classList.remove('active'); +} + +// Confirm and clear all ping data +async function confirmClearPingData() { + try { + const response = await axios.post('/admin/api/clear-ping-data'); + if (response.data.success) { + showNotification('All ping data cleared successfully', 'success'); + closeClearPingDataModal(); + + // Reload monitors to refresh statistics + if (currentMonitorId) { + await loadMonitorStatistics(currentMonitorId); + } + } else { + showNotification(response.data.error || 'Error clearing ping data', 'error'); + } + } catch (error) { + console.error('Error clearing ping data:', error); + showNotification(error.response?.data?.error || 'Error clearing ping data', 'error'); + } +} + +// Show clear monitor ping data confirmation modal +function showClearMonitorPingDataConfirm() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + const monitorName = document.getElementById('monitorName')?.textContent || 'Monitor'; + document.getElementById('clearMonitorPingDataName').textContent = monitorName; + + const modal = document.getElementById('clearMonitorPingDataModal'); + modal.classList.add('active'); +} + +// Close clear monitor ping data modal +function closeClearMonitorPingDataModal() { + const modal = document.getElementById('clearMonitorPingDataModal'); + modal.classList.remove('active'); +} + +// Confirm and clear monitor ping data +async function confirmClearMonitorPingData() { + if (!currentMonitorId) { + showNotification('No monitor selected', 'error'); + return; + } + + try { + const response = await axios.post(`/admin/api/targets/${currentMonitorId}/clear-ping-data`); + if (response.data.success) { + showNotification(response.data.message || 'Ping data cleared successfully', 'success'); + closeClearMonitorPingDataModal(); + + // Reload monitor statistics to refresh the display + await loadMonitorStatistics(currentMonitorId); + } else { + showNotification(response.data.error || 'Error clearing ping data', 'error'); + } + } catch (error) { + console.error('Error clearing monitor ping data:', error); + showNotification(error.response?.data?.error || 'Error clearing ping data', 'error'); + } +} + +// Attach form listeners for protocol and auth changes +function attachFormListeners() { + const protocolSelect = document.getElementById('editProtocol'); + const authSelect = document.getElementById('editAuthMethod'); + + if (protocolSelect) { + protocolSelect.onchange = updateProtocolSettings; + } + if (authSelect) { + authSelect.onchange = updateAuthFields; + } +} + +// ============ BACKUP FUNCTIONS ============ + +// Toggle export options based on full backup checkbox +window.toggleExportOptions = function toggleExportOptions() { + const fullBackup = document.getElementById('exportFull').checked; + const exportOptions = document.getElementById('exportOptions'); + const checkboxes = exportOptions.querySelectorAll('input[type="checkbox"]'); + + if (fullBackup) { + checkboxes.forEach(cb => { + cb.checked = true; + cb.disabled = true; + }); + } else { + checkboxes.forEach(cb => { + cb.disabled = false; + }); + } +} + +// Export backup +window.exportBackup = async function exportBackup() { + try { + const fullBackup = document.getElementById('exportFull').checked; + const exportOptions = { + full: fullBackup, + monitors: document.getElementById('exportMonitors').checked, + incidents: document.getElementById('exportIncidents').checked, + posts: document.getElementById('exportPosts').checked, + dataPoints: document.getElementById('exportDataPoints').checked, + actions: document.getElementById('exportActions').checked, + alerts: document.getElementById('exportAlerts').checked, + settings: document.getElementById('exportSettings').checked, + favicons: document.getElementById('exportFavicons').checked, + }; + + // Check if at least one option is selected + if (!fullBackup && !Object.values(exportOptions).slice(1).some(v => v === true)) { + showNotification('Please select at least one data type to export', 'error'); + return; + } + + showNotification('Exporting backup...', 'success'); + + const response = await axios.post('/admin/api/backup/export', exportOptions); + + if (response.data.success) { + // Create download link + const dataStr = JSON.stringify(response.data.data, null, 2); + const dataBlob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(dataBlob); + const link = document.createElement('a'); + link.href = url; + link.download = `localping-backup-${new Date().toISOString().split('T')[0]}.json`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + + showNotification('Backup exported successfully', 'success'); + } else { + showNotification(response.data.error || 'Error exporting backup', 'error'); + } + } catch (error) { + console.error('Error exporting backup:', error); + showNotification(error.response?.data?.error || 'Error exporting backup', 'error'); + } +} + +// Import backup +window.importBackup = async function importBackup() { + try { + const fileInput = document.getElementById('importFile'); + const file = fileInput.files[0]; + + if (!file) { + showNotification('Please select a backup file to import', 'error'); + return; + } + + if (!file.name.endsWith('.json')) { + showNotification('Please select a valid JSON backup file', 'error'); + return; + } + + showNotification('Reading backup file...', 'success'); + + const fileContent = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = (e) => resolve(e.target.result); + reader.onerror = reject; + reader.readAsText(file); + }); + + let importData; + try { + importData = JSON.parse(fileContent); + } catch (error) { + showNotification('Invalid JSON file format', 'error'); + return; + } + + // Validate import data structure + if (!importData.data || typeof importData.data !== 'object') { + showNotification('Invalid backup file format', 'error'); + return; + } + + const overwrite = document.getElementById('importOverwrite').checked; + + showNotification('Importing backup...', 'success'); + + const response = await axios.post('/admin/api/backup/import', { + importData, + overwrite, + }); + + if (response.data.success) { + const results = response.data.results; + let message = 'Backup imported successfully:\n'; + + // Build summary message + if (results.imported) { + Object.keys(results.imported).forEach(key => { + const data = results.imported[key]; + const parts = []; + if (data.imported) parts.push(`${data.imported} imported`); + if (data.updated) parts.push(`${data.updated} updated`); + if (data.skipped) parts.push(`${data.skipped} skipped`); + if (parts.length > 0) { + message += `\n${key}: ${parts.join(', ')}`; + } + }); + } + + if (results.errors && results.errors.length > 0) { + message += `\n\nErrors: ${results.errors.length} error(s) occurred`; + } + + showNotification(message, 'success'); + + // Clear file input + fileInput.value = ''; + + // Reload relevant data + if (results.imported.targets || results.imported.incidents || results.imported.posts) { + // Reload current tab if applicable + const activeTab = document.querySelector('.tab-content.active'); + if (activeTab) { + const tabId = activeTab.id; + if (tabId === 'monitors' && results.imported.targets) { + loadMonitors(); + } else if (tabId === 'incidents' && results.imported.incidents) { + loadIncidents(); + } else if (tabId === 'posts' && results.imported.posts) { + loadPosts(); + } + } + } + } else { + showNotification(response.data.error || 'Error importing backup', 'error'); + } + } catch (error) { + console.error('Error importing backup:', error); + showNotification(error.response?.data?.error || 'Error importing backup', 'error'); + } +} + +// ============ EVENT RULES MANAGEMENT ============ +let currentEventRuleId = null; +let allTargets = []; + +// Load event rules +async function loadEventRules() { + try { + const response = await axios.get('/admin/api/event-rules'); + const rules = response.data.rules || []; + + const rulesList = document.getElementById('eventRulesList'); + rulesList.innerHTML = ''; + + if (rules.length === 0) { + rulesList.innerHTML = '

No event rules configured. Create one to automatically detect incidents.

'; + return; + } + + for (const rule of rules) { + const ruleCard = document.createElement('div'); + ruleCard.className = 'bg-slate-800/50 rounded-lg p-4 border border-slate-700'; + ruleCard.innerHTML = ` +
+
+

+ ${rule.name} + ${rule.enabled ? 'Enabled' : 'Disabled'} +

+

Type: ${rule.eventType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}

+
+
+ + +
+
+
+

Incident: ${rule.incidentTitle}

+

${rule.incidentDescription}

+
+ `; + rulesList.appendChild(ruleCard); + } + } catch (error) { + console.error('Error loading event rules:', error); + showNotification('Error loading event rules: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Show create event rule modal +async function showCreateEventRuleModal() { + currentEventRuleId = null; + document.getElementById('eventRuleModalTitle').textContent = 'Create New Event Rule'; + document.getElementById('eventRuleForm').reset(); + document.getElementById('eventRuleEnabled').checked = true; + document.getElementById('eventRuleAutoResolve').checked = false; + document.getElementById('autoResolveMessageContainer').classList.add('hidden'); + document.getElementById('eventRuleConditionsContainer').innerHTML = ''; + document.getElementById('eventRuleModal').classList.add('active'); + + // Load targets for selection + try { + const response = await axios.get('/admin/api/targets'); + allTargets = response.data.targets || []; + } catch (error) { + console.error('Error loading targets:', error); + } +} + +// Edit event rule +async function editEventRule(ruleId) { + try { + const response = await axios.get(`/admin/api/event-rules/${ruleId}`); + const rule = response.data.rule; + + currentEventRuleId = ruleId; + document.getElementById('eventRuleModalTitle').textContent = 'Edit Event Rule'; + document.getElementById('eventRuleName').value = rule.name; + document.getElementById('eventRuleType').value = rule.eventType; + document.getElementById('eventRuleEnabled').checked = rule.enabled !== false; + document.getElementById('eventRuleIncidentTitle').value = rule.incidentTitle; + document.getElementById('eventRuleIncidentDescription').value = rule.incidentDescription; + document.getElementById('eventRuleIncidentSeverity').value = rule.incidentSeverity || 'major'; + document.getElementById('eventRuleIncidentStatus').value = rule.incidentStatus || 'investigating'; + document.getElementById('eventRuleAutoResolve').checked = rule.autoResolve === true; + document.getElementById('eventRuleAutoResolveMessage').value = rule.autoResolveMessage || ''; + document.getElementById('eventRuleCooldown').value = rule.cooldownMinutes || 0; + + toggleAutoResolveMessage(); + updateEventRuleConditions(); + + // Load targets for selection + try { + const response = await axios.get('/admin/api/targets'); + allTargets = response.data.targets || []; + } catch (error) { + console.error('Error loading targets:', error); + } + + // Set condition values after loading + setTimeout(() => { + const conditions = rule.conditions; + const currentEventType = document.getElementById('eventRuleType').value; + + // Handle both old format (targetId) and new format (targetIds) for monitor_down/monitor_up + if ((currentEventType === 'monitor_down' || currentEventType === 'monitor_up')) { + const targetIds = conditions.targetIds && Array.isArray(conditions.targetIds) + ? conditions.targetIds + : (conditions.targetId ? [conditions.targetId] : []); + + targetIds.forEach(targetId => { + const checkbox = document.querySelector(`#conditionTargetIdsDropdown .target-checkbox[value="${targetId}"]`); + if (checkbox) { + checkbox.checked = true; + } + }); + + updateTargetDisplay('conditionTargetIds'); + } + // Handle targetIds for multiple_monitors_down + if (currentEventType === 'multiple_monitors_down') { + if (conditions.targetIds && Array.isArray(conditions.targetIds)) { + conditions.targetIds.forEach(targetId => { + const checkbox = document.querySelector(`#conditionTargetIdsDropdown .target-checkbox[value="${targetId}"]`); + if (checkbox) { + checkbox.checked = true; + } + }); + updateTargetDisplay('conditionTargetIds'); + } + } + if (conditions.count !== undefined) { + const input = document.getElementById('conditionCount'); + if (input) input.value = conditions.count; + } + if (conditions.threshold !== undefined) { + const input = document.getElementById('conditionThreshold'); + if (input) input.value = conditions.threshold; + } + if (conditions.operator) { + const select = document.getElementById('conditionOperator'); + if (select) select.value = conditions.operator; + } + if (conditions.period) { + const input = document.getElementById('conditionPeriod'); + if (input) input.value = conditions.period; + } + if (conditions.expression) { + const textarea = document.getElementById('conditionExpression'); + if (textarea) textarea.value = conditions.expression; + } + }, 100); + + document.getElementById('eventRuleModal').classList.add('active'); + } catch (error) { + console.error('Error loading event rule:', error); + showNotification('Error loading event rule: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Update event rule conditions UI based on event type +function updateEventRuleConditions() { + const eventType = document.getElementById('eventRuleType').value; + const container = document.getElementById('eventRuleConditionsContainer'); + + if (!eventType) { + container.innerHTML = ''; + return; + } + + let html = '
'; + html += '

Conditions

'; + + switch (eventType) { + case 'monitor_down': + case 'monitor_up': + html += ` +
+ +
+ + +
+

Click to select/deselect monitors

+
+ `; + break; + case 'multiple_monitors_down': + html += ` +
+ +
+ + +
+

Select monitors to check. The rule triggers when the specified count of these monitors are down.

+
+
+
+ + +
+
+ + +
+
+ `; + break; + case 'monitor_response_time': + html += ` +
+ + +
+
+
+ + +
+
+ + +
+
+ `; + break; + case 'uptime_threshold': + html += ` +
+ + +
+
+
+ + +
+
+ + +
+
+ `; + break; + case 'custom_condition': + html += ` +
+ + +

Available functions: getTargetStatus(id), getLatestResponseTime(id), getUptimePercentage(id, period)

+
+ `; + break; + } + + html += '
'; + container.innerHTML = html; +} + +// Toggle auto-resolve message field +function toggleAutoResolveMessage() { + const autoResolve = document.getElementById('eventRuleAutoResolve').checked; + const container = document.getElementById('autoResolveMessageContainer'); + if (autoResolve) { + container.classList.remove('hidden'); + } else { + container.classList.add('hidden'); + } +} + +// Save event rule +async function saveEventRule(event) { + if (event) { + event.preventDefault(); + } + + const eventType = document.getElementById('eventRuleType').value; + const conditions = {}; + + // Build conditions based on event type + switch (eventType) { + case 'monitor_down': + case 'monitor_up': + { + const checkboxes = document.querySelectorAll('#conditionTargetIdsDropdown .target-checkbox:checked'); + if (checkboxes.length > 0) { + conditions.targetIds = Array.from(checkboxes).map(cb => cb.value); + } + } + break; + case 'multiple_monitors_down': + { + const checkboxes = document.querySelectorAll('#conditionTargetIdsDropdown .target-checkbox:checked'); + if (checkboxes.length > 0) { + conditions.targetIds = Array.from(checkboxes).map(cb => cb.value); + } + conditions.count = parseInt(document.getElementById('conditionCount')?.value || '2'); + conditions.operator = document.getElementById('conditionOperator')?.value || 'gte'; + } + break; + case 'monitor_response_time': + conditions.targetId = document.getElementById('conditionTargetId')?.value; + conditions.threshold = parseInt(document.getElementById('conditionThreshold')?.value || '1000'); + conditions.operator = document.getElementById('conditionOperator')?.value || 'gt'; + break; + case 'uptime_threshold': + conditions.targetId = document.getElementById('conditionTargetId')?.value; + conditions.threshold = parseFloat(document.getElementById('conditionThreshold')?.value || '95'); + conditions.period = document.getElementById('conditionPeriod')?.value || '24h'; + break; + case 'custom_condition': + conditions.expression = document.getElementById('conditionExpression')?.value || ''; + break; + } + + const ruleData = { + name: document.getElementById('eventRuleName').value.trim(), + eventType: eventType, + enabled: document.getElementById('eventRuleEnabled').checked, + conditions: conditions, + incidentTitle: document.getElementById('eventRuleIncidentTitle').value.trim(), + incidentDescription: document.getElementById('eventRuleIncidentDescription').value.trim(), + incidentSeverity: document.getElementById('eventRuleIncidentSeverity').value, + incidentStatus: document.getElementById('eventRuleIncidentStatus').value, + autoResolve: document.getElementById('eventRuleAutoResolve').checked, + autoResolveMessage: document.getElementById('eventRuleAutoResolveMessage').value.trim() || null, + cooldownMinutes: parseInt(document.getElementById('eventRuleCooldown').value || '0'), + }; + + try { + if (currentEventRuleId) { + await axios.put(`/admin/api/event-rules/${currentEventRuleId}`, ruleData); + showNotification('Event rule updated successfully', 'success'); + } else { + await axios.post('/admin/api/event-rules', ruleData); + showNotification('Event rule created successfully', 'success'); + } + + closeEventRuleModal(); + loadEventRules(); + } catch (error) { + console.error('Error saving event rule:', error); + showNotification('Error saving event rule: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Delete event rule +async function deleteEventRule(ruleId) { + if (!confirm('Are you sure you want to delete this event rule?')) return; + + try { + await axios.delete(`/admin/api/event-rules/${ruleId}`); + showNotification('Event rule deleted successfully', 'success'); + loadEventRules(); + } catch (error) { + console.error('Error deleting event rule:', error); + showNotification('Error deleting event rule: ' + (error.response?.data?.error || error.message), 'error'); + } +} + +// Close event rule modal +function closeEventRuleModal() { + document.getElementById('eventRuleModal').classList.remove('active'); + currentEventRuleId = null; +} + +// Toggle target dropdown +function toggleTargetDropdown(id) { + const dropdown = document.getElementById(`${id}Dropdown`); + if (dropdown) { + dropdown.classList.toggle('hidden'); + } +} + +// Update target display text +function updateTargetDisplay(id) { + const checkboxes = document.querySelectorAll(`#${id}Dropdown .target-checkbox:checked`); + const display = document.getElementById(`${id}Display`); + + if (checkboxes.length === 0) { + display.textContent = 'Select monitors...'; + } else if (checkboxes.length === 1) { + display.textContent = checkboxes[0].getAttribute('data-name'); + } else { + display.textContent = `${checkboxes.length} monitors selected`; + } +} + +// Close dropdowns when clicking outside (only if already initialized) +if (typeof document !== 'undefined') { + document.addEventListener('click', (e) => { + // Check if click is outside any dropdown container + if (!e.target.closest('.relative') && !e.target.closest('[id$="Dropdown"]')) { + document.querySelectorAll('[id$="Dropdown"]').forEach(dropdown => { + dropdown.classList.add('hidden'); + }); + } + }); +} + +// Initialize on page load +document.addEventListener('DOMContentLoaded', () => { + attachFormListeners(); + loadPublicUISettings(); // Load custom title for header + + // Hide clone button initially + const cloneBtn = document.getElementById('cloneMonitorBtn'); + if (cloneBtn) { + cloneBtn.style.display = 'none'; + } +}); diff --git a/src/public/js/admin.js b/src/public/js/admin.js new file mode 100644 index 0000000..e77cc59 --- /dev/null +++ b/src/public/js/admin.js @@ -0,0 +1,934 @@ +let pingChart = null; +let selectedTargetId = null; +let allTargets = []; + +// Session-based authentication - no API key needed for admin panel +// API calls use secure session cookies automatically +axios.interceptors.response.use( + (response) => response, + (error) => { + // If 401, redirect to login + if (error.response?.status === 401) { + window.location.href = '/admin/login'; + } + return Promise.reject(error); + } +); + +// Load on page load +loadDashboard(); + +// Auto-refresh every 15 seconds +setInterval(loadDashboard, 15000); + +async function loadDashboard() { + try { + const res = await axios.get('/admin/api/dashboard'); + const { dashboard } = res.data; + + allTargets = dashboard.targets; + + // Update stats + const upCount = dashboard.targets.filter((t) => t.currentStatus === 'up').length; + const downCount = dashboard.targets.length - upCount; + + document.getElementById('total-targets').textContent = dashboard.targets.length; + document.getElementById('targets-up').textContent = upCount; + document.getElementById('targets-down').textContent = downCount; + document.getElementById('active-monitors').textContent = dashboard.targets.filter((t) => t.enabled).length; + + // Display monitors list + displayMonitorsList(dashboard.targets); + + // Update selected monitor if one is selected (but NOT if form is open) + const formPanel = document.getElementById('form-panel'); + if (selectedTargetId && !formPanel.classList.contains('hidden')) { + // Form is open, don't switch to details view + return; + } + + if (selectedTargetId) { + const selectedTarget = dashboard.targets.find(t => t._id === selectedTargetId); + if (selectedTarget) { + displayMonitorDetail(selectedTarget); + } + } + } catch (error) { + console.error('Error loading dashboard:', error); + } +} + +function displayMonitorsList(targets) { + const list = document.getElementById('services-list'); + const searchTerm = document.getElementById('search-input')?.value.toLowerCase() || ''; + + const filtered = targets.filter(target => + target.name.toLowerCase().includes(searchTerm) || + target.host.toLowerCase().includes(searchTerm) + ); + + if (filtered.length === 0) { + list.innerHTML = '
No monitors found
'; + return; + } + + list.innerHTML = filtered.map(target => { + const isSelected = selectedTargetId === target._id; + const statusColor = target.currentStatus === 'up' ? 'bg-green-500' : 'bg-red-500'; + + return ` +
+
+
+
+
+

${target.name}

+

${target.host}:${target.port || 'default'}

+
+
+ + ${target.currentStatus === 'up' ? 'βœ“' : 'βœ—'} + +
+
+ Loading... +
+
+ `; + }).join(''); + + // Load uptime data for all monitors + filtered.forEach(target => { + loadAndDisplayMiniUptime(target._id); + }); +} + +async function loadAndDisplayMiniUptime(targetId) { + try { + const res = await axios.get(`/api/targets/${targetId}/statistics?days=1`); + const stats = res.data.statistics || []; + + let html = ''; + stats.forEach(stat => { + const isUp = stat.successfulPings > 0; + html += `
`; + }); + + const el = document.querySelector(`.uptime-bar-${targetId}`); + if (el) { + el.innerHTML = html; + } + } catch (error) { + console.error('Error loading uptime bars:', error); + } +} + +function selectMonitor(targetId) { + selectedTargetId = targetId; + const selectedTarget = allTargets.find(t => t._id === targetId); + if (selectedTarget) { + displayMonitorDetail(selectedTarget); + // Compact the sidebar when a monitor is selected + const sidebarTop = document.getElementById('sidebar-top-section'); + sidebarTop.classList.remove('sidebar-top-expanded'); + sidebarTop.classList.add('sidebar-top-compact'); + } +} + +async function displayMonitorDetail(target) { + // Show details panel + document.getElementById('no-selection').classList.add('hidden'); + document.getElementById('details-panel').classList.remove('hidden'); + + // Update header immediately + document.getElementById('detail-name').textContent = target.name; + document.getElementById('detail-host').textContent = `${target.host}:${target.port || 'default'} β€’ ${target.protocol}`; + document.getElementById('detail-interval').textContent = `Check every ${target.interval || 60} seconds`; + + // Update status badge + const statusBadge = document.getElementById('detail-status'); + if (target.currentStatus === 'up') { + statusBadge.textContent = 'βœ“ Up'; + statusBadge.className = 'px-4 py-2 rounded-lg font-medium text-lg bg-green-900 text-green-200'; + } else { + statusBadge.textContent = 'βœ— Down'; + statusBadge.className = 'px-4 py-2 rounded-lg font-medium text-lg bg-red-900 text-red-200'; + } + + // Set loading state for chart + document.getElementById('detail-uptime-24h').textContent = 'Loading...'; + document.getElementById('detail-uptime-30d').textContent = 'Loading...'; + document.getElementById('detail-current-ping').textContent = 'Loading...'; + document.getElementById('detail-avg-ping').textContent = 'Loading...'; + + // Load uptime data + try { + const res24h = await axios.get(`/api/targets/${target._id}/uptime?days=1`); + const res30d = await axios.get(`/api/targets/${target._id}/uptime?days=30`); + const resStats = await axios.get(`/api/targets/${target._id}/statistics?days=1`); + + const uptime24h = res24h.data.uptime; + const uptime30d = res30d.data.uptime; + const stats = resStats.data.statistics || []; + + // Get the most recent avg response time + const latestStat = stats.length > 0 ? stats[stats.length - 1] : null; + const currentPing = latestStat?.lastResponseTime || 0; + const avgPing = latestStat?.avgResponseTime || 0; + + // Update uptime stats + document.getElementById('detail-uptime-24h').textContent = `${uptime24h.toFixed(2)}%`; + document.getElementById('detail-uptime-30d').textContent = `${uptime30d.toFixed(2)}%`; + document.getElementById('detail-current-ping').textContent = currentPing.toFixed(2) + ' ms'; + document.getElementById('detail-avg-ping').textContent = avgPing.toFixed(2) + ' ms'; + + // Generate uptime visualization + await generateUptimeVisualization(target._id); + + // Load and display ping chart + await loadPingChart(target._id); + } catch (error) { + console.error('Error loading monitor details:', error); + document.getElementById('detail-uptime-24h').textContent = '-- %'; + document.getElementById('detail-uptime-30d').textContent = '-- %'; + document.getElementById('detail-current-ping').textContent = '-- ms'; + document.getElementById('detail-avg-ping').textContent = '-- ms'; + } +} + +async function generateUptimeVisualization(targetId) { + try { + const res = await axios.get(`/api/targets/${targetId}/statistics?days=30`); + const stats = res.data.statistics || []; + + const viz = document.getElementById('uptime-visualization'); + viz.innerHTML = ''; + + // Create segments based on real statistics data + stats.forEach(stat => { + const segment = document.createElement('div'); + segment.className = 'uptime-segment'; + + const isUp = stat.successfulPings > 0; + if (!isUp) { + segment.classList.add('down'); + } else { + segment.classList.add('up'); + } + + segment.title = `${new Date(stat.date).toLocaleDateString()}: ${isUp ? 'Up' : 'Down'}`; + viz.appendChild(segment); + }); + } catch (error) { + console.error('Error generating uptime visualization:', error); + } +} + +async function loadPingChart(targetId, days = 1) { + try { + // Update button styling + document.querySelectorAll('.period-btn').forEach(btn => { + btn.classList.remove('bg-cyan-600', 'text-white'); + btn.classList.add('bg-slate-700', 'hover:bg-slate-600'); + }); + + // Find and highlight the clicked button + const clickedBtn = document.querySelector(`.period-btn[data-period="${days <= 0.05 ? '1h' : days === 1 ? '24h' : days === 7 ? '7d' : '30d'}"]`); + if (clickedBtn) { + clickedBtn.classList.remove('bg-slate-700', 'hover:bg-slate-600'); + clickedBtn.classList.add('bg-cyan-600', 'text-white'); + } + + const res = await axios.get(`/api/targets/${targetId}/statistics?days=${days}`); + const stats = res.data.statistics || []; + + const labels = []; + const data = []; + + stats.forEach(stat => { + const date = new Date(stat.date); + const label = days <= 0.05 + ? date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + : days <= 1 + ? date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + : date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + labels.push(label); + data.push(stat.avgResponseTime || 0); + }); + + const ctx = document.getElementById('ping-chart').getContext('2d'); + + if (pingChart) { + pingChart.destroy(); + } + + pingChart = new Chart(ctx, { + type: 'line', + data: { + labels, + datasets: [ + { + label: 'Response Time (ms)', + data, + borderColor: '#10b981', + backgroundColor: 'rgba(16, 185, 129, 0.1)', + fill: true, + tension: 0.4, + pointRadius: 2, + pointBackgroundColor: '#10b981', + pointBorderColor: '#fff', + pointHoverRadius: 5, + borderWidth: 2, + }, + ], + }, + options: { + responsive: true, + maintainAspectRatio: false, + plugins: { + legend: { + display: true, + labels: { color: '#cbd5e1' }, + }, + }, + scales: { + y: { + beginAtZero: true, + grid: { color: '#475569' }, + ticks: { color: '#cbd5e1' }, + }, + x: { + grid: { color: '#475569' }, + ticks: { color: '#cbd5e1', maxRotation: 45, minRotation: 0 }, + }, + }, + }, + }); + } catch (error) { + console.error('Error loading ping chart:', error); + } +} + +// Form panel functions +function showAddTargetForm() { + const formPanel = document.getElementById('form-panel'); + const detailsPanel = document.getElementById('details-panel'); + const noSelection = document.getElementById('no-selection'); + const form = document.getElementById('target-form'); + const title = document.getElementById('form-title'); + + title.textContent = 'Add Monitor'; + form.reset(); + delete form.dataset.targetId; + + // Reset protocol-specific sections + updateProtocolSettings(); + resetAuthenticationMethod(); + + // Show form panel, hide details + formPanel.classList.remove('hidden'); + detailsPanel.classList.add('hidden'); + noSelection.classList.add('hidden'); +} + +function cancelEditForm() { + const formPanel = document.getElementById('form-panel'); + const detailsPanel = document.getElementById('details-panel'); + const noSelection = document.getElementById('no-selection'); + const sidebarTop = document.getElementById('sidebar-top-section'); + + // If a monitor is selected, show details. Otherwise show no-selection + if (selectedTargetId) { + formPanel.classList.add('hidden'); + detailsPanel.classList.remove('hidden'); + // Keep sidebar compact when a monitor is selected + sidebarTop.classList.remove('sidebar-top-expanded'); + sidebarTop.classList.add('sidebar-top-compact'); + } else { + formPanel.classList.add('hidden'); + noSelection.classList.remove('hidden'); + // Expand sidebar when no monitor is selected + sidebarTop.classList.remove('sidebar-top-compact'); + sidebarTop.classList.add('sidebar-top-expanded'); + } +} + +function showEditForm() { + const formPanel = document.getElementById('form-panel'); + const detailsPanel = document.getElementById('details-panel'); + const form = document.getElementById('target-form'); + + // First load the target data + editTarget(); + + // Then show the form panel + setTimeout(() => { + formPanel.classList.remove('hidden'); + detailsPanel.classList.add('hidden'); + }, 10); +} + +function updateProtocolSettings() { + const protocol = document.getElementById('target-protocol').value; + const httpSection = document.getElementById('http-options-section'); + const authSection = document.getElementById('auth-section'); + + // Show HTTP options for HTTP/HTTPS protocols + if (protocol === 'HTTP' || protocol === 'HTTPS') { + httpSection.classList.remove('hidden'); + authSection.classList.remove('hidden'); + } else { + httpSection.classList.add('hidden'); + authSection.classList.add('hidden'); + } +} + +function resetAuthenticationMethod() { + const authMethod = document.getElementById('target-auth-method'); + const basicFields = document.getElementById('basic-auth-fields'); + const bearerFields = document.getElementById('bearer-auth-fields'); + + authMethod.value = 'none'; + basicFields.classList.add('hidden'); + bearerFields.classList.add('hidden'); +} + +// Listen for auth method changes +document.addEventListener('DOMContentLoaded', () => { + const authMethod = document.getElementById('target-auth-method'); + if (authMethod) { + authMethod.addEventListener('change', (e) => { + const basicFields = document.getElementById('basic-auth-fields'); + const bearerFields = document.getElementById('bearer-auth-fields'); + + basicFields.classList.add('hidden'); + bearerFields.classList.add('hidden'); + + if (e.target.value === 'basic') { + basicFields.classList.remove('hidden'); + } else if (e.target.value === 'bearer') { + bearerFields.classList.remove('hidden'); + } + }); + } +}); + +async function addTarget(event) { + event.preventDefault(); + + const form = document.getElementById('target-form'); + const isEdit = form.dataset.targetId; + + const target = { + name: document.getElementById('target-name').value, + host: document.getElementById('target-host').value, + protocol: document.getElementById('target-protocol').value, + port: document.getElementById('target-port').value ? parseInt(document.getElementById('target-port').value) : null, + interval: document.getElementById('target-interval').value ? parseInt(document.getElementById('target-interval').value) : 60, + enabled: document.getElementById('target-enabled').checked, + appUrl: document.getElementById('target-app-url').value || null, + appIcon: document.getElementById('target-app-icon').value || null, + retries: parseInt(document.getElementById('target-retries').value) || 0, + retryInterval: parseInt(document.getElementById('target-retry-interval').value) || 5, + timeout: parseInt(document.getElementById('target-timeout').value) || 30, + httpMethod: document.getElementById('target-http-method').value || 'GET', + statusCodes: document.getElementById('target-status-codes').value || '200-299', + maxRedirects: parseInt(document.getElementById('target-max-redirects').value) || 5, + ignoreSsl: document.getElementById('target-ignore-ssl').checked, + upsideDown: document.getElementById('target-upside-down').checked, + position: parseInt(document.getElementById('target-position').value) || 0, + group: document.getElementById('target-group').value || null, + quickCommands: document.getElementById('target-quick-commands').value + ? document.getElementById('target-quick-commands').value.split(',').map(cmd => cmd.trim()).filter(cmd => cmd) + : [], + }; + + // Add authentication if set + const authMethod = document.getElementById('target-auth-method').value; + if (authMethod === 'basic') { + target.auth = { + type: 'basic', + username: document.getElementById('target-auth-username').value, + password: document.getElementById('target-auth-password').value, + }; + } else if (authMethod === 'bearer') { + target.auth = { + type: 'bearer', + token: document.getElementById('target-auth-token').value, + }; + } + + try { + let savedTargetId; + if (isEdit) { + await axios.put(`/api/targets/${form.dataset.targetId}`, target); + savedTargetId = form.dataset.targetId; + } else { + const res = await axios.post('/api/targets', target); + savedTargetId = res.data.target._id; + } + + // Close form and return to details + const formPanel = document.getElementById('form-panel'); + const detailsPanel = document.getElementById('details-panel'); + formPanel.classList.add('hidden'); + + form.reset(); + document.getElementById('target-enabled').checked = true; + + // Reload dashboard and show the saved monitor details + await loadDashboard(); + + // If we just saved a new monitor, select the first one + if (!isEdit && allTargets.length > 0) { + selectMonitor(allTargets[0]._id); + } else if (isEdit) { + // If editing, refresh the details view + displayMonitorDetail(allTargets.find(t => t._id === form.dataset.targetId)); + } + + // Test the monitor immediately after saving + selectedTargetId = savedTargetId; + setTimeout(() => { + testTarget(); + }, 500); + } catch (error) { + alert('Error saving target: ' + error.message); + } +} + +async function editTarget() { + if (!selectedTargetId) return; + + try { + const res = await axios.get(`/api/targets/${selectedTargetId}`); + const target = res.data.target; + + // General section + document.getElementById('target-name').value = target.name; + document.getElementById('target-host').value = target.host; + document.getElementById('target-protocol').value = target.protocol; + document.getElementById('target-port').value = target.port || ''; + document.getElementById('target-interval').value = target.interval || 60; + + // Application section + document.getElementById('target-app-url').value = target.appUrl || ''; + document.getElementById('target-app-icon').value = target.appIcon || ''; + + // Retries section + document.getElementById('target-retries').value = target.retries || 0; + document.getElementById('target-retry-interval').value = target.retryInterval || 5; + + // HTTP Options section + document.getElementById('target-http-method').value = target.httpMethod || 'GET'; + document.getElementById('target-timeout').value = target.timeout || 30; + document.getElementById('target-status-codes').value = target.statusCodes || '200-299'; + document.getElementById('target-max-redirects').value = target.maxRedirects || 5; + + // Authentication section + if (target.auth) { + if (target.auth.type === 'basic') { + document.getElementById('target-auth-method').value = 'basic'; + document.getElementById('target-auth-username').value = target.auth.username || ''; + document.getElementById('target-auth-password').value = target.auth.password || ''; + } else if (target.auth.type === 'bearer') { + document.getElementById('target-auth-method').value = 'bearer'; + document.getElementById('target-auth-token').value = target.auth.token || ''; + } + } else { + document.getElementById('target-auth-method').value = 'none'; + } + + // Advanced section + document.getElementById('target-ignore-ssl').checked = target.ignoreSsl || false; + document.getElementById('target-upside-down').checked = target.upsideDown || false; + document.getElementById('target-enabled').checked = target.enabled !== false; + + // Public UI settings + document.getElementById('target-position').value = target.position || 0; + document.getElementById('target-group').value = target.group || ''; + const quickCommandsInput = document.getElementById('target-quick-commands'); + if (quickCommandsInput) { + quickCommandsInput.value = (target.quickCommands || []).join(', '); + } + + const form = document.getElementById('target-form'); + const title = document.getElementById('form-title'); + + title.textContent = 'Edit Monitor'; + form.dataset.targetId = selectedTargetId; + + // Update protocol settings to show HTTP/auth options if needed + updateProtocolSettings(); + } catch (error) { + alert('Error loading target: ' + error.message); + } +} + +async function deleteTarget() { + if (!selectedTargetId) return; + if (!confirm('Are you sure you want to delete this monitor?')) return; + + try { + await axios.delete(`/api/targets/${selectedTargetId}`); + selectedTargetId = null; + document.getElementById('no-selection').classList.remove('hidden'); + document.getElementById('details-panel').classList.add('hidden'); + loadDashboard(); + } catch (error) { + alert('Error deleting target: ' + error.message); + } +} + +async function testTarget() { + if (!selectedTargetId) return; + + try { + const res = await axios.post(`/api/targets/${selectedTargetId}/test`); + const result = res.data.result; + + showTestNotification(result); + } catch (error) { + showTestNotification(null, error.message); + } +} + +function showTestNotification(result, errorMessage) { + const notificationId = 'test-notification-' + Date.now(); + const isSuccess = result && result.success; + const targetName = allTargets.find(t => t._id === selectedTargetId)?.name || 'Target'; + + let container = document.getElementById('notificationContainer'); + if (!container) { + container = document.createElement('div'); + container.id = 'notificationContainer'; + container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; max-width: 400px; pointer-events: none;'; + document.body.appendChild(container); + } + + const notification = document.createElement('div'); + notification.id = notificationId; + notification.className = `notification ${isSuccess ? 'success' : 'error'}`; + + if (isSuccess) { + notification.innerHTML = ` + +
βœ“ ${targetName} is UP
+
+ Response Time: + ${(result.responseTime || 0).toFixed(2)} ms +
+
+ Protocol: + ${result.protocol || 'N/A'} +
+
+ Timestamp: + ${new Date().toLocaleTimeString()} +
+ `; + } else { + notification.innerHTML = ` + +
βœ— ${targetName} is DOWN
+
+ Error: + ${errorMessage || result?.error || 'Connection failed'} +
+
+ Timestamp: + ${new Date().toLocaleTimeString()} +
+ `; + } + + container.appendChild(notification); + + // Auto-remove after 5 seconds + setTimeout(() => { + const el = document.getElementById(notificationId); + if (el) { + el.style.animation = 'slideOut 0.3s ease-in forwards'; + setTimeout(() => el.remove(), 300); + } + }, 5000); +} + +// Search functionality +document.getElementById('search-input')?.addEventListener('input', () => { + displayMonitorsList(allTargets); +}); + +// Public UI Settings functions +function showPublicUISettings() { + const modal = document.getElementById('public-settings-modal'); + const settingsList = document.getElementById('public-settings-list'); + + if (allTargets.length === 0) { + settingsList.innerHTML = '
No monitors available
'; + modal.classList.remove('hidden'); + return; + } + + settingsList.innerHTML = allTargets.map(target => { + const isEnabled = target.enabled !== false; + return ` + + `; + }).join(''); + + modal.classList.remove('hidden'); +} + +async function savePublicSettings() { + const checkboxes = document.querySelectorAll('.public-ui-setting'); + const updates = []; + + for (const checkbox of checkboxes) { + const targetId = checkbox.dataset.targetId; + const isEnabled = checkbox.checked; + updates.push({ targetId, enabled: isEnabled }); + } + + try { + // Update each target's enabled status + for (const update of updates) { + await axios.put(`/api/targets/${update.targetId}`, { + enabled: update.enabled + }); + } + + document.getElementById('public-settings-modal').classList.add('hidden'); + + // Show success notification + showSuccessNotification('Public UI settings saved successfully!'); + + // Reload dashboard + await loadDashboard(); + } catch (error) { + alert('Error saving settings: ' + error.message); + } +} + +function showSuccessNotification(message) { + const notificationId = 'success-notification-' + Date.now(); + + let container = document.getElementById('notificationContainer'); + if (!container) { + container = document.createElement('div'); + container.id = 'notificationContainer'; + container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; max-width: 400px; pointer-events: none;'; + document.body.appendChild(container); + } + + const notification = document.createElement('div'); + notification.id = notificationId; + notification.className = 'notification success'; + notification.innerHTML = ` + +
βœ“ ${message}
+ `; + + container.appendChild(notification); + + setTimeout(() => { + const el = document.getElementById(notificationId); + if (el) { + el.style.animation = 'slideOut 0.3s ease-in forwards'; + setTimeout(() => el.remove(), 300); + } + }, 3000); +} + +// ============ INCIDENT MANAGEMENT FUNCTIONS ============ + +function showIncidentsPanel() { + // Hide details and form panels + document.getElementById('details-panel').classList.add('hidden'); + document.getElementById('form-panel').classList.add('hidden'); + document.getElementById('no-selection').classList.add('hidden'); + + // Show incidents panel + document.getElementById('incidents-panel').classList.remove('hidden'); + + loadIncidentsPanel(); +} + +function hideIncidentsPanel() { + const incidentsPanel = document.getElementById('incidents-panel'); + const noSelection = document.getElementById('no-selection'); + const sidebarTop = document.getElementById('sidebar-top-section'); + + incidentsPanel.classList.add('hidden'); + + // If a monitor is selected, show details with compact sidebar. Otherwise show no-selection with expanded sidebar + if (selectedTargetId) { + noSelection.classList.add('hidden'); + const selectedTarget = allTargets.find(t => t._id === selectedTargetId); + if (selectedTarget) { + displayMonitorDetail(selectedTarget); + sidebarTop.classList.remove('sidebar-top-expanded'); + sidebarTop.classList.add('sidebar-top-compact'); + } + } else { + noSelection.classList.remove('hidden'); + sidebarTop.classList.remove('sidebar-top-compact'); + sidebarTop.classList.add('sidebar-top-expanded'); + } +} + +function loadIncidentsPanel() { + loadIncidents(); +} + +async function loadIncidents() { + try { + const res = await axios.get('/admin/api/incidents'); + const incidents = res.data.incidents || []; + + const list = document.getElementById('incidents-list-panel'); + + if (incidents.length === 0) { + list.innerHTML = '
No incidents reported
'; + return; + } + + list.innerHTML = incidents.map(incident => { + const severityColor = { + minor: 'bg-yellow-900 text-yellow-200', + major: 'bg-orange-900 text-orange-200', + critical: 'bg-red-900 text-red-200' + }[incident.severity] || 'bg-slate-700'; + + const statusColor = { + investigating: 'bg-blue-900 text-blue-200', + identified: 'bg-cyan-900 text-cyan-200', + monitoring: 'bg-purple-900 text-purple-200', + resolved: 'bg-green-900 text-green-200' + }[incident.status] || 'bg-slate-700'; + + return ` +
+
+
+

${incident.title}

+

${new Date(incident.createdAt).toLocaleString()}

+
+
+ + ${incident.severity.toUpperCase()} + + + ${incident.status.toUpperCase()} + +
+
+

${incident.description}

+
+ + +
+
+ `; + }).join(''); + } catch (error) { + console.error('Error loading incidents:', error); + const list = document.getElementById('incidents-list-panel'); + if (list) { + list.innerHTML = `
Error loading incidents
`; + } + } +} + +function showCreateIncidentModal() { + document.getElementById('incident-form').reset(); + document.getElementById('incident-form-modal').classList.remove('hidden'); + delete document.getElementById('incident-form').dataset.incidentId; +} + +async function editIncident(incidentId) { + try { + const res = await axios.get(`/admin/api/incidents/${incidentId}`); + const incident = res.data.incident; + + document.getElementById('incident-title').value = incident.title; + document.getElementById('incident-description').value = incident.description; + document.getElementById('incident-severity').value = incident.severity; + document.getElementById('incident-status').value = incident.status; + + document.getElementById('incident-form').dataset.incidentId = incidentId; + document.getElementById('incident-form-modal').classList.remove('hidden'); + } catch (error) { + alert('Error loading incident: ' + error.message); + } +} + +async function saveIncident(event) { + event.preventDefault(); + + const title = document.getElementById('incident-title').value; + const description = document.getElementById('incident-description').value; + const severity = document.getElementById('incident-severity').value; + const status = document.getElementById('incident-status').value; + const incidentId = document.getElementById('incident-form').dataset.incidentId; + + try { + if (incidentId) { + // Update existing incident + await axios.put(`/admin/api/incidents/${incidentId}`, { + title, + description, + severity, + status + }); + showSuccessNotification('Incident updated successfully!'); + } else { + // Create new incident + await axios.post('/admin/api/incidents', { + title, + description, + severity, + status + }); + showSuccessNotification('Incident reported successfully!'); + } + + document.getElementById('incident-form-modal').classList.add('hidden'); + loadIncidents(); + } catch (error) { + alert('Error saving incident: ' + error.message); + } +} + +async function deleteIncident(incidentId) { + if (!confirm('Are you sure you want to delete this incident?')) return; + + try { + await axios.delete(`/admin/api/incidents/${incidentId}`); + showSuccessNotification('Incident deleted successfully!'); + loadIncidents(); + } catch (error) { + alert('Error deleting incident: ' + error.message); + } +} diff --git a/src/public/js/notifications.js b/src/public/js/notifications.js new file mode 100644 index 0000000..bbd3bd9 --- /dev/null +++ b/src/public/js/notifications.js @@ -0,0 +1,339 @@ +/** + * Browser Notification System for LocalPing + * Handles desktop and in-app notifications for status changes + */ + +class NotificationManager { + constructor() { + this.notificationPermission = Notification.permission; + this.targetStates = new Map(); // Track previous states and delayed notification state + this.inPageNotifications = []; + this.maxInPageNotifications = 5; + + // Request notification permission if not already granted + if (this.notificationPermission === 'default') { + this.requestPermission(); + } + + // Initialize notification container + this.initializeContainer(); + } + + /** + * Request notification permission from user + */ + async requestPermission() { + try { + const permission = await Notification.requestPermission(); + this.notificationPermission = permission; + + if (permission === 'granted') { + console.log('βœ“ Browser notifications enabled'); + } else if (permission === 'denied') { + console.log('βœ— Browser notifications disabled by user'); + } + } catch (err) { + console.error('Error requesting notification permission:', err); + } + } + + /** + * Initialize notification container in DOM + */ + initializeContainer() { + if (!document.getElementById('notification-container')) { + const container = document.createElement('div'); + container.id = 'notification-container'; + container.style.cssText = ` + position: fixed; + top: 20px; + right: 20px; + z-index: 9999; + max-width: 400px; + pointer-events: none; + `; + document.body.appendChild(container); + } + } + + /** + * Show browser notification + */ + showBrowserNotification(title, options = {}) { + if (this.notificationPermission !== 'granted') { + return; + } + + try { + const notification = new Notification(title, { + icon: '/android-icon-192x192.png', + badge: '/favicon-32x32.png', + ...options, + }); + + // Auto-close after 5 seconds + setTimeout(() => notification.close(), 5000); + + // Handle click + notification.onclick = () => { + window.focus(); + notification.close(); + }; + + return notification; + } catch (err) { + console.error('Error showing browser notification:', err); + } + } + + /** + * Show in-page toast notification + */ + showToastNotification(message, type = 'info', duration = 4000) { + const container = document.getElementById('notification-container'); + if (!container) { + this.initializeContainer(); + return this.showToastNotification(message, type, duration); + } + + const notification = document.createElement('div'); + notification.className = `notification notification-${type}`; + notification.innerHTML = message; + + const colors = { + success: '#10b981', + error: '#ef4444', + warning: '#f59e0b', + info: '#3b82f6', + }; + + notification.style.cssText = ` + background-color: ${colors[type] || colors.info}; + color: white; + padding: 16px; + border-radius: 8px; + margin-bottom: 10px; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + animation: slideIn 0.3s ease-out; + pointer-events: auto; + cursor: pointer; + `; + + // Add animation + if (!document.querySelector('style[data-notification-styles]')) { + const style = document.createElement('style'); + style.setAttribute('data-notification-styles', 'true'); + style.textContent = ` + @keyframes slideIn { + from { + transform: translateX(400px); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } + } + @keyframes slideOut { + from { + transform: translateX(0); + opacity: 1; + } + to { + transform: translateX(400px); + opacity: 0; + } + } + `; + document.head.appendChild(style); + } + + container.appendChild(notification); + + // Click to dismiss + notification.addEventListener('click', () => { + notification.style.animation = 'slideOut 0.3s ease-out'; + setTimeout(() => notification.remove(), 300); + }); + + // A zero duration means the toast should remain until the user dismisses + // it (used for sustained outage notifications). + if (duration > 0) { + setTimeout(() => { + if (notification.parentElement) { + notification.style.animation = 'slideOut 0.3s ease-out'; + setTimeout(() => notification.remove(), 300); + } + }, duration); + } + + // Track notifications + this.inPageNotifications.push(notification); + if (this.inPageNotifications.length > this.maxInPageNotifications) { + const old = this.inPageNotifications.shift(); + old.remove(); + } + } + + /** + * Update target status and send notifications if changed + */ + updateTargetStatus(targetId, targetName, newStatus, metadata = {}) { + const previous = this.targetStates.get(targetId); + const previousStatus = previous?.status || previous; + const hadDownNotification = previous?.downNotified === true; + + // No change + if (previousStatus === newStatus && !(newStatus === 'down' && metadata.notificationEligible && !previous?.downNotified)) { + return; + } + + // Keep the status immediately visible, but gate monitor toasts/browser + // notifications on the server's sustained-outage eligibility signal. + const state = typeof previous === 'object' && previous ? previous : { status: previousStatus }; + state.status = newStatus; + if (newStatus === 'up') state.downNotified = false; + this.targetStates.set(targetId, state); + + // Only send notifications if transitioning from a known state + if (previousStatus === undefined) { + return; + } + + if (newStatus === 'up' && previousStatus === 'down' && hadDownNotification) { + this.notifyTargetUp(targetName); + state.downNotified = false; + } else if (newStatus === 'down' && metadata.notificationEligible && !state.downNotified) { + state.downNotified = true; + this.notifyTargetDown(targetName); + } + } + + /** + * Notify when target comes online + */ + notifyTargetUp(targetName) { + const message = `βœ“ ${targetName} is back online`; + + // Browser notification + this.showBrowserNotification('Target Online', { + body: message, + tag: `target-${targetName}`, + requireInteraction: false, + }); + + // In-page notification + this.showToastNotification(message, 'success'); + } + + /** + * Notify when target goes offline + */ + notifyTargetDown(targetName) { + const message = `βœ— ${targetName} is offline`; + + // Browser notification + this.showBrowserNotification('Target Offline', { + body: message, + tag: `target-${targetName}`, + requireInteraction: true, + }); + + // In-page notification + this.showToastNotification(message, 'error', 0); // Don't auto-dismiss for errors + } + + /** + * Get notification preference from localStorage + */ + getPreference(key, defaultValue = true) { + const stored = localStorage.getItem(`notification-${key}`); + return stored !== null ? stored === 'true' : defaultValue; + } + + /** + * Set notification preference + */ + setPreference(key, value) { + localStorage.setItem(`notification-${key}`, value ? 'true' : 'false'); + } + + /** + * Check if notifications are enabled + */ + isEnabled() { + return this.getPreference('enabled', true) && this.notificationPermission === 'granted'; + } + + /** + * Toggle notifications + */ + async toggleNotifications(enabled) { + this.setPreference('enabled', enabled); + if (enabled && this.notificationPermission === 'default') { + await this.requestPermission(); + } + return this.isEnabled(); + } + + /** + * Notify about new incident + */ + notifyIncident(incident) { + if (!this.isEnabled()) return; + + const severityEmojis = { + 'minor': '⚠️', + 'major': 'πŸ”Ά', + 'critical': 'πŸ”΄' + }; + + const emoji = severityEmojis[incident.severity] || 'πŸ“’'; + const message = `${emoji} ${incident.title}`; + + // Browser notification + this.showBrowserNotification('New Incident', { + body: `${incident.severity.toUpperCase()}: ${incident.description}`, + tag: `incident-${incident._id}`, + requireInteraction: incident.severity === 'critical', + }); + + // In-page notification + this.showToastNotification(message, incident.severity === 'critical' ? 'error' : incident.severity === 'major' ? 'warning' : 'info', incident.severity === 'critical' ? 0 : 5000); + } + + /** + * Notify about incident update + */ + notifyIncidentUpdate(incident) { + if (!this.isEnabled()) return; + + const statusMessages = { + 'investigating': 'πŸ” Investigating', + 'identified': '⚠️ Issue Identified', + 'monitoring': 'πŸ‘οΈ Monitoring', + 'resolved': 'βœ… Resolved' + }; + + const message = `${statusMessages[incident.status] || 'πŸ“’'} ${incident.title}`; + + // Browser notification + this.showBrowserNotification('Incident Update', { + body: `${incident.status.toUpperCase()}: ${incident.description}`, + tag: `incident-update-${incident._id}`, + requireInteraction: false, + }); + + // In-page notification + const type = incident.status === 'resolved' ? 'success' : 'info'; + this.showToastNotification(message, type); + } +} + +// Initialize and export +const notificationManager = new NotificationManager(); + +// Make available globally +if (typeof window !== 'undefined') { + window.notificationManager = notificationManager; +} diff --git a/src/public/js/public.js b/src/public/js/public.js new file mode 100644 index 0000000..b2dcb89 --- /dev/null +++ b/src/public/js/public.js @@ -0,0 +1,2271 @@ +let allTargets = []; +let expandedServiceId = null; +let charts = {}; +let chartPeriods = {}; // Track current period for each chart +let targetUptimeCache = {}; +let faviconCache = {}; // Cache for favicons in localStorage +let previousIncidents = new Map(); // Track previous incidents for change detection +let statisticsCache = null; // Cache for statistics data +let statisticsCacheTime = null; // Timestamp of when cache was created +let viewerIsAdmin = false; +let dataLoadInFlight = null; +let blogLoadInFlight = null; +let blogLoadedAt = 0; +let lastAppsStructureKey = null; +let lastDeepLinkedMonitorId = null; +const PUBLIC_DATA_CACHE_DURATION = 60 * 60 * 1000; +const STATISTICS_CACHE_DURATION = PUBLIC_DATA_CACHE_DURATION; +const GRAPH_CACHE_STORAGE_KEY = 'localping:graph-cache:v1'; +const GRAPH_CACHE_DURATION = PUBLIC_DATA_CACHE_DURATION; +const BLOG_CACHE_DURATION = 60 * 1000; +let graphDataCache = {}; +let graphRefreshes = new Map(); + +// Extend each outage to the edges of its bucket so the red fill reads as one +// connected interval between the surrounding response-time segments. +function buildDowntimeSeries(stats, maxValue) { + const downBuckets = stats.map(stat => Number(stat.successfulPings || 0) === 0); + return downBuckets.map((isDown, index) => ( + isDown || downBuckets[index - 1] || downBuckets[index + 1] ? maxValue : null + )); +} + +// Keep the graph visually minimal while retaining useful hover details. The +// downtime series has bridge points around outages for a continuous fill; +// those points are filtered out of the tooltip via the chart status map. +function buildGraphTooltipOptions() { + return { + enabled: true, + mode: 'index', + intersect: false, + displayColors: false, + backgroundColor: 'rgba(15, 23, 42, 0.96)', + titleColor: '#f8fafc', + bodyColor: '#e2e8f0', + borderColor: 'rgba(148, 163, 184, 0.25)', + borderWidth: 1, + callbacks: { + title: tooltipItems => tooltipItems[0]?.label || '', + label: context => { + if (context.datasetIndex === 1) return 'πŸ”΄ Service Down'; + const responseTime = Number(context.raw); + return Number.isFinite(responseTime) ? `${Math.round(responseTime)} ms` : ''; + }, + }, + filter: context => { + if (context.datasetIndex === 0) { + return context.raw !== null && context.raw !== undefined; + } + const downtimeAtIndex = context.chart?._downtimeAtIndex || []; + return Boolean(downtimeAtIndex[context.dataIndex]) + && context.raw !== null + && context.raw !== undefined; + }, + }; +} + +// Values returned by the API are user-configurable. Keep generated markup +// safe and resilient when a monitor name contains quotes or HTML characters. +function escapeHtml(value) { + return String(value ?? '').replace(/[&<>"']/g, (character) => ({ + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + }[character])); +} + +function escapeInlineArgument(value) { + return escapeHtml(JSON.stringify(String(value ?? ''))); +} + +function serviceIconKey(target) { + return [target.appIcon || '', target.appUrl || '', target.favicon || '', target.name || ''].join('|'); +} + +const MINI_GRAPH_WIDTH = 240; +const MINI_GRAPH_HEIGHT = 44; + +function miniGraphStats(target) { + if (Array.isArray(target?.miniStats)) return target.miniStats; + const cached = graphDataCache[graphCacheKey(target?._id, '24h')]; + return Array.isArray(cached?.statistics) ? cached.statistics : []; +} + +function miniGraphDataKey(target) { + return miniGraphStats(target).map(stat => [ + stat.date || '', + Number(stat.totalPings) || 0, + Number(stat.successfulPings) || 0, + Number(stat.avgResponseTime) || 0, + ].join(':')).join('|'); +} + +function miniGraphPointState(stat) { + const totalPings = Number(stat.totalPings) || 0; + const successfulPings = Number(stat.successfulPings) || 0; + const hasPings = totalPings > 0; + const isDown = hasPings && successfulPings === 0; + const responseTime = hasPings && successfulPings > 0 && Number(stat.avgResponseTime) > 0 + ? Number(stat.avgResponseTime) + : null; + return { isDown, responseTime }; +} + +function buildMiniGraphContent(target) { + const insetX = 2; + const topY = 3; + const bottomY = MINI_GRAPH_HEIGHT - 3; + const stats = miniGraphStats(target) + .filter(stat => stat && stat.date) + .map(stat => ({ + ...stat, + dateObj: new Date(stat.date), + ...miniGraphPointState(stat), + })) + .sort((a, b) => a.dateObj.getTime() - b.dateObj.getTime()); + const pointCount = stats.length; + const xForIndex = index => pointCount <= 1 + ? MINI_GRAPH_WIDTH / 2 + : insetX + (index / (pointCount - 1)) * (MINI_GRAPH_WIDTH - insetX * 2); + + const values = stats + .map(stat => stat.responseTime) + .filter(value => Number.isFinite(value) && value > 0); + const minValue = values.length > 0 ? Math.min(...values) : 0; + const maxValue = values.length > 0 ? Math.max(...values) : 1; + const range = Math.max(maxValue - minValue, 1); + const domainMin = Math.max(0, minValue - range * 0.15); + const domainMax = maxValue + range * 0.15; + const yForValue = value => bottomY - ((value - domainMin) / Math.max(domainMax - domainMin, 1)) * (bottomY - topY); + + const downAreas = []; + let downStart = null; + const flushDownArea = endIndex => { + if (downStart === null || pointCount === 0) return; + const startX = downStart === 0 + ? insetX + : (xForIndex(downStart - 1) + xForIndex(downStart)) / 2; + const endX = endIndex === pointCount - 1 + ? MINI_GRAPH_WIDTH - insetX + : (xForIndex(endIndex) + xForIndex(endIndex + 1)) / 2; + downAreas.push(``); + downStart = null; + }; + + stats.forEach((stat, index) => { + if (stat.isDown && downStart === null) downStart = index; + if ((!stat.isDown || index === pointCount - 1) && downStart !== null) { + flushDownArea(stat.isDown && index === pointCount - 1 ? index : index - 1); + } + }); + + const responsePaths = []; + let responseSegment = []; + const flushResponseSegment = () => { + if (responseSegment.length === 0) return; + if (responseSegment.length === 1) { + const point = responseSegment[0]; + const startX = Math.max(insetX, point.x - 2); + const endX = Math.min(MINI_GRAPH_WIDTH - insetX, point.x + 2); + responsePaths.push(`M ${startX.toFixed(2)} ${point.y.toFixed(2)} L ${endX.toFixed(2)} ${point.y.toFixed(2)}`); + } else { + responsePaths.push(responseSegment + .map((point, index) => `${index === 0 ? 'M' : 'L'} ${point.x.toFixed(2)} ${point.y.toFixed(2)}`) + .join(' ')); + } + responseSegment = []; + }; + + stats.forEach((stat, index) => { + if (stat.responseTime === null || stat.isDown) { + flushResponseSegment(); + return; + } + responseSegment.push({ + x: xForIndex(index), + y: yForValue(stat.responseTime), + }); + }); + flushResponseSegment(); + + const svg = ` + + + ${downAreas.join('')} + ${responsePaths.map(path => ``).join('')} + + ${target.currentStatus === 'down' ? 'Down' : ''} + `; + return svg; +} + +function buildMiniGraphMarkup(target) { + return `
${buildMiniGraphContent(target)}
`; +} + +function buildIconImage(source, name, className, errorHandler) { + return `${escapeHtml(name)}`; +} + +viewerIsAdmin = document.body?.dataset.viewerAdmin === 'true'; + +try { + const storedGraphCache = JSON.parse(localStorage.getItem(GRAPH_CACHE_STORAGE_KEY) || '{}'); + graphDataCache = storedGraphCache && typeof storedGraphCache === 'object' && !Array.isArray(storedGraphCache) + ? storedGraphCache + : {}; +} catch (error) { + graphDataCache = {}; +} + +try { + const cachedSummary = JSON.parse(sessionStorage.getItem('localping:summary-cache:v2') || 'null'); + if (cachedSummary?.data?.targets && cachedSummary.cachedAt && cachedSummary.viewerIsAdmin === viewerIsAdmin) { + statisticsCache = cachedSummary.data; + statisticsCacheTime = cachedSummary.cachedAt; + if (typeof cachedSummary.data.viewer?.isAdmin === 'boolean') { + viewerIsAdmin = cachedSummary.data.viewer.isAdmin; + } + } +} catch (error) { + // Session storage is optional. +} + +// Load previous incidents from localStorage on page load +function loadPreviousIncidents() { + try { + const stored = localStorage.getItem('previousIncidents'); + if (stored) { + const data = JSON.parse(stored); + previousIncidents = new Map(Object.entries(data)); + } + } catch (error) { + console.error('Error loading previous incidents from localStorage:', error); + previousIncidents = new Map(); + } +} + +// Save previous incidents to localStorage +function savePreviousIncidents() { + try { + const data = Object.fromEntries(previousIncidents); + localStorage.setItem('previousIncidents', JSON.stringify(data)); + } catch (error) { + console.error('Error saving previous incidents to localStorage:', error); + } +} + +// Initialize previous incidents from localStorage +loadPreviousIncidents(); + +// Paint the last known summary before the first network round-trip. This is +// deliberately best-effort; live status replaces it as soon as the API responds. +if (statisticsCache?.targets) { + allTargets = statisticsCache.targets; + displayApps(allTargets); + updateServicesList(allTargets); + if (statisticsCache.status) updateHeaderStatus(statisticsCache.status); +} + +// Load immediately from the URL-selected view and refresh at a modest cadence +// so the browser is responsive even with many monitors. +loadData(); +setInterval(loadData, 30000); + +function persistGraphCache() { + try { + const entries = Object.entries(graphDataCache).slice(-120); + graphDataCache = Object.fromEntries(entries); + localStorage.setItem(GRAPH_CACHE_STORAGE_KEY, JSON.stringify(graphDataCache)); + } catch (error) { + // Storage can be disabled or full; the in-memory cache still works. + } +} + +function graphCacheKey(targetId, period) { + return `${targetId}:${period}`; +} + +async function refreshGraphData(targetId, period) { + const key = graphCacheKey(targetId, period); + if (graphRefreshes.has(key)) return graphRefreshes.get(key); + const request = axios.get(`/api/targets/${encodeURIComponent(targetId)}/statistics?period=${encodeURIComponent(period)}`) + .then((response) => { + const entry = { statistics: response.data.statistics || [], updatedAt: Date.now() }; + graphDataCache[key] = entry; + persistGraphCache(); + return entry.statistics; + }) + .finally(() => graphRefreshes.delete(key)); + graphRefreshes.set(key, request); + return request; +} + +async function getGraphData(targetId, period) { + const cached = graphDataCache[graphCacheKey(targetId, period)]; + if (cached && Array.isArray(cached.statistics)) { + // Stale-while-refresh: paint the cached chart now and refresh it in the + // background if it is older than the short freshness window. + if (Date.now() - (cached.updatedAt || 0) > GRAPH_CACHE_DURATION) { + refreshGraphData(targetId, period) + .then(() => { + // Keep an already-open chart current without making the user wait + // for the background refresh to complete. + if (charts[targetId] && chartPeriods[targetId] === period) { + return updateChartData(targetId, period); + } + return undefined; + }) + .catch(() => {}); + } + return cached.statistics; + } + return refreshGraphData(targetId, period); +} + +async function loadBlogPosts() { + if (blogLoadInFlight) return blogLoadInFlight; + if (blogLoadedAt && Date.now() - blogLoadedAt < BLOG_CACHE_DURATION) return; + + blogLoadInFlight = (async () => { + try { + const response = await axios.get('/api/posts'); + const posts = response.data.posts || []; + blogLoadedAt = Date.now(); + + const blogContainer = document.getElementById('blog-posts'); + if (!blogContainer) return; + + if (posts.length === 0) { + blogContainer.innerHTML = '
No posts yet. Check back soon!
'; + return; + } + + // Configure marked.js if available + if (typeof marked !== 'undefined') { + marked.setOptions({ + breaks: true, + gfm: true, + }); + } + + blogContainer.innerHTML = posts.map(post => { + const date = new Date(post.createdAt); + const formattedDate = date.toLocaleDateString(undefined, { + year: 'numeric', + month: 'long', + day: 'numeric' + }); + + // Render markdown if available, otherwise fallback to simple conversion + let contentHtml; + if (typeof marked !== 'undefined') { + contentHtml = marked.parse(post.content); + } else { + // Fallback: simple line break conversion + contentHtml = post.content + .replace(/\n\n/g, '

') + .replace(/\n/g, '
'); + contentHtml = `

${contentHtml}

`; + } + + return ` +
+
+

${post.title}

+ ${formattedDate} +
+
+ ${contentHtml} +
+
+ `; + }).join(''); + } catch (error) { + console.error('Error loading blog posts:', error); + const blogContainer = document.getElementById('blog-posts'); + if (blogContainer) { + blogContainer.innerHTML = '
Error loading posts
'; + } + } + })().finally(() => { + blogLoadInFlight = null; + }); + return blogLoadInFlight; +} + +async function loadData() { + if (dataLoadInFlight) return dataLoadInFlight; + dataLoadInFlight = (async () => { + try { + const now = Date.now(); + const hasMiniGraphData = Array.isArray(statisticsCache?.targets) + && statisticsCache.targets.every(target => Array.isArray(target.miniStats)); + const shouldRefreshStats = !statisticsCache || !statisticsCacheTime || (now - statisticsCacheTime) > STATISTICS_CACHE_DURATION || !hasMiniGraphData; + + // Load incidents (always fresh) + const incidentsPromise = axios.get('/api/incidents'); + + // Load targets and statistics (use cache if available and not expired) + let statusRes; + if (shouldRefreshStats) { + // Use consolidated endpoint for fresh data + statusRes = await axios.get('/api/public/all'); + statisticsCache = statusRes.data; + statisticsCacheTime = now; + if (typeof statusRes.data.viewer?.isAdmin === 'boolean') { + viewerIsAdmin = statusRes.data.viewer.isAdmin; + } + try { sessionStorage.setItem('localping:summary-cache:v2', JSON.stringify({ data: statisticsCache, cachedAt: now, viewerIsAdmin })); } catch (error) { /* optional */ } + } else { + // Use cached statistics but get fresh status + if (statisticsCache) { + // Get fresh status only + const statusOnlyRes = await axios.get('/api/status'); + if (typeof statusOnlyRes.data.viewer?.isAdmin === 'boolean') { + viewerIsAdmin = statusOnlyRes.data.viewer.isAdmin; + } + const cachedTargets = Array.isArray(statisticsCache.targets) ? statisticsCache.targets : []; + const freshTargets = Array.isArray(statusOnlyRes.data.targets) ? statusOnlyRes.data.targets : []; + const cachedTargetIds = new Set(cachedTargets.map(target => String(target._id))); + const freshTargetIds = new Set(freshTargets.map(target => String(target._id))); + const targetSetChanged = cachedTargetIds.size !== freshTargetIds.size + || [...freshTargetIds].some(targetId => !cachedTargetIds.has(targetId)); + + if (targetSetChanged) { + // A monitor was added or removed while the summary cache was warm. + // Refresh the consolidated payload so newly added rows get their + // mini graph immediately instead of waiting for the cache timeout. + statusRes = await axios.get('/api/public/all'); + statisticsCache = statusRes.data; + statisticsCacheTime = now; + try { sessionStorage.setItem('localping:summary-cache:v2', JSON.stringify({ data: statisticsCache, cachedAt: now, viewerIsAdmin })); } catch (error) { /* optional */ } + } else { + // Merge fresh status with cached statistics + statusRes = { + data: { + status: statusOnlyRes.data.status, + targets: freshTargets.map(freshTarget => { + const cachedTarget = cachedTargets.find(t => t._id === freshTarget._id); + if (cachedTarget) { + // Merge fresh status with cached statistics + return { + ...cachedTarget, + ...freshTarget, + // The status endpoint intentionally omits expensive + // aggregates; keep those fields from the summary cache. + uptime: cachedTarget.uptime, + miniStats: cachedTarget.miniStats, + currentStatus: freshTarget.currentStatus, + isUp: freshTarget.isUp, + isDown: freshTarget.isDown, + notification: freshTarget.notification, + }; + } + return { ...freshTarget }; + }), + }, + }; + } + } else { + // No cache, fetch everything + statusRes = await axios.get('/api/public/all'); + statisticsCache = statusRes.data; + statisticsCacheTime = now; + try { sessionStorage.setItem('localping:summary-cache:v2', JSON.stringify({ data: statisticsCache, cachedAt: now, viewerIsAdmin })); } catch (error) { /* optional */ } + } + } + + const incidentsRes = await incidentsPromise; + const { status, targets } = statusRes.data; + const { incidents = [] } = incidentsRes.data || {}; + + if (typeof statusRes.data.viewer?.isAdmin === 'boolean') { + viewerIsAdmin = statusRes.data.viewer.isAdmin; + } + + // Check for status changes and send notifications. The server only marks + // a monitor eligible after the configured sustained-outage delay. + if (window.notificationManager && window.notificationManager.isEnabled()) { + targets.forEach((target) => { + const status = target.currentStatus || (target.isUp ? 'up' : 'down'); + window.notificationManager.updateTargetStatus(target._id, target.name, status, target.notification || {}); + }); + } + + allTargets = targets; + + // Update header status + updateHeaderStatus(status); + + // Check for new/updated incidents and send notifications + if (window.notificationManager && window.notificationManager.isEnabled()) { + incidents.forEach((incident) => { + const prevIncident = previousIncidents.get(incident._id); + + if (!prevIncident) { + // New incident + window.notificationManager.notifyIncident(incident); + } else if (prevIncident.status !== incident.status) { + // Status changed + window.notificationManager.notifyIncidentUpdate(incident); + } + + // Update stored incident + previousIncidents.set(incident._id, { ...incident }); + }); + + // Save to localStorage after processing all incidents + savePreviousIncidents(); + } + + // Display incidents + displayIncidents(incidents); + displayIncidentHistory(incidents); + displayHomeIncidents(incidents); + + // Update both pages + displayApps(targets); + updateServicesList(targets); + if (pageFromLocation() === 'status') openDeepLinkedMonitor(); + } catch (error) { + console.error('Error loading data:', error); + } + })().finally(() => { + dataLoadInFlight = null; + }); + return dataLoadInFlight; +} + +function updateHeaderStatus(status) { + const statusEl = document.getElementById('status-text'); + const statusIndicator = document.getElementById('status-indicator'); + const statusMessage = document.getElementById('overall-status-message'); + const timeEl = document.getElementById('status-time'); + + let statusText = ''; + let statusClass = ''; + let message = ''; + + if (status.overallStatus === 'operational') { + statusText = 'βœ“ All Systems Operational'; + statusClass = 'operational'; + message = 'All systems are operational. No incidents reported.'; + } else if (status.overallStatus === 'degraded') { + statusText = '⚠ Degraded Performance'; + statusClass = 'degraded'; + message = `${status.downTargets} system(s) experiencing issues.`; + } else { + statusText = 'βœ— System Down'; + statusClass = 'down'; + message = `${status.downTargets} system(s) down.`; + } + + statusEl.textContent = statusText; + statusEl.className = `text-lg font-semibold ${ + statusClass === 'operational' ? 'text-green-400' : + statusClass === 'degraded' ? 'text-yellow-400' : + 'text-red-400' + }`; + + statusIndicator.className = `status-indicator ${statusClass}`; + statusMessage.textContent = message; + timeEl.textContent = `Last updated: ${new Date().toLocaleTimeString()}`; +} + +// Format date for scheduled maintenance display +function formatScheduledTime(dateString) { + if (!dateString) return ''; + const date = new Date(dateString); + return date.toLocaleString([], { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + hour12: true + }); +} + +// Display active incidents on home page - Mobile Optimized +function displayHomeIncidents(incidents) { + const homeIncidentsContainer = document.getElementById('home-incidents'); + if (!homeIncidentsContainer) return; + + // Filter for active incidents (investigating, identified, monitoring, scheduled) + const activeIncidents = incidents.filter(i => i.status !== 'resolved'); + + if (activeIncidents.length === 0) { + homeIncidentsContainer.innerHTML = ''; + return; + } + + const statusIcons = { + 'investigating': 'πŸ”', + 'identified': '⚠️', + 'monitoring': 'πŸ‘οΈ', + 'scheduled': 'πŸ“…' + }; + + const statusLabels = { + 'investigating': 'Investigating', + 'identified': 'Identified', + 'monitoring': 'Monitoring', + 'scheduled': 'Scheduled' + }; + + homeIncidentsContainer.innerHTML = ` +
+
+

Ongoing Incidents

+ ${activeIncidents.length} +
+ ${activeIncidents.map(incident => { + const severityClass = incident.severity || 'minor'; + const statusIcon = statusIcons[incident.status] || '⚠️'; + const statusLabel = statusLabels[incident.status] || incident.status; + + const statusBadgeColors = { + 'investigating': 'bg-blue-500/20 text-blue-300', + 'identified': 'bg-yellow-500/20 text-yellow-300', + 'monitoring': 'bg-orange-500/20 text-orange-300', + 'scheduled': 'bg-purple-500/20 text-purple-300' + }; + + const severityBadgeColors = { + 'critical': 'bg-red-500/20 text-red-300', + 'major': 'bg-orange-500/20 text-orange-300', + 'minor': 'bg-yellow-500/20 text-yellow-300' + }; + + const isScheduled = incident.isScheduled && (incident.scheduledStart || incident.scheduledEnd); + let scheduledTimeHtml = ''; + + if (isScheduled) { + if (incident.scheduledStart && incident.scheduledEnd) { + scheduledTimeHtml = ` +
+

+ + ${formatScheduledTime(incident.scheduledStart)} - ${formatScheduledTime(incident.scheduledEnd)} +

+
+ `; + } else if (incident.scheduledStart) { + scheduledTimeHtml = ` +
+

+ + Starts: ${formatScheduledTime(incident.scheduledStart)} +

+
+ `; + } + } + + const timeAgo = getTimeAgo(new Date(incident.createdAt)); + + return ` +
+
+

${incident.title}

+ + ${statusIcon} ${statusLabel} + +
+

${incident.description}

+ ${scheduledTimeHtml} +
+ + ${severityClass.toUpperCase()} + + β€’ + ${timeAgo} +
+
+ `; + }).join('')} +
+ `; +} + +// Helper function to get time ago +function getTimeAgo(date) { + const now = new Date(); + const diffMs = now - date; + const diffMins = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + + if (diffMins < 1) return 'Just now'; + if (diffMins < 60) return `${diffMins}m ago`; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); +} + +// Display active incidents at the top of status page +function displayIncidents(incidents) { + const incidentsContainer = document.getElementById('incidents-container'); + if (!incidentsContainer) return; + + // Filter for active incidents (investigating, identified, monitoring, scheduled) + const activeIncidents = incidents.filter(i => i.status !== 'resolved'); + + if (activeIncidents.length === 0) { + incidentsContainer.innerHTML = ''; + incidentsContainer.style.display = 'none'; + return; + } + + incidentsContainer.style.display = 'block'; + + incidentsContainer.innerHTML = ` +
+

Active Incidents

+ ${activeIncidents.map(incident => { + const severityColors = { + 'minor': 'bg-yellow-900/30 border-yellow-700 text-yellow-300', + 'major': 'bg-orange-900/30 border-orange-700 text-orange-300', + 'critical': 'bg-red-900/30 border-red-700 text-red-300' + }; + + const statusColors = { + 'investigating': 'bg-blue-900/30 text-blue-300', + 'identified': 'bg-yellow-900/30 text-yellow-300', + 'monitoring': 'bg-orange-900/30 text-orange-300', + 'scheduled': 'bg-purple-900/30 text-purple-300' + }; + + const isScheduled = incident.isScheduled && (incident.scheduledStart || incident.scheduledEnd); + let scheduledTimeHtml = ''; + + if (isScheduled) { + if (incident.scheduledStart && incident.scheduledEnd) { + scheduledTimeHtml = ` +
+

+ + Scheduled: ${formatScheduledTime(incident.scheduledStart)} - ${formatScheduledTime(incident.scheduledEnd)} +

+
+ `; + } else if (incident.scheduledStart) { + scheduledTimeHtml = ` +
+

+ + Starts: ${formatScheduledTime(incident.scheduledStart)} +

+
+ `; + } + } + + return ` +
+
+

${incident.title}

+ ${incident.status.toUpperCase()} +
+

${incident.description}

+ ${scheduledTimeHtml} +

Reported: ${new Date(incident.createdAt).toLocaleString()}

+
+ `; + }).join('')} +
+ `; +} + +// Display incident history (all incidents) +function displayIncidentHistory(incidents) { + const historyContainer = document.getElementById('incident-history'); + if (!historyContainer) return; + + // Sort by creation date (newest first) + const sortedIncidents = [...incidents].sort((a, b) => + new Date(b.createdAt) - new Date(a.createdAt) + ); + + if (sortedIncidents.length === 0) { + historyContainer.innerHTML = '
No incidents have been reported
'; + return; + } + + historyContainer.innerHTML = ` +
+ ${sortedIncidents.map(incident => { + const severityColors = { + 'minor': 'bg-yellow-900/20 border-yellow-700', + 'major': 'bg-orange-900/20 border-orange-700', + 'critical': 'bg-red-900/20 border-red-700' + }; + + const statusIcons = { + 'investigating': 'πŸ”', + 'identified': '⚠️', + 'monitoring': 'πŸ‘οΈ', + 'resolved': 'βœ…', + 'scheduled': 'πŸ“…' + }; + + const isResolved = incident.status === 'resolved'; + const isScheduled = incident.isScheduled && (incident.scheduledStart || incident.scheduledEnd); + let scheduledTimeHtml = ''; + + if (isScheduled) { + if (incident.scheduledStart && incident.scheduledEnd) { + scheduledTimeHtml = ` +

+ + Scheduled: ${formatScheduledTime(incident.scheduledStart)} - ${formatScheduledTime(incident.scheduledEnd)} +

+ `; + } else if (incident.scheduledStart) { + scheduledTimeHtml = ` +

+ + Starts: ${formatScheduledTime(incident.scheduledStart)} +

+ `; + } + } + + return ` +
+
+
+ ${statusIcons[incident.status] || 'β€’'} +

${incident.title}

+
+
+ ${incident.severity.toUpperCase()} + ${incident.status.toUpperCase()} +
+
+

${incident.description}

+ ${scheduledTimeHtml} +

Reported: ${new Date(incident.createdAt).toLocaleString()}

+
+ `; + }).join('')} +
+ `; +} + +// Page switching +function switchPage(page, options = {}) { + const pageAliases = { home: '/', status: '/uptime', blog: '/blog' }; + const normalizedPage = page === 'uptime' ? 'status' : page; + const pageEl = document.getElementById(`page-${normalizedPage}`); + const tabEl = document.getElementById(`tab-${normalizedPage}`); + if (!pageEl || !tabEl) return; + + // Hide all pages + document.querySelectorAll('.page').forEach(p => p.classList.remove('active')); + document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active')); + + // Show selected page + pageEl.classList.add('active'); + tabEl.classList.add('active'); + + if (window.history && window.history.pushState && options.pushState !== false && pageAliases[normalizedPage] && location.pathname !== pageAliases[normalizedPage]) { + const hash = normalizedPage === 'status' ? (location.hash || '') : ''; + window.history.pushState({ page: normalizedPage }, '', pageAliases[normalizedPage] + hash); + } + + const pageTitles = { home: 'Apps', status: 'Uptime', blog: 'Blog' }; + document.title = `${pageTitles[normalizedPage] || 'Status'} Β· LocalPing`; + + // Load blog posts if switching to blog page + if (normalizedPage === 'blog') { + loadBlogPosts(); + } + + if (normalizedPage === 'status') { + openDeepLinkedMonitor(); + } +} + +function pageFromLocation() { + const pathname = (location.pathname || '/').replace(/\/+$/, '') || '/'; + if (pathname === '/uptime') return 'status'; + if (pathname === '/blog') return 'blog'; + return 'home'; +} + +window.addEventListener('popstate', () => switchPage(pageFromLocation(), { pushState: false })); +window.addEventListener('hashchange', () => { + const page = pageFromLocation(); + switchPage(page, { pushState: false }); + if (page === 'status') openDeepLinkedMonitor(); +}); + +function openDeepLinkedMonitor() { + const monitorId = new URLSearchParams((location.hash || '').replace(/^#/, '')).get('monitor'); + if (!monitorId) { + lastDeepLinkedMonitorId = null; + return; + } + const serviceEl = document.getElementById(`service-${monitorId}`); + if (!serviceEl) return; + const needsOpen = expandedServiceId !== monitorId; + if (needsOpen) toggleServiceExpand(monitorId, { preserveHash: true }); + if (!needsOpen && lastDeepLinkedMonitorId === monitorId) return; + lastDeepLinkedMonitorId = monitorId; + requestAnimationFrame(() => { + serviceEl.scrollIntoView({ behavior: 'smooth', block: 'center' }); + }); +} + +// ==================== APPS PAGE ==================== + +function displayApps(targets) { + const pageHome = document.getElementById('apps-content') || document.getElementById('page-home'); + + const appTargets = targets.filter(t => t.enabled !== false && t.publicVisible !== false); + const structureKey = appTargets.map(t => `${t._id}:${t.name}:${t.appUrl || ''}:${t.appIcon || ''}:${t.position || 0}:${t.group || ''}:${t.publicShowAppLink !== false}:${JSON.stringify(t.quickCommands || [])}`).join('|'); + if (lastAppsStructureKey === structureKey) { + updateAppCardStatuses(appTargets); + return; + } + lastAppsStructureKey = structureKey; + + // Check if there are ANY targets at all + if (appTargets.length === 0) { + pageHome.innerHTML = ` +
+

Welcome to LocalPing

+

Get started by adding monitors

+
+
+
+
+ + + +
+

No Monitors Yet

+

+ Start monitoring your homelab services and apps. Add monitors to track the status, uptime, and performance of your infrastructure. +

+
+

+ Step 1: Go to the admin panel +

+ + + Open Admin Panel + +

+ + You'll be able to add monitors and configure their settings there. +

+
+
+
+ `; + return; + } + + // Separate targets into apps and services + // Only show apps if publicShowAppLink is true (default true) + const apps = appTargets.filter(t => (t.appUrl || t.appIcon) && (t.publicShowAppLink !== false)); + const appCount = apps.length; + + if (appCount === 0) { + pageHome.innerHTML = ` +
+

Apps

+

(0 apps)

+
+
+

No apps configured with icons. You have ${appTargets.length} monitor${appTargets.length !== 1 ? 's' : ''} on the Uptime tab.

+
+ `; + return; + } + + // Sort apps by position, then by name + const sortedApps = [...apps].sort((a, b) => { + const posA = a.position || 0; + const posB = b.position || 0; + if (posA !== posB) return posA - posB; + return a.name.localeCompare(b.name); + }); + + // Group apps by category + const groupedApps = {}; + const ungroupedApps = []; + + sortedApps.forEach(app => { + if (app.group) { + if (!groupedApps[app.group]) { + groupedApps[app.group] = []; + } + groupedApps[app.group].push(app); + } else { + ungroupedApps.push(app); + } + }); + + // Build the UI with search bar and grouped apps + let html = ` +
+

Apps

+

(${appCount} app${appCount !== 1 ? 's' : ''})

+
+ + +
+ +

+ Type a service name to filter, or use / commands. Example: /jellyfin opens Jellyfin instantly. +

+
+ `; + + // Display ungrouped apps first + if (ungroupedApps.length > 0) { + html += '
'; + html += ungroupedApps.map(app => buildAppCard(app)).join(''); + html += '
'; + } + + // Display grouped apps + Object.entries(groupedApps).forEach(([group, appsInGroup]) => { + html += ` +
+

${escapeHtml(group)}

+
+ ${appsInGroup.map(app => buildAppCard(app)).join('')} +
+
+ `; + }); + + pageHome.innerHTML = html; + + // Attach event listeners + setupAppCardListeners(); + setupSearchAndCommands(sortedApps); +} + +function updateAppCardStatuses(targets) { + const cardsById = new Map(Array.from(document.querySelectorAll('.app-card[data-app-id]')) + .map(card => [String(card.dataset.appId), card])); + targets.forEach((target) => { + const card = cardsById.get(String(target._id)); + if (!card) return; + const down = target.currentStatus === 'down'; + card.dataset.isDown = String(down); + const statusEl = card.querySelector('.app-status'); + if (!statusEl) return; + const nextText = down ? 'Down' : target.currentStatus === 'up' ? 'Up' : 'Checking'; + if (down && statusEl.tagName !== 'BUTTON') { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'app-status down'; + button.dataset.monitorLink = target._id; + button.setAttribute('aria-label', `View ${target.name} uptime`); + button.textContent = nextText; + statusEl.replaceWith(button); + setupAppCardListeners(); + return; + } + if (!down && statusEl.tagName === 'BUTTON') { + const span = document.createElement('span'); + span.className = 'app-status up'; + span.textContent = nextText; + statusEl.replaceWith(span); + return; + } + const statusClass = down ? 'down' : target.currentStatus === 'up' ? 'up' : 'unknown'; + statusEl.className = `app-status ${statusClass}`; + statusEl.textContent = nextText; + if (down) { + statusEl.setAttribute('role', 'button'); + statusEl.setAttribute('tabindex', '0'); + } else { + statusEl.removeAttribute('role'); + statusEl.removeAttribute('tabindex'); + } + }); +} + +function buildAppCard(app) { + const isDown = app.currentStatus === 'down'; + const statusClass = isDown ? 'down' : app.currentStatus === 'up' ? 'up' : 'unknown'; + const statusText = isDown ? 'Down' : app.currentStatus === 'up' ? 'Up' : 'Checking'; + + // Determine icon - prioritize appIcon (manually configured), then cached favicon, then API favicon, then fallback icon + let iconHTML = ''; + + if (app.appIcon) { + // Use manually configured app icon - proxy it + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(app.appIcon)}`; + iconHTML = buildIconImage(proxyUrl, app.name, 'app-favicon', 'handleIconError'); + } else { + const cachedFavicon = faviconCache[app.appUrl]; + + if (cachedFavicon) { + // If favicon is a data URL (base64), use it directly, otherwise proxy it + if (cachedFavicon.startsWith('data:')) { + iconHTML = buildIconImage(cachedFavicon, app.name, 'app-favicon', 'handleIconError'); + } else { + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(cachedFavicon)}`; + iconHTML = buildIconImage(proxyUrl, app.name, 'app-favicon', 'handleIconError'); + } + } else if (app.favicon) { + faviconCache[app.appUrl] = app.favicon; + // If favicon is a data URL (base64), use it directly, otherwise proxy it + if (app.favicon.startsWith('data:')) { + iconHTML = buildIconImage(app.favicon, app.name, 'app-favicon', 'handleIconError'); + } else { + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(app.favicon)}`; + iconHTML = buildIconImage(proxyUrl, app.name, 'app-favicon', 'handleIconError'); + } + } else { + // Fallback to Font Awesome icon + const fallbackIcon = getIconForApp(app.name); + iconHTML = ``; + } + } + + return ` +
+
+ ${iconHTML} +
+
${escapeHtml(app.name)}
+ ${isDown ? '' : '' + statusText + ''} +
+ `; +} + +// Handle icon loading errors +function handleIconError(img, appName = img?.dataset?.iconName || '') { + // Replace failed image with fallback icon + const fallbackIcon = getIconForApp(appName); + img.outerHTML = ``; +} + +// Get icon HTML for a service/monitor +function getServiceIconHTML(target) { + let iconHTML = ''; + + if (target.appIcon) { + // Use manually configured app icon - proxy it + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(target.appIcon)}`; + iconHTML = buildIconImage(proxyUrl, target.name, 'service-favicon', 'handleServiceIconError'); + } else if (target.appUrl) { + const cachedFavicon = faviconCache[target.appUrl]; + + if (cachedFavicon) { + // If favicon is a data URL (base64), use it directly, otherwise proxy it + if (cachedFavicon.startsWith('data:')) { + iconHTML = buildIconImage(cachedFavicon, target.name, 'service-favicon', 'handleServiceIconError'); + } else { + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(cachedFavicon)}`; + iconHTML = buildIconImage(proxyUrl, target.name, 'service-favicon', 'handleServiceIconError'); + } + } else if (target.favicon) { + faviconCache[target.appUrl] = target.favicon; + // If favicon is a data URL (base64), use it directly, otherwise proxy it + if (target.favicon.startsWith('data:')) { + iconHTML = buildIconImage(target.favicon, target.name, 'service-favicon', 'handleServiceIconError'); + } else { + const proxyUrl = `/api/proxy-icon?url=${encodeURIComponent(target.favicon)}`; + iconHTML = buildIconImage(proxyUrl, target.name, 'service-favicon', 'handleServiceIconError'); + } + } else { + // Fallback to Font Awesome icon + const fallbackIcon = getIconForApp(target.name); + iconHTML = ``; + } + } else { + // Fallback to Font Awesome icon + const fallbackIcon = getIconForApp(target.name); + iconHTML = ``; + } + + return iconHTML; +} + +// Handle service icon loading errors +function handleServiceIconError(img, serviceName = img?.dataset?.iconName || '') { + // Replace failed image with fallback icon + const fallbackIcon = getIconForApp(serviceName); + img.outerHTML = ``; +} + +function setupAppCardListeners() { + document.querySelectorAll('.app-status.down[data-monitor-link]').forEach(status => { + if (status.dataset.listenersBound === 'true') return; + status.dataset.listenersBound = 'true'; + status.addEventListener('click', (event) => { + event.preventDefault(); + event.stopPropagation(); + openMonitorFromApps(status.dataset.monitorLink); + }); + status.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + event.stopPropagation(); + openMonitorFromApps(status.dataset.monitorLink); + } + }); + }); + + // Add event listeners for left-click and middle-click + document.querySelectorAll('.app-card[data-app-url]').forEach(card => { + if (card.dataset.listenersBound === 'true') return; + card.dataset.listenersBound = 'true'; + card.style.cursor = 'pointer'; + + card.addEventListener('mousedown', (e) => { + const url = card.getAttribute('data-app-url'); + + if (e.button === 0) { + // Left click - will be handled by click event + } else if (e.button === 1) { + // Middle click - open in background tab without focus + e.preventDefault(); + window.open(url, '_blank'); + } else if (e.button === 2) { + // Right click - let context menu handle it + e.preventDefault(); + window.open(url, '_blank'); + } + }); + + card.addEventListener('click', (e) => { + // Handle left click + if (e.button === 0 && !e.target.closest('.app-status.down')) { + const url = card.getAttribute('data-app-url'); + if (url) window.open(url, '_blank'); + } + }); + }); +} + +function openMonitorFromApps(serviceId) { + if (!serviceId) return; + const hash = `#monitor=${encodeURIComponent(serviceId)}`; + if (window.history?.pushState) { + window.history.pushState({ page: 'status', monitor: serviceId }, '', `/uptime${hash}`); + } + switchPage('status', { pushState: false }); + setTimeout(openDeepLinkedMonitor, 0); +} + +function setupSearchAndCommands(allApps) { + const searchInput = document.getElementById('search-input'); + if (!searchInput) return; + + let suggestedCommand = null; + + searchInput.addEventListener('keyup', (e) => { + const query = e.target.value.toLowerCase().trim(); + + // Handle quick commands (starting with /) + if (query.startsWith('/')) { + const command = query.substring(1); + + // Find matching command + const matchingApp = findAppByCommand(command, allApps); + + // If exact match found, suggest it + if (matchingApp && e.key !== 'Enter') { + suggestedCommand = matchingApp; + showCommandSuggestion(matchingApp, command); + } else { + hideCommandSuggestion(); + } + + // Show all apps when typing a command + const allCards = document.querySelectorAll('.app-card'); + allCards.forEach(card => { + card.style.display = ''; + }); + return; + } + + hideCommandSuggestion(); + + // Filter apps based on search query (only for non-command searches) + if (query.length === 0) { + const allCards = document.querySelectorAll('.app-card'); + allCards.forEach(card => { + card.style.display = ''; + }); + } else { + const allCards = document.querySelectorAll('.app-card'); + allCards.forEach(card => { + const appName = card.getAttribute('data-app-name') || ''; + const quickCommands = card.getAttribute('data-quick-commands') || ''; + const matches = appName.includes(query) || quickCommands.includes(query); + card.style.display = matches ? '' : 'none'; + }); + } + }); + + searchInput.addEventListener('keydown', (e) => { + const query = e.target.value.toLowerCase().trim(); + + // Tab completion for commands + if (e.key === 'Tab') { + e.preventDefault(); + + if (query.startsWith('/')) { + const command = query.substring(1); + const matchingApp = findAppByCommand(command, allApps); + + if (matchingApp) { + // Use the first quick command or the app name + const fullCommand = matchingApp.quickCommands?.[0] || matchingApp.name.toLowerCase(); + searchInput.value = `/${fullCommand}`; + suggestedCommand = null; + hideCommandSuggestion(); + } + } + return; + } + + // Enter key handling + if (e.key === 'Enter') { + const query = e.target.value.toLowerCase().trim(); + + if (query.startsWith('/')) { + e.preventDefault(); + const command = query.substring(1); + handleQuickCommand(command, allApps); + e.target.value = ''; + hideCommandSuggestion(); + } else { + // DuckDuckGo search + e.preventDefault(); + window.open(`https://duckduckgo.com/?q=${encodeURIComponent(query)}`, '_blank'); + e.target.value = ''; + } + } + }); +} + +function findAppByCommand(command, allApps) { + const lowerCommand = command.toLowerCase(); + + // First try exact match with quick commands + for (const app of allApps) { + const quickCommands = (app.quickCommands || []).map(c => c.toLowerCase()); + if (quickCommands.some(c => c.startsWith(lowerCommand))) { + return app; + } + } + + // Then try partial match with app names + for (const app of allApps) { + const appName = app.name.toLowerCase(); + if (appName.startsWith(lowerCommand)) { + return app; + } + } + + return null; +} + +function showCommandSuggestion(app, partialCommand) { + let suggestionEl = document.getElementById('command-suggestion'); + + if (!suggestionEl) { + suggestionEl = document.createElement('div'); + suggestionEl.id = 'command-suggestion'; + suggestionEl.style.cssText = ` + background: rgba(15, 23, 42, 0.95); + border: 1px solid rgba(148, 163, 184, 0.3); + border-radius: 0.5rem; + padding: 0.75rem 1rem; + margin-top: 0.5rem; + margin-bottom: 0.5rem; + font-size: 0.875rem; + color: #cbd5e1; + z-index: 10; + white-space: nowrap; + max-width: 300px; + overflow: hidden; + text-overflow: ellipsis; + `; + const searchInput = document.getElementById('search-input'); + searchInput.parentNode.insertBefore(suggestionEl, searchInput.nextSibling); + } + + const suggestedCommand = app.quickCommands?.[0] || app.name.toLowerCase(); + const remaining = suggestedCommand.substring(partialCommand.length); + + suggestionEl.innerHTML = `Press Tab to complete: /${suggestedCommand}`; + suggestionEl.style.display = 'block'; +} + +function hideCommandSuggestion() { + const suggestionEl = document.getElementById('command-suggestion'); + if (suggestionEl) { + suggestionEl.style.display = 'none'; + } +} + +function handleQuickCommand(command, allApps) { + const lowerCommand = command.toLowerCase(); + + // Search for matching app by quick command or name + for (const app of allApps) { + const quickCommands = (app.quickCommands || []).map(c => c.toLowerCase()); + const appName = app.name.toLowerCase(); + + // Check if command matches quick command or app name + if (quickCommands.includes(lowerCommand) || appName === lowerCommand) { + if (!app.isUp) { + alert(`${app.name} is currently down and cannot be opened.`); + return; + } + + if (app.appUrl) { + window.open(app.appUrl, '_blank'); + return; + } + } + } + + // Command not found + alert(`Service not found. Try one of these commands:\n${allApps + .filter(a => a.appUrl) + .slice(0, 5) + .map(a => `/${a.quickCommands?.[0] || a.name.toLowerCase()}`) + .join('\n')}`); +} + +function getIconForApp(appName, customIcon) { + if (customIcon) return customIcon; + + const iconMap = { + 'nginx': 'fa-server', + 'apache': 'fa-server', + 'docker': 'fa-docker', + 'kubernetes': 'fa-cube', + 'prometheus': 'fa-chart-line', + 'grafana': 'fa-chart-area', + 'jenkins': 'fa-gears', + 'gitlab': 'fa-gitlab', + 'github': 'fa-github', + 'gitea': 'fa-git-alt', + 'sonarqube': 'fa-code', + 'vault': 'fa-lock', + 'consul': 'fa-sitemap', + 'minio': 'fa-database', + 'postgresql': 'fa-database', + 'mysql': 'fa-database', + 'sqlite': 'fa-database', + 'redis': 'fa-database', + 'elasticsearch': 'fa-search', + 'kibana': 'fa-chart-line', + 'nexus': 'fa-box', + 'artifactory': 'fa-box', + 'portainer': 'fa-docker', + 'pihole': 'fa-shield-alt', + 'adguard': 'fa-shield-alt', + 'jellyfin': 'fa-film', + 'plex': 'fa-film', + 'kodi': 'fa-tv', + 'emby': 'fa-film', + 'nextcloud': 'fa-cloud', + 'synology': 'fa-hdd', + 'qnap': 'fa-hdd', + 'home assistant': 'fa-home', + 'homebridge': 'fa-home', + 'openwrt': 'fa-network-wired', + 'unifi': 'fa-wifi', + 'piaware': 'fa-plane', + 'resin': 'fa-flask', + 'wireguard': 'fa-lock', + 'openvpn': 'fa-lock', + }; + + const lowerName = appName.toLowerCase(); + for (const [key, icon] of Object.entries(iconMap)) { + if (lowerName.includes(key)) { + return icon; + } + } + + // Default icon + return 'fa-cube'; +} + +function openApp(url) { + if (url) { + window.open(url, '_blank'); + } +} + +// ==================== STATUS PAGE ==================== + +async function getTargetUptime(targetId) { + // Use cached data from consolidated endpoint if available + const target = allTargets.find(t => t._id === targetId); + if (target && target.uptime) { + return target.uptime['30d']?.uptime || 0; + } + + if (targetUptimeCache[targetId]) { + return targetUptimeCache[targetId]; + } + + try { + const res = await axios.get(`/api/targets/${targetId}/uptime?days=30`); + const uptime = res.data.uptime; + targetUptimeCache[targetId] = uptime; + return uptime; + } catch (error) { + console.error('Error fetching uptime:', error); + return 0; + } +} + +async function getTargetCurrentPing(targetId) { + // Try to get from cached data first (we don't cache individual ping, but we can skip the request) + // For now, return 0 as we don't have current ping in the consolidated endpoint + // This can be enhanced later if needed + return 0; +} + +async function loadAndDisplayPing(targetId) { + const ping = await getTargetCurrentPing(targetId); + const el = document.querySelector(`.ping-${targetId}`); + if (el) { + if (ping > 0) { + el.textContent = ping.toFixed(0) + 'ms'; + } else { + el.textContent = '-'; + } + } +} + +function updateServicesList(targets) { + const list = document.getElementById('services-list'); + const countEl = document.getElementById('service-count'); + + if (!list) return; + + // Admins get the complete configured monitor inventory. Public visitors see + // only enabled monitors explicitly exposed on the status page. + const deepLinkedMonitorId = new URLSearchParams((location.hash || '').replace(/^#/, '')).get('monitor'); + const visibleTargets = targets.filter(t => viewerIsAdmin || ( + t.enabled !== false && + t.publicVisible !== false && + (t.publicShowStatus !== false || String(t._id) === String(deepLinkedMonitorId || '')) + )); + + // Show all targets in status page + if (visibleTargets.length === 0) { + // Only clear if we're not on the status page or if there are no existing services + const existingServices = list.querySelectorAll('.service-item'); + if (existingServices.length === 0) { + list.innerHTML = '
No services found
'; + } + countEl.textContent = '(0)'; + return; + } + + countEl.textContent = `(${visibleTargets.length})`; + + // Check if services list is still showing loading message (only clear if it's the ONLY content) + const loadingMsg = list.querySelector('.text-center.text-slate-400'); + if (loadingMsg && list.children.length === 1) { + // Only clear if this is the only child (the loading message) + list.innerHTML = ''; + } + + // Get list of existing service IDs to track what needs to be removed + const existingServiceIds = new Set(); + list.querySelectorAll('.service-item').forEach(el => { + const id = el.id.replace('service-', ''); + if (id) existingServiceIds.add(id); + }); + + // Update each service row dynamically without re-rendering + visibleTargets.forEach(target => { + existingServiceIds.delete(target._id); // Mark as still existing + const serviceEl = document.getElementById(`service-${target._id}`); + + if (!serviceEl) { + // If service doesn't exist, add it using appendChild to preserve DOM state + const tempDiv = document.createElement('div'); + tempDiv.innerHTML = createServiceElement(target); + const newServiceEl = tempDiv.firstElementChild; + list.appendChild(newServiceEl); + const newMiniGraph = newServiceEl.querySelector('.service-mini-graph'); + if (newMiniGraph) { + newMiniGraph._miniKey = miniGraphDataKey(target); + newMiniGraph._miniStatus = target.currentStatus || 'unknown'; + } + + // If this service should be expanded, restore its expanded state + if (expandedServiceId === target._id) { + const wrapper = document.getElementById(`details-wrapper-${target._id}`); + const row = newServiceEl.querySelector('.service-row'); + const icon = row ? row.querySelector('.expand-icon') : null; + + if (wrapper) wrapper.classList.add('open'); + if (row) row.classList.add('expanded'); + if (icon) icon.classList.add('rotated'); + + // Load details if not already loaded + const contentEl = document.getElementById(`service-content-${target._id}`); + if (contentEl && contentEl.innerHTML.includes('Loading details...')) { + loadServiceDetails(target._id); + } + } + } else { + // Update existing service - preserve expanded state at all costs + const isDown = target.currentStatus === 'down'; + + const row = serviceEl.querySelector('.service-row'); + if (!row) return; // Safety check + + const wrapper = document.getElementById(`details-wrapper-${target._id}`); + const icon = row?.querySelector('.expand-icon'); + const iconEl = row.querySelector('.service-icon'); + + // Update icon if it exists + if (iconEl && iconEl.dataset.iconKey !== serviceIconKey(target)) { + const newIconHTML = getServiceIconHTML(target); + iconEl.innerHTML = newIconHTML; + iconEl.dataset.iconKey = serviceIconKey(target); + } + + // Keep the row itself as the status signal. Down monitors get a subtle + // red wash and the graph adds the explicit "Down" label. + serviceEl.classList.toggle('service-item-down', isDown); + updateServiceMiniGraph(target, serviceEl); + + // CRITICAL: Always preserve expanded state - never close if it's expanded + const isExpanded = expandedServiceId === target._id; + if (isExpanded) { + // Force open state - don't check, just ensure it's open + if (wrapper) wrapper.classList.add('open'); + if (row) row.classList.add('expanded'); + if (icon) icon.classList.add('rotated'); + } else { + // Only close if it's not supposed to be expanded + if (wrapper && wrapper.classList.contains('open')) { + wrapper.classList.remove('open'); + } + if (row && row.classList.contains('expanded')) { + row.classList.remove('expanded'); + } + if (icon) icon.classList.remove('rotated'); + } + + } + }); + + // Remove services that no longer exist (but preserve expanded state if it's the expanded one) + if (expandedServiceId && !visibleTargets.some(target => String(target._id) === String(expandedServiceId))) { + if (charts[expandedServiceId]) { + charts[expandedServiceId].destroy(); + delete charts[expandedServiceId]; + } + delete chartPeriods[expandedServiceId]; + expandedServiceId = null; + } + existingServiceIds.forEach(serviceId => { + const serviceEl = document.getElementById(`service-${serviceId}`); + if (serviceEl) { + serviceEl.remove(); + } + }); + + // Update expanded service details if one is open - do this AFTER all DOM updates + if (expandedServiceId) { + // Use setTimeout to ensure DOM is stable + setTimeout(() => { + loadServiceDetailsUpdate(expandedServiceId); + }, 0); + } +} + +function createServiceElement(target) { + const isDown = target.currentStatus === 'down'; + const isExpanded = expandedServiceId === target._id; + + // Get icon HTML for the service + const iconHTML = getServiceIconHTML(target); + + return ` +
+
+
+ ${iconHTML} +
+
+
${escapeHtml(target.name)}
+
+
+ ${buildMiniGraphMarkup(target)} +
+
+ +
+
+
Loading details...
+
+
+
+ `; +} + +function updateServiceMiniGraph(target, serviceEl) { + const graphEl = serviceEl?.querySelector('.service-mini-graph'); + if (!graphEl) return; + + const dataKey = miniGraphDataKey(target); + const status = target.currentStatus || 'unknown'; + if (graphEl._miniKey === dataKey && graphEl._miniStatus === status) return; + + graphEl._miniKey = dataKey; + graphEl._miniStatus = status; + graphEl.innerHTML = buildMiniGraphContent(target); +} + +async function loadAndDisplayUptime(targetId) { + const uptime = await getTargetUptime(targetId); + const el = document.querySelector(`.uptime-${targetId}`); + if (el) { + el.textContent = uptime + '%'; + } +} + +async function loadAndDisplayUptimeBars(targetId) { + try { + // Daily bars are detail data. Fetch them only when the monitor's detail + // view asks for them instead of including them in the landing-page + // summary for every monitor. + const stats = await getGraphData(targetId, '30d'); + + // Get the uptime bar container + const serviceEl = document.getElementById(`service-${targetId}`); + if (!serviceEl) return; + + const uptimeBar = serviceEl.querySelector('.uptime-bar'); + if (!uptimeBar) return; + + // Clear loading segments and rebuild with actual data + let html = ''; + stats.forEach(stat => { + const isUp = stat.successfulPings > 0; + const status = isUp ? 'up' : 'down'; + const uptime = stat.successfulPings > 0 ? ((stat.successfulPings / stat.totalPings) * 100).toFixed(0) : 0; + html += `
`; + }); + + // If no stats yet, show loading state + if (stats.length === 0) { + html = ''; + for (let i = 0; i < 40; i++) { + html += `
`; + } + } + + uptimeBar.innerHTML = html; + } catch (error) { + console.error('Error loading uptime bars:', error); + } +} + +function generateUptimeBars(targetId) { + let html = ''; + for (let i = 0; i < 40; i++) { + html += `
`; + } + return `
${html}
`; +} + +function toggleServiceExpand(serviceId, options = {}) { + // A deep link owns the hash while it is being resolved. A normal user click + // should release that ownership so the next polling refresh cannot reopen a + // row the user deliberately collapsed or replace it with another row. + if (!options.preserveHash) { + const hashMonitorId = new URLSearchParams((location.hash || '').replace(/^#/, '')).get('monitor'); + if (hashMonitorId) { + const url = `${location.pathname}${location.search}`; + if (window.history?.replaceState) window.history.replaceState({}, '', url); + lastDeepLinkedMonitorId = null; + } + } + + // If clicking the same service, close it + if (expandedServiceId === serviceId) { + expandedServiceId = null; + const wrapper = document.getElementById(`details-wrapper-${serviceId}`); + const row = document.querySelector(`#service-${serviceId} .service-row`); + const icon = row?.querySelector('.expand-icon'); + + if (wrapper) { + wrapper.classList.remove('open'); + } + if (row) { + row.classList.remove('expanded'); + } + if (icon) { + icon.classList.remove('rotated'); + } + } else { + // Close previous expanded service + if (expandedServiceId) { + const prevWrapper = document.getElementById(`details-wrapper-${expandedServiceId}`); + const prevRow = document.querySelector(`#service-${expandedServiceId} .service-row`); + const prevIcon = prevRow?.querySelector('.expand-icon'); + + if (prevWrapper) { + prevWrapper.classList.remove('open'); + } + if (prevRow) { + prevRow.classList.remove('expanded'); + } + if (prevIcon) { + prevIcon.classList.remove('rotated'); + } + } + + // Open new service + expandedServiceId = serviceId; + const wrapper = document.getElementById(`details-wrapper-${serviceId}`); + const row = document.querySelector(`#service-${serviceId} .service-row`); + const icon = row?.querySelector('.expand-icon'); + + if (wrapper) { + wrapper.classList.add('open'); + } + if (row) { + row.classList.add('expanded'); + } + if (icon) { + icon.classList.add('rotated'); + } + + // Load the details + loadServiceDetails(serviceId); + } +} + +async function loadServiceDetails(serviceId) { + const target = allTargets.find(t => t._id === serviceId); + if (!target) return; + + const contentEl = document.getElementById(`service-content-${serviceId}`); + + try { + // Replacing the details markup also replaces the canvas. Destroy the + // previous Chart.js instance first so it cannot keep rendering to a + // detached canvas when a user collapses and reopens a service. + if (charts[serviceId]) { + charts[serviceId].destroy(); + delete charts[serviceId]; + } + + // Use cached uptime data if available, otherwise fetch + let uptime24h = 0; + let uptime30d = 0; + + if (target.uptime) { + uptime24h = parseFloat(target.uptime['24h']?.uptime || 0); + uptime30d = parseFloat(target.uptime['30d']?.uptime || 0); + } else { + // Fallback: fetch if not in cache + const statsResponse = await axios.get(`/api/targets/${serviceId}/statistics?period=24h`); + const uptimeData = statsResponse.data.uptime || {}; + uptime24h = parseFloat(uptimeData['24h']?.uptime || 0); + uptime30d = parseFloat(uptimeData['30d']?.uptime || 0); + } + + // Chart data will be loaded separately when needed (only when details are expanded) + + contentEl.innerHTML = ` +
+ +
+
+

Current Status

+

${!target.enabled ? 'PAUSED' : target.currentStatus === 'up' ? 'βœ“ UP' : target.currentStatus === 'down' ? 'βœ— DOWN' : 'CHECKING'}

+
+
+

Uptime (24h)

+

${uptime24h.toFixed(2)}%

+
+
+

Uptime (30d)

+

${uptime30d.toFixed(2)}%

+
+ ${target.publicShowDetails ? ` +
+

Protocol

+

${escapeHtml(target.protocol)}

+
+ ` : ''} +
+ + + +
+ + + + + +
+ + +
+
+

Response Time & Status

+
+
+
+ Response Time +
+
+
+ Downtime +
+
+
+
+ +
+
+
+ `; + + // Load initial chart + setTimeout(() => { + loadServiceChart(serviceId, '24h'); + }, 100); + } catch (error) { + console.error('Error loading service details:', error); + contentEl.innerHTML = `
Error loading details
`; + } +} + +async function loadServiceDetailsUpdate(serviceId) { + const target = allTargets.find(t => t._id === serviceId); + if (!target) return; + + try { + // Ensure wrapper stays open if this is the expanded service + const wrapper = document.getElementById(`details-wrapper-${serviceId}`); + if (expandedServiceId === serviceId && wrapper) { + wrapper.classList.add('open'); + } + + // Only update the values if the details panel exists + const contentEl = document.getElementById(`service-content-${serviceId}`); + if (!contentEl) { + // If content doesn't exist but service is expanded, load it + if (expandedServiceId === serviceId) { + loadServiceDetails(serviceId); + } + return; + } + + // Uptime summaries are already part of the consolidated payload. Avoid a + // second database request on every status refresh. + const uptimeData = target.uptime || {}; + + const uptime24h = parseFloat(uptimeData['24h']?.uptime || 0).toFixed(2); + const uptime30d = parseFloat(uptimeData['30d']?.uptime || 0).toFixed(2); + + // Update values dynamically + const uptime24hEl = contentEl.querySelector(`.uptime-24h-${serviceId}`); + const uptime30dEl = contentEl.querySelector(`.uptime-30d-${serviceId}`); + + // Find status element - it's in the first compact stat card + const statusEl = contentEl.querySelector('.monitor-current-status'); + + if (uptime24hEl) uptime24hEl.textContent = uptime24h + '%'; + if (uptime30dEl) uptime30dEl.textContent = uptime30d + '%'; + + // Update status if changed + if (statusEl) { + const isUp = target.currentStatus === 'up'; + const isDown = target.currentStatus === 'down'; + statusEl.className = `monitor-current-status text-base font-bold leading-tight whitespace-nowrap ${isUp ? 'text-green-400' : isDown ? 'text-red-400' : 'text-slate-400'}`; + statusEl.textContent = !target.enabled ? 'PAUSED' : isUp ? 'βœ“ UP' : isDown ? 'βœ— DOWN' : 'CHECKING'; + } + + // Update chart data dynamically if chart exists + if (charts[serviceId] && chartPeriods[serviceId]) { + await updateChartData(serviceId, chartPeriods[serviceId]); + } else if (contentEl.querySelector(`#chart-${serviceId}`)) { + // Chart canvas exists but chart wasn't created yet, create it now + const currentPeriod = chartPeriods[serviceId] || '24h'; + await loadServiceChart(serviceId, currentPeriod); + } + } catch (error) { + console.error('Error updating service details:', error); + } +} + +async function switchChartPeriod(serviceId, period) { + // Update button states + const buttons = document.querySelectorAll(`#service-content-${serviceId} .period-btn`); + buttons.forEach(btn => { + if (btn.dataset.period === period) { + btn.className = 'period-btn px-4 py-2 rounded-lg text-xs font-medium bg-gradient-to-r from-cyan-600 to-cyan-500 text-white shadow-lg shadow-cyan-500/30 transition-all duration-200 border border-cyan-500/50'; + } else { + btn.className = 'period-btn px-4 py-2 rounded-lg text-xs font-medium bg-slate-700/50 hover:bg-slate-600/70 text-slate-300 transition-all duration-200 border border-slate-600/50'; + } + }); + + await loadServiceChart(serviceId, period); +} + +async function updateChartData(serviceId, period) { + try { + const chart = charts[serviceId]; + if (!chart) return; + + // Fetch real statistics from the API with period parameter + const statistics = await getGraphData(serviceId, period); + + // Parse and sort statistics chronologically (oldest first = left to right) + const sortedStats = [...statistics] + .map(stat => ({ + ...stat, + dateObj: new Date(stat.date) // Parse date once + })) + .sort((a, b) => a.dateObj.getTime() - b.dateObj.getTime()); // Sort chronologically (oldest first) + + const labels = []; + const responseTimeData = []; + + sortedStats.forEach(stat => { + const date = stat.dateObj; + if (period === '1h') { + // 1H: Show time only (HH:MM) + labels.push(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })); + } else if (period === '24h') { + // 24H: Show day and time (Mon 15, 14:30) + labels.push(date.toLocaleString([], { weekday: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } else if (period === '7d') { + // 7D: Show date and time (Nov 15, 14:30) + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } else if (period === '30d') { + // 30D: Show date only (Nov 15) + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric' })); + } else { + // Default: Show date and time + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } + + // Leave the response-time series blank during downtime. Chart.js treats + // null as a gap when spanGaps is false, so no green segment is rendered + // through the red downtime region. + const avgResponseTime = stat.avgResponseTime || 0; + const isDown = Number(stat.successfulPings || 0) === 0; + responseTimeData.push(isDown ? null : Math.round(avgResponseTime)); + + }); + + // Calculate max response time for scaling downtime indicator + const validResponseTimes = responseTimeData.filter(v => v > 0); + const maxResponseTime = validResponseTimes.length > 0 ? Math.max(...validResponseTimes) : 100; + const downtimeMaxValue = Math.round(Math.max(maxResponseTime * 1.1, 100)); // Add 10% padding, minimum 100, rounded + + // Scale downtime indicator to max Y value + const scaledDownData = buildDowntimeSeries(sortedStats, downtimeMaxValue); + const downtimeAtIndex = sortedStats.map(stat => Number(stat.successfulPings || 0) === 0); + + // Update chart data dynamically + chart.data.labels = labels; + chart.data.datasets[0].data = responseTimeData; + chart.data.datasets[1].data = scaledDownData; + chart._downtimeAtIndex = downtimeAtIndex; + + // Keep the line clean at every period. A hit radius still allows chart + // interaction without rendering a marker at each sample. + chart.data.datasets[0].pointRadius = 0; + chart.data.datasets[0].pointHoverRadius = 0; + + chart.update('none'); // Update without animation for smooth refresh + } catch (error) { + console.error('Error updating chart data:', error); + } +} + +async function loadServiceChart(serviceId, period) { + try { + const canvas = document.getElementById(`chart-${serviceId}`); + if (!canvas) return; + + // If chart already exists and period hasn't changed, just update the data + if (charts[serviceId] && chartPeriods[serviceId] === period) { + await updateChartData(serviceId, period); + return; + } + + // Fetch real statistics from the API with period parameter + const statistics = await getGraphData(serviceId, period); + + // Parse and sort statistics chronologically (oldest first = left to right) + const sortedStats = [...statistics] + .map(stat => ({ + ...stat, + dateObj: new Date(stat.date) // Parse date once + })) + .sort((a, b) => a.dateObj.getTime() - b.dateObj.getTime()); // Sort chronologically (oldest first) + + const labels = []; + const responseTimeData = []; + + sortedStats.forEach(stat => { + const date = stat.dateObj; + if (period === '1h') { + // 1H: Show time only (HH:MM) + labels.push(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })); + } else if (period === '24h') { + // 24H: Show day and time (Mon 15, 14:30) + labels.push(date.toLocaleString([], { weekday: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } else if (period === '7d') { + // 7D: Show date and time (Nov 15, 14:30) + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } else if (period === '30d') { + // 30D: Show date only (Nov 15) + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric' })); + } else { + // Default: Show date and time + labels.push(date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })); + } + + // Leave the response-time series blank during downtime. Chart.js treats + // null as a gap when spanGaps is false, so no green segment is rendered + // through the red downtime region. + const avgResponseTime = stat.avgResponseTime || 0; + const isDown = Number(stat.successfulPings || 0) === 0; + responseTimeData.push(isDown ? null : Math.round(avgResponseTime)); + + }); + + // Destroy existing chart if any + if (charts[serviceId]) { + charts[serviceId].destroy(); + } + + const ctx = canvas.getContext('2d'); + + // Calculate min/max for better scaling + const validResponseTimes = responseTimeData.filter(v => v > 0); + const minResponseTime = validResponseTimes.length > 0 ? Math.min(...validResponseTimes) : 0; + const maxResponseTime = validResponseTimes.length > 0 ? Math.max(...validResponseTimes) : 100; + const downtimeMaxValue = Math.round(Math.max(maxResponseTime * 1.1, 100)); // Add 10% padding, minimum 100, rounded + + // Scale downtime indicator to max Y value + const scaledDownData = buildDowntimeSeries(sortedStats, downtimeMaxValue); + const downtimeAtIndex = sortedStats.map(stat => Number(stat.successfulPings || 0) === 0); + + // Store the period for this chart + chartPeriods[serviceId] = period; + + charts[serviceId] = new Chart(ctx, { + type: 'line', + data: { + labels, + datasets: [ + { + label: 'Response Time (ms)', + data: responseTimeData, + borderColor: '#10b981', + backgroundColor: 'rgba(16, 185, 129, 0.15)', + fill: true, + tension: 0.5, + pointRadius: 0, + pointHoverRadius: 0, + pointHitRadius: 8, + borderWidth: 3, + spanGaps: false, + order: 1, + }, + { + label: 'Downtime', + data: scaledDownData, + borderColor: '#ef4444', + backgroundColor: 'rgba(239, 68, 68, 0.25)', + fill: true, + tension: 0.3, + pointRadius: 0, + pointHoverRadius: 0, + pointHitRadius: 8, + borderWidth: 0, + spanGaps: false, + order: 0, + }, + ], + }, + options: { + responsive: true, + maintainAspectRatio: false, + interaction: { + mode: 'index', + intersect: false, + }, + plugins: { + legend: { + display: false, + }, + tooltip: buildGraphTooltipOptions() + }, + scales: { + y: { + beginAtZero: true, + max: downtimeMaxValue, // Set max to ensure downtime indicator reaches top + grid: { + color: 'rgba(255, 255, 255, 0.08)', + drawBorder: false, + lineWidth: 1 + }, + ticks: { display: false }, + title: { + display: false + } + }, + x: { + type: 'category', + grid: { + color: 'rgba(255, 255, 255, 0.05)', + drawBorder: false + }, + ticks: { display: false }, + // Ensure chronological order (left = oldest, right = newest) + reverse: false + }, + }, + elements: { + point: { + radius: 0, + hoverRadius: 0, + hoverBorderWidth: 0, + } + }, + animation: { + duration: 1000, + easing: 'easeInOutQuart' + } + }, + }); + charts[serviceId]._downtimeAtIndex = downtimeAtIndex; + } catch (error) { + console.error('Error loading chart:', error); + } +} diff --git a/src/public/manifest.json b/src/public/manifest.json new file mode 100644 index 0000000..c6e4d47 --- /dev/null +++ b/src/public/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "App", + "icons": [ + { + "src": "\/android-icon-192x192.png", + "sizes": "192x192", + "type": "image\/png", + "purpose": "any maskable" + } + ] +} diff --git a/src/public/ms-icon-150x150.png b/src/public/ms-icon-150x150.png new file mode 100644 index 0000000..0a2c30e Binary files /dev/null and b/src/public/ms-icon-150x150.png differ diff --git a/src/public/ms-icon-310x310.png b/src/public/ms-icon-310x310.png new file mode 100644 index 0000000..2094156 Binary files /dev/null and b/src/public/ms-icon-310x310.png differ diff --git a/src/public/ms-icon-70x70.png b/src/public/ms-icon-70x70.png new file mode 100644 index 0000000..0851378 Binary files /dev/null and b/src/public/ms-icon-70x70.png differ diff --git a/src/public/vendor/axios.min.js b/src/public/vendor/axios.min.js new file mode 100644 index 0000000..2b482fa --- /dev/null +++ b/src/public/vendor/axios.min.js @@ -0,0 +1,3 @@ +/*! Axios v1.13.2 Copyright (c) 2025 Matt Zabriskie and contributors */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(e){var r,n;function o(r,n){try{var a=e[r](n),u=a.value,s=u instanceof t;Promise.resolve(s?u.v:u).then((function(t){if(s){var n="return"===r?"return":"next";if(!u.k||t.done)return o(n,t);t=e[n](t).value}i(a.done?"return":"normal",t)}),(function(e){o("throw",e)}))}catch(e){i("throw",e)}}function i(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?o(r.key,r.arg):n=null}this._invoke=function(e,t){return new Promise((function(i,a){var u={key:e,arg:t,resolve:i,reject:a,next:null};n?n=n.next=u:(r=n=u,o(e,t))}))},"function"!=typeof e.return&&(this.return=void 0)}function t(e,t){this.v=e,this.k=t}function r(e){var r={},n=!1;function o(r,o){return n=!0,o=new Promise((function(t){t(e[r](o))})),{done:!1,value:new t(o,1)}}return r["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},r.next=function(e){return n?(n=!1,e):o("next",e)},"function"==typeof e.throw&&(r.throw=function(e){if(n)throw n=!1,e;return o("throw",e)}),"function"==typeof e.return&&(r.return=function(e){return n?(n=!1,e):o("return",e)}),r}function n(e){var t,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(t=e[r]))return t.call(e);if(n&&null!=(t=e[n]))return new o(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function o(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return o=function(e){this.s=e,this.n=e.next},o.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new o(e)}function i(e){return new t(e,0)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),A(r),y}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;A(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:L(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),y}},t}function c(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}function l(t){return function(){return new e(t.apply(this,arguments))}}function p(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function d(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){p(i,n,o,a,u,"next",e)}function u(e){p(i,n,o,a,u,"throw",e)}a(void 0)}))}}function h(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r2&&void 0!==arguments[2]?arguments[2]:{},i=o.allOwnKeys,a=void 0!==i&&i;if(null!=e)if("object"!==f(e)&&(e=[e]),L(e))for(r=0,n=e.length;r0;)if(t===(r=n[o]).toLowerCase())return r;return null}var Q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Z=function(e){return!N(e)&&e!==Q};var ee,te=(ee="undefined"!=typeof Uint8Array&&R(Uint8Array),function(e){return ee&&e instanceof ee}),re=A("HTMLFormElement"),ne=function(e){var t=Object.prototype.hasOwnProperty;return function(e,r){return t.call(e,r)}}(),oe=A("RegExp"),ie=function(e,t){var r=Object.getOwnPropertyDescriptors(e),n={};$(r,(function(r,o){var i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)};var ae,ue,se,ce,fe=A("AsyncFunction"),le=(ae="function"==typeof setImmediate,ue=F(Q.postMessage),ae?setImmediate:ue?(se="axios@".concat(Math.random()),ce=[],Q.addEventListener("message",(function(e){var t=e.source,r=e.data;t===Q&&r===se&&ce.length&&ce.shift()()}),!1),function(e){ce.push(e),Q.postMessage(se,"*")}):function(e){return setTimeout(e)}),pe="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Q):"undefined"!=typeof process&&process.nextTick||le,de={isArray:L,isArrayBuffer:_,isBuffer:C,isFormData:function(e){var t;return e&&("function"==typeof FormData&&e instanceof FormData||F(e.append)&&("formdata"===(t=j(e))||"object"===t&&F(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&_(e.buffer)},isString:U,isNumber:B,isBoolean:function(e){return!0===e||!1===e},isObject:D,isPlainObject:I,isEmptyObject:function(e){if(!D(e)||C(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:K,isRequest:V,isResponse:G,isHeaders:X,isUndefined:N,isDate:q,isFile:M,isBlob:z,isRegExp:oe,isFunction:F,isStream:function(e){return D(e)&&F(e.pipe)},isURLSearchParams:J,isTypedArray:te,isFileList:H,forEach:$,merge:function e(){for(var t=Z(this)&&this||{},r=t.caseless,n=t.skipUndefined,o={},i=function(t,i){var a=r&&Y(o,i)||i;I(o[a])&&I(t)?o[a]=e(o[a],t):I(t)?o[a]=e({},t):L(t)?o[a]=t.slice():n&&N(t)||(o[a]=t)},a=0,u=arguments.length;a3&&void 0!==arguments[3]?arguments[3]:{},o=n.allOwnKeys;return $(t,(function(t,n){r&&F(t)?e[n]=O(t,r):e[n]=t}),{allOwnKeys:o}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,r,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:function(e,t,r,n){var o,i,a,u={};if(t=t||{},null==e)return t;do{for(i=(o=Object.getOwnPropertyNames(e)).length;i-- >0;)a=o[i],n&&!n(a,e,t)||u[a]||(t[a]=e[a],u[a]=!0);e=!1!==r&&R(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:j,kindOfTest:A,endsWith:function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var n=e.indexOf(t,r);return-1!==n&&n===r},toArray:function(e){if(!e)return null;if(L(e))return e;var t=e.length;if(!B(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},forEachEntry:function(e,t){for(var r,n=(e&&e[k]).call(e);(r=n.next())&&!r.done;){var o=r.value;t.call(e,o[0],o[1])}},matchAll:function(e,t){for(var r,n=[];null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:re,hasOwnProperty:ne,hasOwnProp:ne,reduceDescriptors:ie,freezeMethods:function(e){ie(e,(function(t,r){if(F(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;var n=e[r];F(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:function(e,t){var r={},n=function(e){e.forEach((function(e){r[e]=!0}))};return L(e)?n(e):n(String(e).split(t)),r},toCamelCase:function(e){return e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r}))},noop:function(){},toFiniteNumber:function(e,t){return null!=e&&Number.isFinite(e=+e)?e:t},findKey:Y,global:Q,isContextDefined:Z,isSpecCompliantForm:function(e){return!!(e&&F(e.append)&&"FormData"===e[T]&&e[k])},toJSONObject:function(e){var t=new Array(10);return function e(r,n){if(D(r)){if(t.indexOf(r)>=0)return;if(C(r))return r;if(!("toJSON"in r)){t[n]=r;var o=L(r)?[]:{};return $(r,(function(t,r){var i=e(t,n+1);!N(i)&&(o[r]=i)})),t[n]=void 0,o}}return r}(e,0)},isAsyncFn:fe,isThenable:function(e){return e&&(D(e)||F(e))&&F(e.then)&&F(e.catch)},setImmediate:le,asap:pe,isIterable:function(e){return null!=e&&F(e[k])}};function he(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}de.inherits(he,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:de.toJSONObject(this.config),code:this.code,status:this.status}}});var ve=he.prototype,ye={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((function(e){ye[e]={value:e}})),Object.defineProperties(he,ye),Object.defineProperty(ve,"isAxiosError",{value:!0}),he.from=function(e,t,r,n,o,i){var a=Object.create(ve);de.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(function(e){return"isAxiosError"!==e}));var u=e&&e.message?e.message:"Error",s=null==t&&e?e.code:t;return he.call(a,u,s,r,n,o),e&&null==a.cause&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",i&&Object.assign(a,i),a};function me(e){return de.isPlainObject(e)||de.isArray(e)}function be(e){return de.endsWith(e,"[]")?e.slice(0,-2):e}function ge(e,t,r){return e?e.concat(t).map((function(e,t){return e=be(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}var we=de.toFlatObject(de,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Ee(e,t,r){if(!de.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;var n=(r=de.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!de.isUndefined(t[e])}))).metaTokens,o=r.visitor||c,i=r.dots,a=r.indexes,u=(r.Blob||"undefined"!=typeof Blob&&Blob)&&de.isSpecCompliantForm(t);if(!de.isFunction(o))throw new TypeError("visitor must be a function");function s(e){if(null===e)return"";if(de.isDate(e))return e.toISOString();if(de.isBoolean(e))return e.toString();if(!u&&de.isBlob(e))throw new he("Blob is not supported. Use a Buffer instead.");return de.isArrayBuffer(e)||de.isTypedArray(e)?u&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function c(e,r,o){var u=e;if(e&&!o&&"object"===f(e))if(de.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(de.isArray(e)&&function(e){return de.isArray(e)&&!e.some(me)}(e)||(de.isFileList(e)||de.endsWith(r,"[]"))&&(u=de.toArray(e)))return r=be(r),u.forEach((function(e,n){!de.isUndefined(e)&&null!==e&&t.append(!0===a?ge([r],n,i):null===a?r:r+"[]",s(e))})),!1;return!!me(e)||(t.append(ge(o,r,i),s(e)),!1)}var l=[],p=Object.assign(we,{defaultVisitor:c,convertValue:s,isVisitable:me});if(!de.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!de.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),de.forEach(r,(function(r,i){!0===(!(de.isUndefined(r)||null===r)&&o.call(t,r,de.isString(i)?i.trim():i,n,p))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t}function Oe(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Se(e,t){this._pairs=[],e&&Ee(e,this,t)}var xe=Se.prototype;function Re(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ke(e,t,r){if(!t)return e;var n=r&&r.encode||Re;de.isFunction(r)&&(r={serialize:r});var o,i=r&&r.serialize;if(o=i?i(t,r):de.isURLSearchParams(t)?t.toString():new Se(t,r).toString(n)){var a=e.indexOf("#");-1!==a&&(e=e.slice(0,a)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}xe.append=function(e,t){this._pairs.push([e,t])},xe.toString=function(e){var t=e?function(t){return e.call(this,t,Oe)}:Oe;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Te=function(){function e(){h(this,e),this.handlers=[]}return y(e,[{key:"use",value:function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}},{key:"eject",value:function(e){this.handlers[e]&&(this.handlers[e]=null)}},{key:"clear",value:function(){this.handlers&&(this.handlers=[])}},{key:"forEach",value:function(e){de.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}]),e}(),je={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ae={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Se,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Pe="undefined"!=typeof window&&"undefined"!=typeof document,Le="object"===("undefined"==typeof navigator?"undefined":f(navigator))&&navigator||void 0,Ne=Pe&&(!Le||["ReactNative","NativeScript","NS"].indexOf(Le.product)<0),Ce="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,_e=Pe&&window.location.href||"http://localhost",Ue=u(u({},Object.freeze({__proto__:null,hasBrowserEnv:Pe,hasStandardBrowserWebWorkerEnv:Ce,hasStandardBrowserEnv:Ne,navigator:Le,origin:_e})),Ae);function Fe(e){function t(e,r,n,o){var i=e[o++];if("__proto__"===i)return!0;var a=Number.isFinite(+i),u=o>=e.length;return i=!i&&de.isArray(n)?n.length:i,u?(de.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a):(n[i]&&de.isObject(n[i])||(n[i]=[]),t(e,r,n[i],o)&&de.isArray(n[i])&&(n[i]=function(e){var t,r,n={},o=Object.keys(e),i=o.length;for(t=0;t-1,i=de.isObject(e);if(i&&de.isHTMLForm(e)&&(e=new FormData(e)),de.isFormData(e))return o?JSON.stringify(Fe(e)):e;if(de.isArrayBuffer(e)||de.isBuffer(e)||de.isStream(e)||de.isFile(e)||de.isBlob(e)||de.isReadableStream(e))return e;if(de.isArrayBufferView(e))return e.buffer;if(de.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Ee(e,new Ue.classes.URLSearchParams,u({visitor:function(e,t,r,n){return Ue.isNode&&de.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((r=de.isFileList(e))||n.indexOf("multipart/form-data")>-1){var a=this.env&&this.env.FormData;return Ee(r?{"files[]":e}:e,a&&new a,this.formSerializer)}}return i||o?(t.setContentType("application/json",!1),function(e,t,r){if(de.isString(e))try{return(t||JSON.parse)(e),de.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||Be.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(de.isResponse(e)||de.isReadableStream(e))return e;if(e&&de.isString(e)&&(r&&!this.responseType||n)){var o=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,this.parseReviver)}catch(e){if(o){if("SyntaxError"===e.name)throw he.from(e,he.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ue.classes.FormData,Blob:Ue.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};de.forEach(["delete","get","head","post","put","patch"],(function(e){Be.headers[e]={}}));var De=Be,Ie=de.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),qe=Symbol("internals");function Me(e){return e&&String(e).trim().toLowerCase()}function ze(e){return!1===e||null==e?e:de.isArray(e)?e.map(ze):String(e)}function He(e,t,r,n,o){return de.isFunction(n)?n.call(this,t,r):(o&&(t=r),de.isString(t)?de.isString(n)?-1!==t.indexOf(n):de.isRegExp(n)?n.test(t):void 0:void 0)}var Je=function(e,t){function r(e){h(this,r),e&&this.set(e)}return y(r,[{key:"set",value:function(e,t,r){var n=this;function o(e,t,r){var o=Me(t);if(!o)throw new Error("header name must be a non-empty string");var i=de.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=ze(e))}var i=function(e,t){return de.forEach(e,(function(e,r){return o(e,r,t)}))};if(de.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(de.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i(function(e){var t,r,n,o={};return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),t=e.substring(0,n).trim().toLowerCase(),r=e.substring(n+1).trim(),!t||o[t]&&Ie[t]||("set-cookie"===t?o[t]?o[t].push(r):o[t]=[r]:o[t]=o[t]?o[t]+", "+r:r)})),o}(e),t);else if(de.isObject(e)&&de.isIterable(e)){var a,u,s,c={},f=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=w(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw i}}}}(e);try{for(f.s();!(s=f.n()).done;){var l=s.value;if(!de.isArray(l))throw TypeError("Object iterator must return a key-value pair");c[u=l[0]]=(a=c[u])?de.isArray(a)?[].concat(g(a),[l[1]]):[a,l[1]]:l[1]}}catch(e){f.e(e)}finally{f.f()}i(c,t)}else null!=e&&o(t,e,r);return this}},{key:"get",value:function(e,t){if(e=Me(e)){var r=de.findKey(this,e);if(r){var n=this[r];if(!t)return n;if(!0===t)return function(e){for(var t,r=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=n.exec(e);)r[t[1]]=t[2];return r}(n);if(de.isFunction(t))return t.call(this,n,r);if(de.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}},{key:"has",value:function(e,t){if(e=Me(e)){var r=de.findKey(this,e);return!(!r||void 0===this[r]||t&&!He(0,this[r],r,t))}return!1}},{key:"delete",value:function(e,t){var r=this,n=!1;function o(e){if(e=Me(e)){var o=de.findKey(r,e);!o||t&&!He(0,r[o],o,t)||(delete r[o],n=!0)}}return de.isArray(e)?e.forEach(o):o(e),n}},{key:"clear",value:function(e){for(var t=Object.keys(this),r=t.length,n=!1;r--;){var o=t[r];e&&!He(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}},{key:"normalize",value:function(e){var t=this,r={};return de.forEach(this,(function(n,o){var i=de.findKey(r,o);if(i)return t[i]=ze(n),void delete t[o];var a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r}))}(o):String(o).trim();a!==o&&delete t[o],t[a]=ze(n),r[a]=!0})),this}},{key:"concat",value:function(){for(var e,t=arguments.length,r=new Array(t),n=0;n1?r-1:0),o=1;o1&&void 0!==arguments[1]?arguments[1]:Date.now();o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(void 0,g(t))};return[function(){for(var e=Date.now(),t=e-o,u=arguments.length,s=new Array(u),c=0;c=i?a(s,e):(r=s,n||(n=setTimeout((function(){n=null,a(r)}),i-t)))},function(){return r&&a(r)}]}de.inherits(Ge,he,{__CANCEL__:!0});var Qe=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0,o=$e(50,250);return Ye((function(r){var i=r.loaded,a=r.lengthComputable?r.total:void 0,u=i-n,s=o(u);n=i;var c=m({loaded:i,total:a,progress:a?i/a:void 0,bytes:u,rate:s||void 0,estimated:s&&a&&i<=a?(a-i)/s:void 0,event:r,lengthComputable:null!=a},t?"download":"upload",!0);e(c)}),r)},Ze=function(e,t){var r=null!=e;return[function(n){return t[0]({lengthComputable:r,total:e,loaded:n})},t[1]]},et=function(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n1?t-1:0),n=1;n1?"since :\n"+s.map(xt).join("\n"):" "+xt(s[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:St};function Tt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ge(null,e)}function jt(e){return Tt(e),e.headers=We.from(e.headers),e.data=Ke.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),kt.getAdapter(e.adapter||De.adapter,e)(e).then((function(t){return Tt(e),t.data=Ke.call(e,e.transformResponse,t),t.headers=We.from(t.headers),t}),(function(t){return Ve(t)||(Tt(e),t&&t.response&&(t.response.data=Ke.call(e,e.transformResponse,t.response),t.response.headers=We.from(t.response.headers))),Promise.reject(t)}))}var At="1.13.2",Pt={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Pt[e]=function(r){return f(r)===e||"a"+(t<1?"n ":" ")+e}}));var Lt={};Pt.transitional=function(e,t,r){function n(e,t){return"[Axios v1.13.2] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,o,i){if(!1===e)throw new he(n(o," has been removed"+(t?" in "+t:"")),he.ERR_DEPRECATED);return t&&!Lt[o]&&(Lt[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},Pt.spelling=function(e){return function(t,r){return console.warn("".concat(r," is likely a misspelling of ").concat(e)),!0}};var Nt={assertOptions:function(e,t,r){if("object"!==f(e))throw new he("options must be an object",he.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),o=n.length;o-- >0;){var i=n[o],a=t[i];if(a){var u=e[i],s=void 0===u||a(u,i,e);if(!0!==s)throw new he("option "+i+" must be "+s,he.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new he("Unknown option "+i,he.ERR_BAD_OPTION)}},validators:Pt},Ct=Nt.validators,_t=function(){function e(t){h(this,e),this.defaults=t||{},this.interceptors={request:new Te,response:new Te}}var t;return y(e,[{key:"request",value:(t=d(s().mark((function e(t,r){var n,o;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this._request(t,r);case 3:return e.abrupt("return",e.sent);case 6:if(e.prev=6,e.t0=e.catch(0),e.t0 instanceof Error){n={},Error.captureStackTrace?Error.captureStackTrace(n):n=new Error,o=n.stack?n.stack.replace(/^.+\n/,""):"";try{e.t0.stack?o&&!String(e.t0.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(e.t0.stack+="\n"+o):e.t0.stack=o}catch(e){}}throw e.t0;case 10:case"end":return e.stop()}}),e,this,[[0,6]])}))),function(e,r){return t.apply(this,arguments)})},{key:"_request",value:function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};var r=t=it(this.defaults,t),n=r.transitional,o=r.paramsSerializer,i=r.headers;void 0!==n&&Nt.assertOptions(n,{silentJSONParsing:Ct.transitional(Ct.boolean),forcedJSONParsing:Ct.transitional(Ct.boolean),clarifyTimeoutError:Ct.transitional(Ct.boolean)},!1),null!=o&&(de.isFunction(o)?t.paramsSerializer={serialize:o}:Nt.assertOptions(o,{encode:Ct.function,serialize:Ct.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Nt.assertOptions(t,{baseUrl:Ct.spelling("baseURL"),withXsrfToken:Ct.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();var a=i&&de.merge(i.common,i[t.method]);i&&de.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete i[e]})),t.headers=We.concat(a,i);var u=[],s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,u.unshift(e.fulfilled,e.rejected))}));var c,f=[];this.interceptors.response.forEach((function(e){f.push(e.fulfilled,e.rejected)}));var l,p=0;if(!s){var d=[jt.bind(this),void 0];for(d.unshift.apply(d,u),d.push.apply(d,f),l=d.length,c=Promise.resolve(t);p0;)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},t((function(e,t,o){n.reason||(n.reason=new Ge(e,t,o),r(n.reason))}))}return y(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}},{key:"toAbortSignal",value:function(){var e=this,t=new AbortController,r=function(e){t.abort(e)};return this.subscribe(r),t.signal.unsubscribe=function(){return e.unsubscribe(r)},t.signal}}],[{key:"source",value:function(){var t;return{token:new e((function(e){t=e})),cancel:t}}}]),e}(),Bt=Ft;var Dt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Dt).forEach((function(e){var t=b(e,2),r=t[0],n=t[1];Dt[n]=r}));var It=Dt;var qt=function e(t){var r=new Ut(t),n=O(Ut.prototype.request,r);return de.extend(n,Ut.prototype,r,{allOwnKeys:!0}),de.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(it(t,r))},n}(De);return qt.Axios=Ut,qt.CanceledError=Ge,qt.CancelToken=Bt,qt.isCancel=Ve,qt.VERSION=At,qt.toFormData=Ee,qt.AxiosError=he,qt.Cancel=qt.CanceledError,qt.all=function(e){return Promise.all(e)},qt.spread=function(e){return function(t){return e.apply(null,t)}},qt.isAxiosError=function(e){return de.isObject(e)&&!0===e.isAxiosError},qt.mergeConfig=it,qt.AxiosHeaders=We,qt.formToJSON=function(e){return Fe(de.isHTMLForm(e)?new FormData(e):e)},qt.getAdapter=kt.getAdapter,qt.HttpStatusCode=It,qt.default=qt,qt})); +//# sourceMappingURL=axios.min.js.map diff --git a/src/public/vendor/chart.js b/src/public/vendor/chart.js new file mode 100644 index 0000000..008464f --- /dev/null +++ b/src/public/vendor/chart.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.5.1 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=Z(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=Z(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Jt{constructor(t){if(t instanceof Jt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Jt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Zt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Zt(t)?t:new Jt(t)}function te(t){return Zt(t)?t:new Jt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Me(t.height*s),o=Me(t.width*s);t.height=Me(t.height),t.width=Me(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Ze(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Ze(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Ze(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Je(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Ze(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Je(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:J,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hb||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tYi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Ji(t,e){return t.filter((t=>t.pos===e))}function Zi(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Qi(Ji(e,"left"),!0),n=Qi(Ji(e,"right")),o=Qi(Ji(e,"top"),!0),a=Qi(Ji(e,"bottom")),r=Zi(e,"x"),l=Zi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ji(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Ws(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ns=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ws(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ws(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ns(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ns(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ns(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Js(t){return t.drawTicks?t.tickLength:0}function Zs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=Z(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Js(t.grid)-e.padding-Zs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(Z((h.highest.height+6)/o,-1,1)),Math.asin(Z(a/r,-1,1))-Math.asin(Z(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Zs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Js(n)+o):(t.height=this.maxHeight,t.width=Js(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Js(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.5.1";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Ni(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data,{labels:{pointStyle:i,textAlign:s,color:n,useBorderRadius:o,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map(((e,r)=>{const l=t.getDatasetMeta(0).controller.getStyle(r);return{text:e,fillStyle:l.backgroundColor,fontColor:n,hidden:!t.getDataVisibility(r),lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:l.borderWidth,strokeStyle:l.borderColor,textAlign:s,pointStyle:i,borderRadius:o&&(a||l.borderRadius),index:r}})):[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nJ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>J(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter((i=>t[i].axis===e)).shift()}_getAxis(){const t={},e=this.getFirstScaleIdForIndexAxis();for(const i of this.chart.data.datasets)t[l("x"===this.chart.options.indexAxis?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;const c=this._getAxisCount();if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,d="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return Z(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:Z(n.innerStart,0,a),innerEnd:Z(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,x=n-p-f,{outerStart:b,outerEnd:_,innerStart:y,innerEnd:v}=Xn(e,u,d,x-m),M=d-b,w=d-_,k=m+b/M,S=x-_/w,P=u+y,D=u+v,O=m+y/P,A=x-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=qn(w,S,a,r);t.arc(e.x,e.y,_,S,x+E)}const i=qn(D,x,a,r);if(t.lineTo(i.x,i.y),v>0){const e=qn(D,A,a,r);t.arc(e.x,e.y,v,x+E,A+Math.PI)}const s=(x-v/u+(m+y/u))/2;if(t.arc(a,r,u,x-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=qn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=qn(M,m,a,r);if(t.lineTo(n.x,n.y),b>0){const e=qn(M,k,a,r);t.arc(e.x,e.y,b,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u,borderRadius:f}=l,g="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,g?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let p=e.endAngle;if(o){Kn(t,e,i,s,p,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,p),l.selfJoin&&p-a>=C&&0===f&&"miter"!==c&&function(t,e,i){const{startAngle:s,x:n,y:o,outerRadius:a,innerRadius:r,options:l}=e,{borderWidth:h,borderJoinStyle:c}=l,d=Math.min(h/a,G(s-i));if(t.beginPath(),t.arc(n,o,a-h/2,s+d/2,i-d/2),r>0){const e=Math.min(h/r,G(s-i));t.arc(n,o,r+h/2,i-e/2,s+e/2,!0)}else{const e=Math.min(h/2,a*G(s-i));if("round"===c)t.arc(n,o,e,i-C/2,s+C/2,!0);else if("bevel"===c){const a=2*e*e,r=-a*Math.cos(i+C/2)+n,l=-a*Math.sin(i+C/2)+o,h=a*Math.cos(s+C/2)+n,c=a*Math.sin(s+C/2)+o;t.lineTo(r,l),t.lineTo(h,c)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}(t,e,p),o||(Kn(t,e,i,s,p,n),t.stroke())}function Jn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Jn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Jn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=J(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function No(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=Z(s,0,o),n=Z(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:Z(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Jo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=Z(it(e,o.axis,a).lo,0,i-1)),s=h?Z(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const _a=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class ya extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=_a(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=va(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=_a(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=va(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class wa extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var ka={id:"title",_element:wa,start(t,e,i){!function(t,e){const i=new wa({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa=new WeakMap;var Pa={id:"subtitle",start(t,e,i){const s=new wa({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),Sa.set(t,s)},stop(t){ls.removeBox(t,Sa.get(t)),Sa.delete(t)},beforeUpdate(t,e,i){const s=Sa.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Da={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;et+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i-1?t.split("\n"):t}function Aa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Ta(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function La(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ea(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||La(t,e,i,s),yAlign:s}}function Ra(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:Z(g,0,s.width-e.width),y:Z(p,0,s.height-e.height)}}function Ia(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function za(t){return Ca([],Oa(t))}function Fa(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Va={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Fa(i,t);Ca(e.before,Oa(Ba(n,"beforeLabel",this,t))),Ca(e.lines,Ba(n,"label",this,t)),Ca(e.after,Oa(Ba(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return za(Ba(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Ba(i,"beforeFooter",this,t),n=Ba(i,"footer",this,t),o=Ba(i,"afterFooter",this,t);let a=[];return a=Ca(a,Oa(s)),a=Ca(a,Oa(n)),a=Ca(a,Oa(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Fa(t.callbacks,e);s.push(Ba(i,"labelColor",this,e)),n.push(Ba(i,"labelPointStyle",this,e)),o.push(Ba(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Da[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Ta(this,i),a=Object.assign({},t,e),r=Ea(this.chart,i,a),l=Ra(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ia(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ia(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Da[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Ta(this,t),a=Object.assign({},i,this._size),r=Ea(e,t,a),l=Ra(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Da[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Na={id:"tooltip",_element:Wa,positioners:Da,afterInit(t,e,i){i&&(t.tooltip=new Wa({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Va},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn})); +//# sourceMappingURL=chart.umd.min.js.map diff --git a/src/public/vendor/font-awesome/all.min.css b/src/public/vendor/font-awesome/all.min.css new file mode 100644 index 0000000..5f2c80d --- /dev/null +++ b/src/public/vendor/font-awesome/all.min.css @@ -0,0 +1,9 @@ +/*! + * Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com + * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) + * Copyright 2023 Fonticons, Inc. + */ +.fa{font-family:var(--fa-style-family,"Font Awesome 6 Free");font-weight:var(--fa-style,900)}.fa,.fa-brands,.fa-classic,.fa-regular,.fa-sharp,.fa-solid,.fab,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:var(--fa-display,inline-block);font-style:normal;font-variant:normal;line-height:1;text-rendering:auto}.fa-classic,.fa-regular,.fa-solid,.far,.fas{font-family:"Font Awesome 6 Free"}.fa-brands,.fab{font-family:"Font Awesome 6 Brands"}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-2xs{font-size:.625em;line-height:.1em;vertical-align:.225em}.fa-xs{font-size:.75em;line-height:.08333em;vertical-align:.125em}.fa-sm{font-size:.875em;line-height:.07143em;vertical-align:.05357em}.fa-lg{font-size:1.25em;line-height:.05em;vertical-align:-.075em}.fa-xl{font-size:1.5em;line-height:.04167em;vertical-align:-.125em}.fa-2xl{font-size:2em;line-height:.03125em;vertical-align:-.1875em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:var(--fa-li-margin,2.5em);padding-left:0}.fa-ul>li{position:relative}.fa-li{left:calc(var(--fa-li-width, 2em)*-1);position:absolute;text-align:center;width:var(--fa-li-width,2em);line-height:inherit}.fa-border{border-radius:var(--fa-border-radius,.1em);border:var(--fa-border-width,.08em) var(--fa-border-style,solid) var(--fa-border-color,#eee);padding:var(--fa-border-padding,.2em .25em .15em)}.fa-pull-left{float:left;margin-right:var(--fa-pull-margin,.3em)}.fa-pull-right{float:right;margin-left:var(--fa-pull-margin,.3em)}.fa-beat{-webkit-animation-name:fa-beat;animation-name:fa-beat;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-bounce{-webkit-animation-name:fa-bounce;animation-name:fa-bounce;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1))}.fa-fade{-webkit-animation-name:fa-fade;animation-name:fa-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-beat-fade,.fa-fade{-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s)}.fa-beat-fade{-webkit-animation-name:fa-beat-fade;animation-name:fa-beat-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-flip{-webkit-animation-name:fa-flip;animation-name:fa-flip;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-shake{-webkit-animation-name:fa-shake;animation-name:fa-shake;-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,linear);animation-timing-function:var(--fa-animation-timing,linear)}.fa-shake,.fa-spin{-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal)}.fa-spin{-webkit-animation-name:fa-spin;animation-name:fa-spin;-webkit-animation-duration:var(--fa-animation-duration,2s);animation-duration:var(--fa-animation-duration,2s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,linear);animation-timing-function:var(--fa-animation-timing,linear)}.fa-spin-reverse{--fa-animation-direction:reverse}.fa-pulse,.fa-spin-pulse{-webkit-animation-name:fa-spin;animation-name:fa-spin;-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,steps(8));animation-timing-function:var(--fa-animation-timing,steps(8))}@media (prefers-reduced-motion:reduce){.fa-beat,.fa-beat-fade,.fa-bounce,.fa-fade,.fa-flip,.fa-pulse,.fa-shake,.fa-spin,.fa-spin-pulse{-webkit-animation-delay:-1ms;animation-delay:-1ms;-webkit-animation-duration:1ms;animation-duration:1ms;-webkit-animation-iteration-count:1;animation-iteration-count:1;-webkit-transition-delay:0s;transition-delay:0s;-webkit-transition-duration:0s;transition-duration:0s}}@-webkit-keyframes fa-beat{0%,90%{-webkit-transform:scale(1);transform:scale(1)}45%{-webkit-transform:scale(var(--fa-beat-scale,1.25));transform:scale(var(--fa-beat-scale,1.25))}}@keyframes fa-beat{0%,90%{-webkit-transform:scale(1);transform:scale(1)}45%{-webkit-transform:scale(var(--fa-beat-scale,1.25));transform:scale(var(--fa-beat-scale,1.25))}}@-webkit-keyframes fa-bounce{0%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}10%{-webkit-transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0);transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0)}30%{-webkit-transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em));transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em))}50%{-webkit-transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0);transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0)}57%{-webkit-transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em));transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em))}64%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}to{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}}@keyframes fa-bounce{0%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}10%{-webkit-transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0);transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0)}30%{-webkit-transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em));transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em))}50%{-webkit-transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0);transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0)}57%{-webkit-transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em));transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em))}64%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}to{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}}@-webkit-keyframes fa-fade{50%{opacity:var(--fa-fade-opacity,.4)}}@keyframes fa-fade{50%{opacity:var(--fa-fade-opacity,.4)}}@-webkit-keyframes fa-beat-fade{0%,to{opacity:var(--fa-beat-fade-opacity,.4);-webkit-transform:scale(1);transform:scale(1)}50%{opacity:1;-webkit-transform:scale(var(--fa-beat-fade-scale,1.125));transform:scale(var(--fa-beat-fade-scale,1.125))}}@keyframes fa-beat-fade{0%,to{opacity:var(--fa-beat-fade-opacity,.4);-webkit-transform:scale(1);transform:scale(1)}50%{opacity:1;-webkit-transform:scale(var(--fa-beat-fade-scale,1.125));transform:scale(var(--fa-beat-fade-scale,1.125))}}@-webkit-keyframes fa-flip{50%{-webkit-transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg));transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg))}}@keyframes fa-flip{50%{-webkit-transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg));transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg))}}@-webkit-keyframes fa-shake{0%{-webkit-transform:rotate(-15deg);transform:rotate(-15deg)}4%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}8%,24%{-webkit-transform:rotate(-18deg);transform:rotate(-18deg)}12%,28%{-webkit-transform:rotate(18deg);transform:rotate(18deg)}16%{-webkit-transform:rotate(-22deg);transform:rotate(-22deg)}20%{-webkit-transform:rotate(22deg);transform:rotate(22deg)}32%{-webkit-transform:rotate(-12deg);transform:rotate(-12deg)}36%{-webkit-transform:rotate(12deg);transform:rotate(12deg)}40%,to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}@keyframes fa-shake{0%{-webkit-transform:rotate(-15deg);transform:rotate(-15deg)}4%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}8%,24%{-webkit-transform:rotate(-18deg);transform:rotate(-18deg)}12%,28%{-webkit-transform:rotate(18deg);transform:rotate(18deg)}16%{-webkit-transform:rotate(-22deg);transform:rotate(-22deg)}20%{-webkit-transform:rotate(22deg);transform:rotate(22deg)}32%{-webkit-transform:rotate(-12deg);transform:rotate(-12deg)}36%{-webkit-transform:rotate(12deg);transform:rotate(12deg)}40%,to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-webkit-transform:scaleY(-1);transform:scaleY(-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1);transform:scale(-1)}.fa-rotate-by{-webkit-transform:rotate(var(--fa-rotate-angle,none));transform:rotate(var(--fa-rotate-angle,none))}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%;z-index:var(--fa-stack-z-index,auto)}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:var(--fa-inverse,#fff)} + +.fa-0:before{content:"\30"}.fa-1:before{content:"\31"}.fa-2:before{content:"\32"}.fa-3:before{content:"\33"}.fa-4:before{content:"\34"}.fa-5:before{content:"\35"}.fa-6:before{content:"\36"}.fa-7:before{content:"\37"}.fa-8:before{content:"\38"}.fa-9:before{content:"\39"}.fa-fill-drip:before{content:"\f576"}.fa-arrows-to-circle:before{content:"\e4bd"}.fa-chevron-circle-right:before,.fa-circle-chevron-right:before{content:"\f138"}.fa-at:before{content:"\40"}.fa-trash-alt:before,.fa-trash-can:before{content:"\f2ed"}.fa-text-height:before{content:"\f034"}.fa-user-times:before,.fa-user-xmark:before{content:"\f235"}.fa-stethoscope:before{content:"\f0f1"}.fa-comment-alt:before,.fa-message:before{content:"\f27a"}.fa-info:before{content:"\f129"}.fa-compress-alt:before,.fa-down-left-and-up-right-to-center:before{content:"\f422"}.fa-explosion:before{content:"\e4e9"}.fa-file-alt:before,.fa-file-lines:before,.fa-file-text:before{content:"\f15c"}.fa-wave-square:before{content:"\f83e"}.fa-ring:before{content:"\f70b"}.fa-building-un:before{content:"\e4d9"}.fa-dice-three:before{content:"\f527"}.fa-calendar-alt:before,.fa-calendar-days:before{content:"\f073"}.fa-anchor-circle-check:before{content:"\e4aa"}.fa-building-circle-arrow-right:before{content:"\e4d1"}.fa-volleyball-ball:before,.fa-volleyball:before{content:"\f45f"}.fa-arrows-up-to-line:before{content:"\e4c2"}.fa-sort-desc:before,.fa-sort-down:before{content:"\f0dd"}.fa-circle-minus:before,.fa-minus-circle:before{content:"\f056"}.fa-door-open:before{content:"\f52b"}.fa-right-from-bracket:before,.fa-sign-out-alt:before{content:"\f2f5"}.fa-atom:before{content:"\f5d2"}.fa-soap:before{content:"\e06e"}.fa-heart-music-camera-bolt:before,.fa-icons:before{content:"\f86d"}.fa-microphone-alt-slash:before,.fa-microphone-lines-slash:before{content:"\f539"}.fa-bridge-circle-check:before{content:"\e4c9"}.fa-pump-medical:before{content:"\e06a"}.fa-fingerprint:before{content:"\f577"}.fa-hand-point-right:before{content:"\f0a4"}.fa-magnifying-glass-location:before,.fa-search-location:before{content:"\f689"}.fa-forward-step:before,.fa-step-forward:before{content:"\f051"}.fa-face-smile-beam:before,.fa-smile-beam:before{content:"\f5b8"}.fa-flag-checkered:before{content:"\f11e"}.fa-football-ball:before,.fa-football:before{content:"\f44e"}.fa-school-circle-exclamation:before{content:"\e56c"}.fa-crop:before{content:"\f125"}.fa-angle-double-down:before,.fa-angles-down:before{content:"\f103"}.fa-users-rectangle:before{content:"\e594"}.fa-people-roof:before{content:"\e537"}.fa-people-line:before{content:"\e534"}.fa-beer-mug-empty:before,.fa-beer:before{content:"\f0fc"}.fa-diagram-predecessor:before{content:"\e477"}.fa-arrow-up-long:before,.fa-long-arrow-up:before{content:"\f176"}.fa-burn:before,.fa-fire-flame-simple:before{content:"\f46a"}.fa-male:before,.fa-person:before{content:"\f183"}.fa-laptop:before{content:"\f109"}.fa-file-csv:before{content:"\f6dd"}.fa-menorah:before{content:"\f676"}.fa-truck-plane:before{content:"\e58f"}.fa-record-vinyl:before{content:"\f8d9"}.fa-face-grin-stars:before,.fa-grin-stars:before{content:"\f587"}.fa-bong:before{content:"\f55c"}.fa-pastafarianism:before,.fa-spaghetti-monster-flying:before{content:"\f67b"}.fa-arrow-down-up-across-line:before{content:"\e4af"}.fa-spoon:before,.fa-utensil-spoon:before{content:"\f2e5"}.fa-jar-wheat:before{content:"\e517"}.fa-envelopes-bulk:before,.fa-mail-bulk:before{content:"\f674"}.fa-file-circle-exclamation:before{content:"\e4eb"}.fa-circle-h:before,.fa-hospital-symbol:before{content:"\f47e"}.fa-pager:before{content:"\f815"}.fa-address-book:before,.fa-contact-book:before{content:"\f2b9"}.fa-strikethrough:before{content:"\f0cc"}.fa-k:before{content:"\4b"}.fa-landmark-flag:before{content:"\e51c"}.fa-pencil-alt:before,.fa-pencil:before{content:"\f303"}.fa-backward:before{content:"\f04a"}.fa-caret-right:before{content:"\f0da"}.fa-comments:before{content:"\f086"}.fa-file-clipboard:before,.fa-paste:before{content:"\f0ea"}.fa-code-pull-request:before{content:"\e13c"}.fa-clipboard-list:before{content:"\f46d"}.fa-truck-loading:before,.fa-truck-ramp-box:before{content:"\f4de"}.fa-user-check:before{content:"\f4fc"}.fa-vial-virus:before{content:"\e597"}.fa-sheet-plastic:before{content:"\e571"}.fa-blog:before{content:"\f781"}.fa-user-ninja:before{content:"\f504"}.fa-person-arrow-up-from-line:before{content:"\e539"}.fa-scroll-torah:before,.fa-torah:before{content:"\f6a0"}.fa-broom-ball:before,.fa-quidditch-broom-ball:before,.fa-quidditch:before{content:"\f458"}.fa-toggle-off:before{content:"\f204"}.fa-archive:before,.fa-box-archive:before{content:"\f187"}.fa-person-drowning:before{content:"\e545"}.fa-arrow-down-9-1:before,.fa-sort-numeric-desc:before,.fa-sort-numeric-down-alt:before{content:"\f886"}.fa-face-grin-tongue-squint:before,.fa-grin-tongue-squint:before{content:"\f58a"}.fa-spray-can:before{content:"\f5bd"}.fa-truck-monster:before{content:"\f63b"}.fa-w:before{content:"\57"}.fa-earth-africa:before,.fa-globe-africa:before{content:"\f57c"}.fa-rainbow:before{content:"\f75b"}.fa-circle-notch:before{content:"\f1ce"}.fa-tablet-alt:before,.fa-tablet-screen-button:before{content:"\f3fa"}.fa-paw:before{content:"\f1b0"}.fa-cloud:before{content:"\f0c2"}.fa-trowel-bricks:before{content:"\e58a"}.fa-face-flushed:before,.fa-flushed:before{content:"\f579"}.fa-hospital-user:before{content:"\f80d"}.fa-tent-arrow-left-right:before{content:"\e57f"}.fa-gavel:before,.fa-legal:before{content:"\f0e3"}.fa-binoculars:before{content:"\f1e5"}.fa-microphone-slash:before{content:"\f131"}.fa-box-tissue:before{content:"\e05b"}.fa-motorcycle:before{content:"\f21c"}.fa-bell-concierge:before,.fa-concierge-bell:before{content:"\f562"}.fa-pen-ruler:before,.fa-pencil-ruler:before{content:"\f5ae"}.fa-people-arrows-left-right:before,.fa-people-arrows:before{content:"\e068"}.fa-mars-and-venus-burst:before{content:"\e523"}.fa-caret-square-right:before,.fa-square-caret-right:before{content:"\f152"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-sun-plant-wilt:before{content:"\e57a"}.fa-toilets-portable:before{content:"\e584"}.fa-hockey-puck:before{content:"\f453"}.fa-table:before{content:"\f0ce"}.fa-magnifying-glass-arrow-right:before{content:"\e521"}.fa-digital-tachograph:before,.fa-tachograph-digital:before{content:"\f566"}.fa-users-slash:before{content:"\e073"}.fa-clover:before{content:"\e139"}.fa-mail-reply:before,.fa-reply:before{content:"\f3e5"}.fa-star-and-crescent:before{content:"\f699"}.fa-house-fire:before{content:"\e50c"}.fa-minus-square:before,.fa-square-minus:before{content:"\f146"}.fa-helicopter:before{content:"\f533"}.fa-compass:before{content:"\f14e"}.fa-caret-square-down:before,.fa-square-caret-down:before{content:"\f150"}.fa-file-circle-question:before{content:"\e4ef"}.fa-laptop-code:before{content:"\f5fc"}.fa-swatchbook:before{content:"\f5c3"}.fa-prescription-bottle:before{content:"\f485"}.fa-bars:before,.fa-navicon:before{content:"\f0c9"}.fa-people-group:before{content:"\e533"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-heart-broken:before,.fa-heart-crack:before{content:"\f7a9"}.fa-external-link-square-alt:before,.fa-square-up-right:before{content:"\f360"}.fa-face-kiss-beam:before,.fa-kiss-beam:before{content:"\f597"}.fa-film:before{content:"\f008"}.fa-ruler-horizontal:before{content:"\f547"}.fa-people-robbery:before{content:"\e536"}.fa-lightbulb:before{content:"\f0eb"}.fa-caret-left:before{content:"\f0d9"}.fa-circle-exclamation:before,.fa-exclamation-circle:before{content:"\f06a"}.fa-school-circle-xmark:before{content:"\e56d"}.fa-arrow-right-from-bracket:before,.fa-sign-out:before{content:"\f08b"}.fa-chevron-circle-down:before,.fa-circle-chevron-down:before{content:"\f13a"}.fa-unlock-alt:before,.fa-unlock-keyhole:before{content:"\f13e"}.fa-cloud-showers-heavy:before{content:"\f740"}.fa-headphones-alt:before,.fa-headphones-simple:before{content:"\f58f"}.fa-sitemap:before{content:"\f0e8"}.fa-circle-dollar-to-slot:before,.fa-donate:before{content:"\f4b9"}.fa-memory:before{content:"\f538"}.fa-road-spikes:before{content:"\e568"}.fa-fire-burner:before{content:"\e4f1"}.fa-flag:before{content:"\f024"}.fa-hanukiah:before{content:"\f6e6"}.fa-feather:before{content:"\f52d"}.fa-volume-down:before,.fa-volume-low:before{content:"\f027"}.fa-comment-slash:before{content:"\f4b3"}.fa-cloud-sun-rain:before{content:"\f743"}.fa-compress:before{content:"\f066"}.fa-wheat-alt:before,.fa-wheat-awn:before{content:"\e2cd"}.fa-ankh:before{content:"\f644"}.fa-hands-holding-child:before{content:"\e4fa"}.fa-asterisk:before{content:"\2a"}.fa-check-square:before,.fa-square-check:before{content:"\f14a"}.fa-peseta-sign:before{content:"\e221"}.fa-header:before,.fa-heading:before{content:"\f1dc"}.fa-ghost:before{content:"\f6e2"}.fa-list-squares:before,.fa-list:before{content:"\f03a"}.fa-phone-square-alt:before,.fa-square-phone-flip:before{content:"\f87b"}.fa-cart-plus:before{content:"\f217"}.fa-gamepad:before{content:"\f11b"}.fa-circle-dot:before,.fa-dot-circle:before{content:"\f192"}.fa-dizzy:before,.fa-face-dizzy:before{content:"\f567"}.fa-egg:before{content:"\f7fb"}.fa-house-medical-circle-xmark:before{content:"\e513"}.fa-campground:before{content:"\f6bb"}.fa-folder-plus:before{content:"\f65e"}.fa-futbol-ball:before,.fa-futbol:before,.fa-soccer-ball:before{content:"\f1e3"}.fa-paint-brush:before,.fa-paintbrush:before{content:"\f1fc"}.fa-lock:before{content:"\f023"}.fa-gas-pump:before{content:"\f52f"}.fa-hot-tub-person:before,.fa-hot-tub:before{content:"\f593"}.fa-map-location:before,.fa-map-marked:before{content:"\f59f"}.fa-house-flood-water:before{content:"\e50e"}.fa-tree:before{content:"\f1bb"}.fa-bridge-lock:before{content:"\e4cc"}.fa-sack-dollar:before{content:"\f81d"}.fa-edit:before,.fa-pen-to-square:before{content:"\f044"}.fa-car-side:before{content:"\f5e4"}.fa-share-alt:before,.fa-share-nodes:before{content:"\f1e0"}.fa-heart-circle-minus:before{content:"\e4ff"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-microscope:before{content:"\f610"}.fa-sink:before{content:"\e06d"}.fa-bag-shopping:before,.fa-shopping-bag:before{content:"\f290"}.fa-arrow-down-z-a:before,.fa-sort-alpha-desc:before,.fa-sort-alpha-down-alt:before{content:"\f881"}.fa-mitten:before{content:"\f7b5"}.fa-person-rays:before{content:"\e54d"}.fa-users:before{content:"\f0c0"}.fa-eye-slash:before{content:"\f070"}.fa-flask-vial:before{content:"\e4f3"}.fa-hand-paper:before,.fa-hand:before{content:"\f256"}.fa-om:before{content:"\f679"}.fa-worm:before{content:"\e599"}.fa-house-circle-xmark:before{content:"\e50b"}.fa-plug:before{content:"\f1e6"}.fa-chevron-up:before{content:"\f077"}.fa-hand-spock:before{content:"\f259"}.fa-stopwatch:before{content:"\f2f2"}.fa-face-kiss:before,.fa-kiss:before{content:"\f596"}.fa-bridge-circle-xmark:before{content:"\e4cb"}.fa-face-grin-tongue:before,.fa-grin-tongue:before{content:"\f589"}.fa-chess-bishop:before{content:"\f43a"}.fa-face-grin-wink:before,.fa-grin-wink:before{content:"\f58c"}.fa-deaf:before,.fa-deafness:before,.fa-ear-deaf:before,.fa-hard-of-hearing:before{content:"\f2a4"}.fa-road-circle-check:before{content:"\e564"}.fa-dice-five:before{content:"\f523"}.fa-rss-square:before,.fa-square-rss:before{content:"\f143"}.fa-land-mine-on:before{content:"\e51b"}.fa-i-cursor:before{content:"\f246"}.fa-stamp:before{content:"\f5bf"}.fa-stairs:before{content:"\e289"}.fa-i:before{content:"\49"}.fa-hryvnia-sign:before,.fa-hryvnia:before{content:"\f6f2"}.fa-pills:before{content:"\f484"}.fa-face-grin-wide:before,.fa-grin-alt:before{content:"\f581"}.fa-tooth:before{content:"\f5c9"}.fa-v:before{content:"\56"}.fa-bangladeshi-taka-sign:before{content:"\e2e6"}.fa-bicycle:before{content:"\f206"}.fa-rod-asclepius:before,.fa-rod-snake:before,.fa-staff-aesculapius:before,.fa-staff-snake:before{content:"\e579"}.fa-head-side-cough-slash:before{content:"\e062"}.fa-ambulance:before,.fa-truck-medical:before{content:"\f0f9"}.fa-wheat-awn-circle-exclamation:before{content:"\e598"}.fa-snowman:before{content:"\f7d0"}.fa-mortar-pestle:before{content:"\f5a7"}.fa-road-barrier:before{content:"\e562"}.fa-school:before{content:"\f549"}.fa-igloo:before{content:"\f7ae"}.fa-joint:before{content:"\f595"}.fa-angle-right:before{content:"\f105"}.fa-horse:before{content:"\f6f0"}.fa-q:before{content:"\51"}.fa-g:before{content:"\47"}.fa-notes-medical:before{content:"\f481"}.fa-temperature-2:before,.fa-temperature-half:before,.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-dong-sign:before{content:"\e169"}.fa-capsules:before{content:"\f46b"}.fa-poo-bolt:before,.fa-poo-storm:before{content:"\f75a"}.fa-face-frown-open:before,.fa-frown-open:before{content:"\f57a"}.fa-hand-point-up:before{content:"\f0a6"}.fa-money-bill:before{content:"\f0d6"}.fa-bookmark:before{content:"\f02e"}.fa-align-justify:before{content:"\f039"}.fa-umbrella-beach:before{content:"\f5ca"}.fa-helmet-un:before{content:"\e503"}.fa-bullseye:before{content:"\f140"}.fa-bacon:before{content:"\f7e5"}.fa-hand-point-down:before{content:"\f0a7"}.fa-arrow-up-from-bracket:before{content:"\e09a"}.fa-folder-blank:before,.fa-folder:before{content:"\f07b"}.fa-file-medical-alt:before,.fa-file-waveform:before{content:"\f478"}.fa-radiation:before{content:"\f7b9"}.fa-chart-simple:before{content:"\e473"}.fa-mars-stroke:before{content:"\f229"}.fa-vial:before{content:"\f492"}.fa-dashboard:before,.fa-gauge-med:before,.fa-gauge:before,.fa-tachometer-alt-average:before{content:"\f624"}.fa-magic-wand-sparkles:before,.fa-wand-magic-sparkles:before{content:"\e2ca"}.fa-e:before{content:"\45"}.fa-pen-alt:before,.fa-pen-clip:before{content:"\f305"}.fa-bridge-circle-exclamation:before{content:"\e4ca"}.fa-user:before{content:"\f007"}.fa-school-circle-check:before{content:"\e56b"}.fa-dumpster:before{content:"\f793"}.fa-shuttle-van:before,.fa-van-shuttle:before{content:"\f5b6"}.fa-building-user:before{content:"\e4da"}.fa-caret-square-left:before,.fa-square-caret-left:before{content:"\f191"}.fa-highlighter:before{content:"\f591"}.fa-key:before{content:"\f084"}.fa-bullhorn:before{content:"\f0a1"}.fa-globe:before{content:"\f0ac"}.fa-synagogue:before{content:"\f69b"}.fa-person-half-dress:before{content:"\e548"}.fa-road-bridge:before{content:"\e563"}.fa-location-arrow:before{content:"\f124"}.fa-c:before{content:"\43"}.fa-tablet-button:before{content:"\f10a"}.fa-building-lock:before{content:"\e4d6"}.fa-pizza-slice:before{content:"\f818"}.fa-money-bill-wave:before{content:"\f53a"}.fa-area-chart:before,.fa-chart-area:before{content:"\f1fe"}.fa-house-flag:before{content:"\e50d"}.fa-person-circle-minus:before{content:"\e540"}.fa-ban:before,.fa-cancel:before{content:"\f05e"}.fa-camera-rotate:before{content:"\e0d8"}.fa-air-freshener:before,.fa-spray-can-sparkles:before{content:"\f5d0"}.fa-star:before{content:"\f005"}.fa-repeat:before{content:"\f363"}.fa-cross:before{content:"\f654"}.fa-box:before{content:"\f466"}.fa-venus-mars:before{content:"\f228"}.fa-arrow-pointer:before,.fa-mouse-pointer:before{content:"\f245"}.fa-expand-arrows-alt:before,.fa-maximize:before{content:"\f31e"}.fa-charging-station:before{content:"\f5e7"}.fa-shapes:before,.fa-triangle-circle-square:before{content:"\f61f"}.fa-random:before,.fa-shuffle:before{content:"\f074"}.fa-person-running:before,.fa-running:before{content:"\f70c"}.fa-mobile-retro:before{content:"\e527"}.fa-grip-lines-vertical:before{content:"\f7a5"}.fa-spider:before{content:"\f717"}.fa-hands-bound:before{content:"\e4f9"}.fa-file-invoice-dollar:before{content:"\f571"}.fa-plane-circle-exclamation:before{content:"\e556"}.fa-x-ray:before{content:"\f497"}.fa-spell-check:before{content:"\f891"}.fa-slash:before{content:"\f715"}.fa-computer-mouse:before,.fa-mouse:before{content:"\f8cc"}.fa-arrow-right-to-bracket:before,.fa-sign-in:before{content:"\f090"}.fa-shop-slash:before,.fa-store-alt-slash:before{content:"\e070"}.fa-server:before{content:"\f233"}.fa-virus-covid-slash:before{content:"\e4a9"}.fa-shop-lock:before{content:"\e4a5"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-blender-phone:before{content:"\f6b6"}.fa-building-wheat:before{content:"\e4db"}.fa-person-breastfeeding:before{content:"\e53a"}.fa-right-to-bracket:before,.fa-sign-in-alt:before{content:"\f2f6"}.fa-venus:before{content:"\f221"}.fa-passport:before{content:"\f5ab"}.fa-heart-pulse:before,.fa-heartbeat:before{content:"\f21e"}.fa-people-carry-box:before,.fa-people-carry:before{content:"\f4ce"}.fa-temperature-high:before{content:"\f769"}.fa-microchip:before{content:"\f2db"}.fa-crown:before{content:"\f521"}.fa-weight-hanging:before{content:"\f5cd"}.fa-xmarks-lines:before{content:"\e59a"}.fa-file-prescription:before{content:"\f572"}.fa-weight-scale:before,.fa-weight:before{content:"\f496"}.fa-user-friends:before,.fa-user-group:before{content:"\f500"}.fa-arrow-up-a-z:before,.fa-sort-alpha-up:before{content:"\f15e"}.fa-chess-knight:before{content:"\f441"}.fa-face-laugh-squint:before,.fa-laugh-squint:before{content:"\f59b"}.fa-wheelchair:before{content:"\f193"}.fa-arrow-circle-up:before,.fa-circle-arrow-up:before{content:"\f0aa"}.fa-toggle-on:before{content:"\f205"}.fa-person-walking:before,.fa-walking:before{content:"\f554"}.fa-l:before{content:"\4c"}.fa-fire:before{content:"\f06d"}.fa-bed-pulse:before,.fa-procedures:before{content:"\f487"}.fa-shuttle-space:before,.fa-space-shuttle:before{content:"\f197"}.fa-face-laugh:before,.fa-laugh:before{content:"\f599"}.fa-folder-open:before{content:"\f07c"}.fa-heart-circle-plus:before{content:"\e500"}.fa-code-fork:before{content:"\e13b"}.fa-city:before{content:"\f64f"}.fa-microphone-alt:before,.fa-microphone-lines:before{content:"\f3c9"}.fa-pepper-hot:before{content:"\f816"}.fa-unlock:before{content:"\f09c"}.fa-colon-sign:before{content:"\e140"}.fa-headset:before{content:"\f590"}.fa-store-slash:before{content:"\e071"}.fa-road-circle-xmark:before{content:"\e566"}.fa-user-minus:before{content:"\f503"}.fa-mars-stroke-up:before,.fa-mars-stroke-v:before{content:"\f22a"}.fa-champagne-glasses:before,.fa-glass-cheers:before{content:"\f79f"}.fa-clipboard:before{content:"\f328"}.fa-house-circle-exclamation:before{content:"\e50a"}.fa-file-arrow-up:before,.fa-file-upload:before{content:"\f574"}.fa-wifi-3:before,.fa-wifi-strong:before,.fa-wifi:before{content:"\f1eb"}.fa-bath:before,.fa-bathtub:before{content:"\f2cd"}.fa-underline:before{content:"\f0cd"}.fa-user-edit:before,.fa-user-pen:before{content:"\f4ff"}.fa-signature:before{content:"\f5b7"}.fa-stroopwafel:before{content:"\f551"}.fa-bold:before{content:"\f032"}.fa-anchor-lock:before{content:"\e4ad"}.fa-building-ngo:before{content:"\e4d7"}.fa-manat-sign:before{content:"\e1d5"}.fa-not-equal:before{content:"\f53e"}.fa-border-style:before,.fa-border-top-left:before{content:"\f853"}.fa-map-location-dot:before,.fa-map-marked-alt:before{content:"\f5a0"}.fa-jedi:before{content:"\f669"}.fa-poll:before,.fa-square-poll-vertical:before{content:"\f681"}.fa-mug-hot:before{content:"\f7b6"}.fa-battery-car:before,.fa-car-battery:before{content:"\f5df"}.fa-gift:before{content:"\f06b"}.fa-dice-two:before{content:"\f528"}.fa-chess-queen:before{content:"\f445"}.fa-glasses:before{content:"\f530"}.fa-chess-board:before{content:"\f43c"}.fa-building-circle-check:before{content:"\e4d2"}.fa-person-chalkboard:before{content:"\e53d"}.fa-mars-stroke-h:before,.fa-mars-stroke-right:before{content:"\f22b"}.fa-hand-back-fist:before,.fa-hand-rock:before{content:"\f255"}.fa-caret-square-up:before,.fa-square-caret-up:before{content:"\f151"}.fa-cloud-showers-water:before{content:"\e4e4"}.fa-bar-chart:before,.fa-chart-bar:before{content:"\f080"}.fa-hands-bubbles:before,.fa-hands-wash:before{content:"\e05e"}.fa-less-than-equal:before{content:"\f537"}.fa-train:before{content:"\f238"}.fa-eye-low-vision:before,.fa-low-vision:before{content:"\f2a8"}.fa-crow:before{content:"\f520"}.fa-sailboat:before{content:"\e445"}.fa-window-restore:before{content:"\f2d2"}.fa-plus-square:before,.fa-square-plus:before{content:"\f0fe"}.fa-torii-gate:before{content:"\f6a1"}.fa-frog:before{content:"\f52e"}.fa-bucket:before{content:"\e4cf"}.fa-image:before{content:"\f03e"}.fa-microphone:before{content:"\f130"}.fa-cow:before{content:"\f6c8"}.fa-caret-up:before{content:"\f0d8"}.fa-screwdriver:before{content:"\f54a"}.fa-folder-closed:before{content:"\e185"}.fa-house-tsunami:before{content:"\e515"}.fa-square-nfi:before{content:"\e576"}.fa-arrow-up-from-ground-water:before{content:"\e4b5"}.fa-glass-martini-alt:before,.fa-martini-glass:before{content:"\f57b"}.fa-rotate-back:before,.fa-rotate-backward:before,.fa-rotate-left:before,.fa-undo-alt:before{content:"\f2ea"}.fa-columns:before,.fa-table-columns:before{content:"\f0db"}.fa-lemon:before{content:"\f094"}.fa-head-side-mask:before{content:"\e063"}.fa-handshake:before{content:"\f2b5"}.fa-gem:before{content:"\f3a5"}.fa-dolly-box:before,.fa-dolly:before{content:"\f472"}.fa-smoking:before{content:"\f48d"}.fa-compress-arrows-alt:before,.fa-minimize:before{content:"\f78c"}.fa-monument:before{content:"\f5a6"}.fa-snowplow:before{content:"\f7d2"}.fa-angle-double-right:before,.fa-angles-right:before{content:"\f101"}.fa-cannabis:before{content:"\f55f"}.fa-circle-play:before,.fa-play-circle:before{content:"\f144"}.fa-tablets:before{content:"\f490"}.fa-ethernet:before{content:"\f796"}.fa-eur:before,.fa-euro-sign:before,.fa-euro:before{content:"\f153"}.fa-chair:before{content:"\f6c0"}.fa-check-circle:before,.fa-circle-check:before{content:"\f058"}.fa-circle-stop:before,.fa-stop-circle:before{content:"\f28d"}.fa-compass-drafting:before,.fa-drafting-compass:before{content:"\f568"}.fa-plate-wheat:before{content:"\e55a"}.fa-icicles:before{content:"\f7ad"}.fa-person-shelter:before{content:"\e54f"}.fa-neuter:before{content:"\f22c"}.fa-id-badge:before{content:"\f2c1"}.fa-marker:before{content:"\f5a1"}.fa-face-laugh-beam:before,.fa-laugh-beam:before{content:"\f59a"}.fa-helicopter-symbol:before{content:"\e502"}.fa-universal-access:before{content:"\f29a"}.fa-chevron-circle-up:before,.fa-circle-chevron-up:before{content:"\f139"}.fa-lari-sign:before{content:"\e1c8"}.fa-volcano:before{content:"\f770"}.fa-person-walking-dashed-line-arrow-right:before{content:"\e553"}.fa-gbp:before,.fa-pound-sign:before,.fa-sterling-sign:before{content:"\f154"}.fa-viruses:before{content:"\e076"}.fa-square-person-confined:before{content:"\e577"}.fa-user-tie:before{content:"\f508"}.fa-arrow-down-long:before,.fa-long-arrow-down:before{content:"\f175"}.fa-tent-arrow-down-to-line:before{content:"\e57e"}.fa-certificate:before{content:"\f0a3"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-suitcase:before{content:"\f0f2"}.fa-person-skating:before,.fa-skating:before{content:"\f7c5"}.fa-filter-circle-dollar:before,.fa-funnel-dollar:before{content:"\f662"}.fa-camera-retro:before{content:"\f083"}.fa-arrow-circle-down:before,.fa-circle-arrow-down:before{content:"\f0ab"}.fa-arrow-right-to-file:before,.fa-file-import:before{content:"\f56f"}.fa-external-link-square:before,.fa-square-arrow-up-right:before{content:"\f14c"}.fa-box-open:before{content:"\f49e"}.fa-scroll:before{content:"\f70e"}.fa-spa:before{content:"\f5bb"}.fa-location-pin-lock:before{content:"\e51f"}.fa-pause:before{content:"\f04c"}.fa-hill-avalanche:before{content:"\e507"}.fa-temperature-0:before,.fa-temperature-empty:before,.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-bomb:before{content:"\f1e2"}.fa-registered:before{content:"\f25d"}.fa-address-card:before,.fa-contact-card:before,.fa-vcard:before{content:"\f2bb"}.fa-balance-scale-right:before,.fa-scale-unbalanced-flip:before{content:"\f516"}.fa-subscript:before{content:"\f12c"}.fa-diamond-turn-right:before,.fa-directions:before{content:"\f5eb"}.fa-burst:before{content:"\e4dc"}.fa-house-laptop:before,.fa-laptop-house:before{content:"\e066"}.fa-face-tired:before,.fa-tired:before{content:"\f5c8"}.fa-money-bills:before{content:"\e1f3"}.fa-smog:before{content:"\f75f"}.fa-crutch:before{content:"\f7f7"}.fa-cloud-arrow-up:before,.fa-cloud-upload-alt:before,.fa-cloud-upload:before{content:"\f0ee"}.fa-palette:before{content:"\f53f"}.fa-arrows-turn-right:before{content:"\e4c0"}.fa-vest:before{content:"\e085"}.fa-ferry:before{content:"\e4ea"}.fa-arrows-down-to-people:before{content:"\e4b9"}.fa-seedling:before,.fa-sprout:before{content:"\f4d8"}.fa-arrows-alt-h:before,.fa-left-right:before{content:"\f337"}.fa-boxes-packing:before{content:"\e4c7"}.fa-arrow-circle-left:before,.fa-circle-arrow-left:before{content:"\f0a8"}.fa-group-arrows-rotate:before{content:"\e4f6"}.fa-bowl-food:before{content:"\e4c6"}.fa-candy-cane:before{content:"\f786"}.fa-arrow-down-wide-short:before,.fa-sort-amount-asc:before,.fa-sort-amount-down:before{content:"\f160"}.fa-cloud-bolt:before,.fa-thunderstorm:before{content:"\f76c"}.fa-remove-format:before,.fa-text-slash:before{content:"\f87d"}.fa-face-smile-wink:before,.fa-smile-wink:before{content:"\f4da"}.fa-file-word:before{content:"\f1c2"}.fa-file-powerpoint:before{content:"\f1c4"}.fa-arrows-h:before,.fa-arrows-left-right:before{content:"\f07e"}.fa-house-lock:before{content:"\e510"}.fa-cloud-arrow-down:before,.fa-cloud-download-alt:before,.fa-cloud-download:before{content:"\f0ed"}.fa-children:before{content:"\e4e1"}.fa-blackboard:before,.fa-chalkboard:before{content:"\f51b"}.fa-user-alt-slash:before,.fa-user-large-slash:before{content:"\f4fa"}.fa-envelope-open:before{content:"\f2b6"}.fa-handshake-alt-slash:before,.fa-handshake-simple-slash:before{content:"\e05f"}.fa-mattress-pillow:before{content:"\e525"}.fa-guarani-sign:before{content:"\e19a"}.fa-arrows-rotate:before,.fa-refresh:before,.fa-sync:before{content:"\f021"}.fa-fire-extinguisher:before{content:"\f134"}.fa-cruzeiro-sign:before{content:"\e152"}.fa-greater-than-equal:before{content:"\f532"}.fa-shield-alt:before,.fa-shield-halved:before{content:"\f3ed"}.fa-atlas:before,.fa-book-atlas:before{content:"\f558"}.fa-virus:before{content:"\e074"}.fa-envelope-circle-check:before{content:"\e4e8"}.fa-layer-group:before{content:"\f5fd"}.fa-arrows-to-dot:before{content:"\e4be"}.fa-archway:before{content:"\f557"}.fa-heart-circle-check:before{content:"\e4fd"}.fa-house-chimney-crack:before,.fa-house-damage:before{content:"\f6f1"}.fa-file-archive:before,.fa-file-zipper:before{content:"\f1c6"}.fa-square:before{content:"\f0c8"}.fa-glass-martini:before,.fa-martini-glass-empty:before{content:"\f000"}.fa-couch:before{content:"\f4b8"}.fa-cedi-sign:before{content:"\e0df"}.fa-italic:before{content:"\f033"}.fa-church:before{content:"\f51d"}.fa-comments-dollar:before{content:"\f653"}.fa-democrat:before{content:"\f747"}.fa-z:before{content:"\5a"}.fa-person-skiing:before,.fa-skiing:before{content:"\f7c9"}.fa-road-lock:before{content:"\e567"}.fa-a:before{content:"\41"}.fa-temperature-arrow-down:before,.fa-temperature-down:before{content:"\e03f"}.fa-feather-alt:before,.fa-feather-pointed:before{content:"\f56b"}.fa-p:before{content:"\50"}.fa-snowflake:before{content:"\f2dc"}.fa-newspaper:before{content:"\f1ea"}.fa-ad:before,.fa-rectangle-ad:before{content:"\f641"}.fa-arrow-circle-right:before,.fa-circle-arrow-right:before{content:"\f0a9"}.fa-filter-circle-xmark:before{content:"\e17b"}.fa-locust:before{content:"\e520"}.fa-sort:before,.fa-unsorted:before{content:"\f0dc"}.fa-list-1-2:before,.fa-list-numeric:before,.fa-list-ol:before{content:"\f0cb"}.fa-person-dress-burst:before{content:"\e544"}.fa-money-check-alt:before,.fa-money-check-dollar:before{content:"\f53d"}.fa-vector-square:before{content:"\f5cb"}.fa-bread-slice:before{content:"\f7ec"}.fa-language:before{content:"\f1ab"}.fa-face-kiss-wink-heart:before,.fa-kiss-wink-heart:before{content:"\f598"}.fa-filter:before{content:"\f0b0"}.fa-question:before{content:"\3f"}.fa-file-signature:before{content:"\f573"}.fa-arrows-alt:before,.fa-up-down-left-right:before{content:"\f0b2"}.fa-house-chimney-user:before{content:"\e065"}.fa-hand-holding-heart:before{content:"\f4be"}.fa-puzzle-piece:before{content:"\f12e"}.fa-money-check:before{content:"\f53c"}.fa-star-half-alt:before,.fa-star-half-stroke:before{content:"\f5c0"}.fa-code:before{content:"\f121"}.fa-glass-whiskey:before,.fa-whiskey-glass:before{content:"\f7a0"}.fa-building-circle-exclamation:before{content:"\e4d3"}.fa-magnifying-glass-chart:before{content:"\e522"}.fa-arrow-up-right-from-square:before,.fa-external-link:before{content:"\f08e"}.fa-cubes-stacked:before{content:"\e4e6"}.fa-krw:before,.fa-won-sign:before,.fa-won:before{content:"\f159"}.fa-virus-covid:before{content:"\e4a8"}.fa-austral-sign:before{content:"\e0a9"}.fa-f:before{content:"\46"}.fa-leaf:before{content:"\f06c"}.fa-road:before{content:"\f018"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-person-circle-plus:before{content:"\e541"}.fa-chart-pie:before,.fa-pie-chart:before{content:"\f200"}.fa-bolt-lightning:before{content:"\e0b7"}.fa-sack-xmark:before{content:"\e56a"}.fa-file-excel:before{content:"\f1c3"}.fa-file-contract:before{content:"\f56c"}.fa-fish-fins:before{content:"\e4f2"}.fa-building-flag:before{content:"\e4d5"}.fa-face-grin-beam:before,.fa-grin-beam:before{content:"\f582"}.fa-object-ungroup:before{content:"\f248"}.fa-poop:before{content:"\f619"}.fa-location-pin:before,.fa-map-marker:before{content:"\f041"}.fa-kaaba:before{content:"\f66b"}.fa-toilet-paper:before{content:"\f71e"}.fa-hard-hat:before,.fa-hat-hard:before,.fa-helmet-safety:before{content:"\f807"}.fa-eject:before{content:"\f052"}.fa-arrow-alt-circle-right:before,.fa-circle-right:before{content:"\f35a"}.fa-plane-circle-check:before{content:"\e555"}.fa-face-rolling-eyes:before,.fa-meh-rolling-eyes:before{content:"\f5a5"}.fa-object-group:before{content:"\f247"}.fa-chart-line:before,.fa-line-chart:before{content:"\f201"}.fa-mask-ventilator:before{content:"\e524"}.fa-arrow-right:before{content:"\f061"}.fa-map-signs:before,.fa-signs-post:before{content:"\f277"}.fa-cash-register:before{content:"\f788"}.fa-person-circle-question:before{content:"\e542"}.fa-h:before{content:"\48"}.fa-tarp:before{content:"\e57b"}.fa-screwdriver-wrench:before,.fa-tools:before{content:"\f7d9"}.fa-arrows-to-eye:before{content:"\e4bf"}.fa-plug-circle-bolt:before{content:"\e55b"}.fa-heart:before{content:"\f004"}.fa-mars-and-venus:before{content:"\f224"}.fa-home-user:before,.fa-house-user:before{content:"\e1b0"}.fa-dumpster-fire:before{content:"\f794"}.fa-house-crack:before{content:"\e3b1"}.fa-cocktail:before,.fa-martini-glass-citrus:before{content:"\f561"}.fa-face-surprise:before,.fa-surprise:before{content:"\f5c2"}.fa-bottle-water:before{content:"\e4c5"}.fa-circle-pause:before,.fa-pause-circle:before{content:"\f28b"}.fa-toilet-paper-slash:before{content:"\e072"}.fa-apple-alt:before,.fa-apple-whole:before{content:"\f5d1"}.fa-kitchen-set:before{content:"\e51a"}.fa-r:before{content:"\52"}.fa-temperature-1:before,.fa-temperature-quarter:before,.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-cube:before{content:"\f1b2"}.fa-bitcoin-sign:before{content:"\e0b4"}.fa-shield-dog:before{content:"\e573"}.fa-solar-panel:before{content:"\f5ba"}.fa-lock-open:before{content:"\f3c1"}.fa-elevator:before{content:"\e16d"}.fa-money-bill-transfer:before{content:"\e528"}.fa-money-bill-trend-up:before{content:"\e529"}.fa-house-flood-water-circle-arrow-right:before{content:"\e50f"}.fa-poll-h:before,.fa-square-poll-horizontal:before{content:"\f682"}.fa-circle:before{content:"\f111"}.fa-backward-fast:before,.fa-fast-backward:before{content:"\f049"}.fa-recycle:before{content:"\f1b8"}.fa-user-astronaut:before{content:"\f4fb"}.fa-plane-slash:before{content:"\e069"}.fa-trademark:before{content:"\f25c"}.fa-basketball-ball:before,.fa-basketball:before{content:"\f434"}.fa-satellite-dish:before{content:"\f7c0"}.fa-arrow-alt-circle-up:before,.fa-circle-up:before{content:"\f35b"}.fa-mobile-alt:before,.fa-mobile-screen-button:before{content:"\f3cd"}.fa-volume-high:before,.fa-volume-up:before{content:"\f028"}.fa-users-rays:before{content:"\e593"}.fa-wallet:before{content:"\f555"}.fa-clipboard-check:before{content:"\f46c"}.fa-file-audio:before{content:"\f1c7"}.fa-burger:before,.fa-hamburger:before{content:"\f805"}.fa-wrench:before{content:"\f0ad"}.fa-bugs:before{content:"\e4d0"}.fa-rupee-sign:before,.fa-rupee:before{content:"\f156"}.fa-file-image:before{content:"\f1c5"}.fa-circle-question:before,.fa-question-circle:before{content:"\f059"}.fa-plane-departure:before{content:"\f5b0"}.fa-handshake-slash:before{content:"\e060"}.fa-book-bookmark:before{content:"\e0bb"}.fa-code-branch:before{content:"\f126"}.fa-hat-cowboy:before{content:"\f8c0"}.fa-bridge:before{content:"\e4c8"}.fa-phone-alt:before,.fa-phone-flip:before{content:"\f879"}.fa-truck-front:before{content:"\e2b7"}.fa-cat:before{content:"\f6be"}.fa-anchor-circle-exclamation:before{content:"\e4ab"}.fa-truck-field:before{content:"\e58d"}.fa-route:before{content:"\f4d7"}.fa-clipboard-question:before{content:"\e4e3"}.fa-panorama:before{content:"\e209"}.fa-comment-medical:before{content:"\f7f5"}.fa-teeth-open:before{content:"\f62f"}.fa-file-circle-minus:before{content:"\e4ed"}.fa-tags:before{content:"\f02c"}.fa-wine-glass:before{content:"\f4e3"}.fa-fast-forward:before,.fa-forward-fast:before{content:"\f050"}.fa-face-meh-blank:before,.fa-meh-blank:before{content:"\f5a4"}.fa-parking:before,.fa-square-parking:before{content:"\f540"}.fa-house-signal:before{content:"\e012"}.fa-bars-progress:before,.fa-tasks-alt:before{content:"\f828"}.fa-faucet-drip:before{content:"\e006"}.fa-cart-flatbed:before,.fa-dolly-flatbed:before{content:"\f474"}.fa-ban-smoking:before,.fa-smoking-ban:before{content:"\f54d"}.fa-terminal:before{content:"\f120"}.fa-mobile-button:before{content:"\f10b"}.fa-house-medical-flag:before{content:"\e514"}.fa-basket-shopping:before,.fa-shopping-basket:before{content:"\f291"}.fa-tape:before{content:"\f4db"}.fa-bus-alt:before,.fa-bus-simple:before{content:"\f55e"}.fa-eye:before{content:"\f06e"}.fa-face-sad-cry:before,.fa-sad-cry:before{content:"\f5b3"}.fa-audio-description:before{content:"\f29e"}.fa-person-military-to-person:before{content:"\e54c"}.fa-file-shield:before{content:"\e4f0"}.fa-user-slash:before{content:"\f506"}.fa-pen:before{content:"\f304"}.fa-tower-observation:before{content:"\e586"}.fa-file-code:before{content:"\f1c9"}.fa-signal-5:before,.fa-signal-perfect:before,.fa-signal:before{content:"\f012"}.fa-bus:before{content:"\f207"}.fa-heart-circle-xmark:before{content:"\e501"}.fa-home-lg:before,.fa-house-chimney:before{content:"\e3af"}.fa-window-maximize:before{content:"\f2d0"}.fa-face-frown:before,.fa-frown:before{content:"\f119"}.fa-prescription:before{content:"\f5b1"}.fa-shop:before,.fa-store-alt:before{content:"\f54f"}.fa-floppy-disk:before,.fa-save:before{content:"\f0c7"}.fa-vihara:before{content:"\f6a7"}.fa-balance-scale-left:before,.fa-scale-unbalanced:before{content:"\f515"}.fa-sort-asc:before,.fa-sort-up:before{content:"\f0de"}.fa-comment-dots:before,.fa-commenting:before{content:"\f4ad"}.fa-plant-wilt:before{content:"\e5aa"}.fa-diamond:before{content:"\f219"}.fa-face-grin-squint:before,.fa-grin-squint:before{content:"\f585"}.fa-hand-holding-dollar:before,.fa-hand-holding-usd:before{content:"\f4c0"}.fa-bacterium:before{content:"\e05a"}.fa-hand-pointer:before{content:"\f25a"}.fa-drum-steelpan:before{content:"\f56a"}.fa-hand-scissors:before{content:"\f257"}.fa-hands-praying:before,.fa-praying-hands:before{content:"\f684"}.fa-arrow-right-rotate:before,.fa-arrow-rotate-forward:before,.fa-arrow-rotate-right:before,.fa-redo:before{content:"\f01e"}.fa-biohazard:before{content:"\f780"}.fa-location-crosshairs:before,.fa-location:before{content:"\f601"}.fa-mars-double:before{content:"\f227"}.fa-child-dress:before{content:"\e59c"}.fa-users-between-lines:before{content:"\e591"}.fa-lungs-virus:before{content:"\e067"}.fa-face-grin-tears:before,.fa-grin-tears:before{content:"\f588"}.fa-phone:before{content:"\f095"}.fa-calendar-times:before,.fa-calendar-xmark:before{content:"\f273"}.fa-child-reaching:before{content:"\e59d"}.fa-head-side-virus:before{content:"\e064"}.fa-user-cog:before,.fa-user-gear:before{content:"\f4fe"}.fa-arrow-up-1-9:before,.fa-sort-numeric-up:before{content:"\f163"}.fa-door-closed:before{content:"\f52a"}.fa-shield-virus:before{content:"\e06c"}.fa-dice-six:before{content:"\f526"}.fa-mosquito-net:before{content:"\e52c"}.fa-bridge-water:before{content:"\e4ce"}.fa-person-booth:before{content:"\f756"}.fa-text-width:before{content:"\f035"}.fa-hat-wizard:before{content:"\f6e8"}.fa-pen-fancy:before{content:"\f5ac"}.fa-digging:before,.fa-person-digging:before{content:"\f85e"}.fa-trash:before{content:"\f1f8"}.fa-gauge-simple-med:before,.fa-gauge-simple:before,.fa-tachometer-average:before{content:"\f629"}.fa-book-medical:before{content:"\f7e6"}.fa-poo:before{content:"\f2fe"}.fa-quote-right-alt:before,.fa-quote-right:before{content:"\f10e"}.fa-shirt:before,.fa-t-shirt:before,.fa-tshirt:before{content:"\f553"}.fa-cubes:before{content:"\f1b3"}.fa-divide:before{content:"\f529"}.fa-tenge-sign:before,.fa-tenge:before{content:"\f7d7"}.fa-headphones:before{content:"\f025"}.fa-hands-holding:before{content:"\f4c2"}.fa-hands-clapping:before{content:"\e1a8"}.fa-republican:before{content:"\f75e"}.fa-arrow-left:before{content:"\f060"}.fa-person-circle-xmark:before{content:"\e543"}.fa-ruler:before{content:"\f545"}.fa-align-left:before{content:"\f036"}.fa-dice-d6:before{content:"\f6d1"}.fa-restroom:before{content:"\f7bd"}.fa-j:before{content:"\4a"}.fa-users-viewfinder:before{content:"\e595"}.fa-file-video:before{content:"\f1c8"}.fa-external-link-alt:before,.fa-up-right-from-square:before{content:"\f35d"}.fa-table-cells:before,.fa-th:before{content:"\f00a"}.fa-file-pdf:before{content:"\f1c1"}.fa-bible:before,.fa-book-bible:before{content:"\f647"}.fa-o:before{content:"\4f"}.fa-medkit:before,.fa-suitcase-medical:before{content:"\f0fa"}.fa-user-secret:before{content:"\f21b"}.fa-otter:before{content:"\f700"}.fa-female:before,.fa-person-dress:before{content:"\f182"}.fa-comment-dollar:before{content:"\f651"}.fa-briefcase-clock:before,.fa-business-time:before{content:"\f64a"}.fa-table-cells-large:before,.fa-th-large:before{content:"\f009"}.fa-book-tanakh:before,.fa-tanakh:before{content:"\f827"}.fa-phone-volume:before,.fa-volume-control-phone:before{content:"\f2a0"}.fa-hat-cowboy-side:before{content:"\f8c1"}.fa-clipboard-user:before{content:"\f7f3"}.fa-child:before{content:"\f1ae"}.fa-lira-sign:before{content:"\f195"}.fa-satellite:before{content:"\f7bf"}.fa-plane-lock:before{content:"\e558"}.fa-tag:before{content:"\f02b"}.fa-comment:before{content:"\f075"}.fa-birthday-cake:before,.fa-cake-candles:before,.fa-cake:before{content:"\f1fd"}.fa-envelope:before{content:"\f0e0"}.fa-angle-double-up:before,.fa-angles-up:before{content:"\f102"}.fa-paperclip:before{content:"\f0c6"}.fa-arrow-right-to-city:before{content:"\e4b3"}.fa-ribbon:before{content:"\f4d6"}.fa-lungs:before{content:"\f604"}.fa-arrow-up-9-1:before,.fa-sort-numeric-up-alt:before{content:"\f887"}.fa-litecoin-sign:before{content:"\e1d3"}.fa-border-none:before{content:"\f850"}.fa-circle-nodes:before{content:"\e4e2"}.fa-parachute-box:before{content:"\f4cd"}.fa-indent:before{content:"\f03c"}.fa-truck-field-un:before{content:"\e58e"}.fa-hourglass-empty:before,.fa-hourglass:before{content:"\f254"}.fa-mountain:before{content:"\f6fc"}.fa-user-doctor:before,.fa-user-md:before{content:"\f0f0"}.fa-circle-info:before,.fa-info-circle:before{content:"\f05a"}.fa-cloud-meatball:before{content:"\f73b"}.fa-camera-alt:before,.fa-camera:before{content:"\f030"}.fa-square-virus:before{content:"\e578"}.fa-meteor:before{content:"\f753"}.fa-car-on:before{content:"\e4dd"}.fa-sleigh:before{content:"\f7cc"}.fa-arrow-down-1-9:before,.fa-sort-numeric-asc:before,.fa-sort-numeric-down:before{content:"\f162"}.fa-hand-holding-droplet:before,.fa-hand-holding-water:before{content:"\f4c1"}.fa-water:before{content:"\f773"}.fa-calendar-check:before{content:"\f274"}.fa-braille:before{content:"\f2a1"}.fa-prescription-bottle-alt:before,.fa-prescription-bottle-medical:before{content:"\f486"}.fa-landmark:before{content:"\f66f"}.fa-truck:before{content:"\f0d1"}.fa-crosshairs:before{content:"\f05b"}.fa-person-cane:before{content:"\e53c"}.fa-tent:before{content:"\e57d"}.fa-vest-patches:before{content:"\e086"}.fa-check-double:before{content:"\f560"}.fa-arrow-down-a-z:before,.fa-sort-alpha-asc:before,.fa-sort-alpha-down:before{content:"\f15d"}.fa-money-bill-wheat:before{content:"\e52a"}.fa-cookie:before{content:"\f563"}.fa-arrow-left-rotate:before,.fa-arrow-rotate-back:before,.fa-arrow-rotate-backward:before,.fa-arrow-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-hard-drive:before,.fa-hdd:before{content:"\f0a0"}.fa-face-grin-squint-tears:before,.fa-grin-squint-tears:before{content:"\f586"}.fa-dumbbell:before{content:"\f44b"}.fa-list-alt:before,.fa-rectangle-list:before{content:"\f022"}.fa-tarp-droplet:before{content:"\e57c"}.fa-house-medical-circle-check:before{content:"\e511"}.fa-person-skiing-nordic:before,.fa-skiing-nordic:before{content:"\f7ca"}.fa-calendar-plus:before{content:"\f271"}.fa-plane-arrival:before{content:"\f5af"}.fa-arrow-alt-circle-left:before,.fa-circle-left:before{content:"\f359"}.fa-subway:before,.fa-train-subway:before{content:"\f239"}.fa-chart-gantt:before{content:"\e0e4"}.fa-indian-rupee-sign:before,.fa-indian-rupee:before,.fa-inr:before{content:"\e1bc"}.fa-crop-alt:before,.fa-crop-simple:before{content:"\f565"}.fa-money-bill-1:before,.fa-money-bill-alt:before{content:"\f3d1"}.fa-left-long:before,.fa-long-arrow-alt-left:before{content:"\f30a"}.fa-dna:before{content:"\f471"}.fa-virus-slash:before{content:"\e075"}.fa-minus:before,.fa-subtract:before{content:"\f068"}.fa-chess:before{content:"\f439"}.fa-arrow-left-long:before,.fa-long-arrow-left:before{content:"\f177"}.fa-plug-circle-check:before{content:"\e55c"}.fa-street-view:before{content:"\f21d"}.fa-franc-sign:before{content:"\e18f"}.fa-volume-off:before{content:"\f026"}.fa-american-sign-language-interpreting:before,.fa-asl-interpreting:before,.fa-hands-american-sign-language-interpreting:before,.fa-hands-asl-interpreting:before{content:"\f2a3"}.fa-cog:before,.fa-gear:before{content:"\f013"}.fa-droplet-slash:before,.fa-tint-slash:before{content:"\f5c7"}.fa-mosque:before{content:"\f678"}.fa-mosquito:before{content:"\e52b"}.fa-star-of-david:before{content:"\f69a"}.fa-person-military-rifle:before{content:"\e54b"}.fa-cart-shopping:before,.fa-shopping-cart:before{content:"\f07a"}.fa-vials:before{content:"\f493"}.fa-plug-circle-plus:before{content:"\e55f"}.fa-place-of-worship:before{content:"\f67f"}.fa-grip-vertical:before{content:"\f58e"}.fa-arrow-turn-up:before,.fa-level-up:before{content:"\f148"}.fa-u:before{content:"\55"}.fa-square-root-alt:before,.fa-square-root-variable:before{content:"\f698"}.fa-clock-four:before,.fa-clock:before{content:"\f017"}.fa-backward-step:before,.fa-step-backward:before{content:"\f048"}.fa-pallet:before{content:"\f482"}.fa-faucet:before{content:"\e005"}.fa-baseball-bat-ball:before{content:"\f432"}.fa-s:before{content:"\53"}.fa-timeline:before{content:"\e29c"}.fa-keyboard:before{content:"\f11c"}.fa-caret-down:before{content:"\f0d7"}.fa-clinic-medical:before,.fa-house-chimney-medical:before{content:"\f7f2"}.fa-temperature-3:before,.fa-temperature-three-quarters:before,.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-mobile-android-alt:before,.fa-mobile-screen:before{content:"\f3cf"}.fa-plane-up:before{content:"\e22d"}.fa-piggy-bank:before{content:"\f4d3"}.fa-battery-3:before,.fa-battery-half:before{content:"\f242"}.fa-mountain-city:before{content:"\e52e"}.fa-coins:before{content:"\f51e"}.fa-khanda:before{content:"\f66d"}.fa-sliders-h:before,.fa-sliders:before{content:"\f1de"}.fa-folder-tree:before{content:"\f802"}.fa-network-wired:before{content:"\f6ff"}.fa-map-pin:before{content:"\f276"}.fa-hamsa:before{content:"\f665"}.fa-cent-sign:before{content:"\e3f5"}.fa-flask:before{content:"\f0c3"}.fa-person-pregnant:before{content:"\e31e"}.fa-wand-sparkles:before{content:"\f72b"}.fa-ellipsis-v:before,.fa-ellipsis-vertical:before{content:"\f142"}.fa-ticket:before{content:"\f145"}.fa-power-off:before{content:"\f011"}.fa-long-arrow-alt-right:before,.fa-right-long:before{content:"\f30b"}.fa-flag-usa:before{content:"\f74d"}.fa-laptop-file:before{content:"\e51d"}.fa-teletype:before,.fa-tty:before{content:"\f1e4"}.fa-diagram-next:before{content:"\e476"}.fa-person-rifle:before{content:"\e54e"}.fa-house-medical-circle-exclamation:before{content:"\e512"}.fa-closed-captioning:before{content:"\f20a"}.fa-hiking:before,.fa-person-hiking:before{content:"\f6ec"}.fa-venus-double:before{content:"\f226"}.fa-images:before{content:"\f302"}.fa-calculator:before{content:"\f1ec"}.fa-people-pulling:before{content:"\e535"}.fa-n:before{content:"\4e"}.fa-cable-car:before,.fa-tram:before{content:"\f7da"}.fa-cloud-rain:before{content:"\f73d"}.fa-building-circle-xmark:before{content:"\e4d4"}.fa-ship:before{content:"\f21a"}.fa-arrows-down-to-line:before{content:"\e4b8"}.fa-download:before{content:"\f019"}.fa-face-grin:before,.fa-grin:before{content:"\f580"}.fa-backspace:before,.fa-delete-left:before{content:"\f55a"}.fa-eye-dropper-empty:before,.fa-eye-dropper:before,.fa-eyedropper:before{content:"\f1fb"}.fa-file-circle-check:before{content:"\e5a0"}.fa-forward:before{content:"\f04e"}.fa-mobile-android:before,.fa-mobile-phone:before,.fa-mobile:before{content:"\f3ce"}.fa-face-meh:before,.fa-meh:before{content:"\f11a"}.fa-align-center:before{content:"\f037"}.fa-book-dead:before,.fa-book-skull:before{content:"\f6b7"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-heart-circle-exclamation:before{content:"\e4fe"}.fa-home-alt:before,.fa-home-lg-alt:before,.fa-home:before,.fa-house:before{content:"\f015"}.fa-calendar-week:before{content:"\f784"}.fa-laptop-medical:before{content:"\f812"}.fa-b:before{content:"\42"}.fa-file-medical:before{content:"\f477"}.fa-dice-one:before{content:"\f525"}.fa-kiwi-bird:before{content:"\f535"}.fa-arrow-right-arrow-left:before,.fa-exchange:before{content:"\f0ec"}.fa-redo-alt:before,.fa-rotate-forward:before,.fa-rotate-right:before{content:"\f2f9"}.fa-cutlery:before,.fa-utensils:before{content:"\f2e7"}.fa-arrow-up-wide-short:before,.fa-sort-amount-up:before{content:"\f161"}.fa-mill-sign:before{content:"\e1ed"}.fa-bowl-rice:before{content:"\e2eb"}.fa-skull:before{content:"\f54c"}.fa-broadcast-tower:before,.fa-tower-broadcast:before{content:"\f519"}.fa-truck-pickup:before{content:"\f63c"}.fa-long-arrow-alt-up:before,.fa-up-long:before{content:"\f30c"}.fa-stop:before{content:"\f04d"}.fa-code-merge:before{content:"\f387"}.fa-upload:before{content:"\f093"}.fa-hurricane:before{content:"\f751"}.fa-mound:before{content:"\e52d"}.fa-toilet-portable:before{content:"\e583"}.fa-compact-disc:before{content:"\f51f"}.fa-file-arrow-down:before,.fa-file-download:before{content:"\f56d"}.fa-caravan:before{content:"\f8ff"}.fa-shield-cat:before{content:"\e572"}.fa-bolt:before,.fa-zap:before{content:"\f0e7"}.fa-glass-water:before{content:"\e4f4"}.fa-oil-well:before{content:"\e532"}.fa-vault:before{content:"\e2c5"}.fa-mars:before{content:"\f222"}.fa-toilet:before{content:"\f7d8"}.fa-plane-circle-xmark:before{content:"\e557"}.fa-cny:before,.fa-jpy:before,.fa-rmb:before,.fa-yen-sign:before,.fa-yen:before{content:"\f157"}.fa-rouble:before,.fa-rub:before,.fa-ruble-sign:before,.fa-ruble:before{content:"\f158"}.fa-sun:before{content:"\f185"}.fa-guitar:before{content:"\f7a6"}.fa-face-laugh-wink:before,.fa-laugh-wink:before{content:"\f59c"}.fa-horse-head:before{content:"\f7ab"}.fa-bore-hole:before{content:"\e4c3"}.fa-industry:before{content:"\f275"}.fa-arrow-alt-circle-down:before,.fa-circle-down:before{content:"\f358"}.fa-arrows-turn-to-dots:before{content:"\e4c1"}.fa-florin-sign:before{content:"\e184"}.fa-arrow-down-short-wide:before,.fa-sort-amount-desc:before,.fa-sort-amount-down-alt:before{content:"\f884"}.fa-less-than:before{content:"\3c"}.fa-angle-down:before{content:"\f107"}.fa-car-tunnel:before{content:"\e4de"}.fa-head-side-cough:before{content:"\e061"}.fa-grip-lines:before{content:"\f7a4"}.fa-thumbs-down:before{content:"\f165"}.fa-user-lock:before{content:"\f502"}.fa-arrow-right-long:before,.fa-long-arrow-right:before{content:"\f178"}.fa-anchor-circle-xmark:before{content:"\e4ac"}.fa-ellipsis-h:before,.fa-ellipsis:before{content:"\f141"}.fa-chess-pawn:before{content:"\f443"}.fa-first-aid:before,.fa-kit-medical:before{content:"\f479"}.fa-person-through-window:before{content:"\e5a9"}.fa-toolbox:before{content:"\f552"}.fa-hands-holding-circle:before{content:"\e4fb"}.fa-bug:before{content:"\f188"}.fa-credit-card-alt:before,.fa-credit-card:before{content:"\f09d"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-hand-holding-hand:before{content:"\e4f7"}.fa-book-open-reader:before,.fa-book-reader:before{content:"\f5da"}.fa-mountain-sun:before{content:"\e52f"}.fa-arrows-left-right-to-line:before{content:"\e4ba"}.fa-dice-d20:before{content:"\f6cf"}.fa-truck-droplet:before{content:"\e58c"}.fa-file-circle-xmark:before{content:"\e5a1"}.fa-temperature-arrow-up:before,.fa-temperature-up:before{content:"\e040"}.fa-medal:before{content:"\f5a2"}.fa-bed:before{content:"\f236"}.fa-h-square:before,.fa-square-h:before{content:"\f0fd"}.fa-podcast:before{content:"\f2ce"}.fa-temperature-4:before,.fa-temperature-full:before,.fa-thermometer-4:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-bell:before{content:"\f0f3"}.fa-superscript:before{content:"\f12b"}.fa-plug-circle-xmark:before{content:"\e560"}.fa-star-of-life:before{content:"\f621"}.fa-phone-slash:before{content:"\f3dd"}.fa-paint-roller:before{content:"\f5aa"}.fa-hands-helping:before,.fa-handshake-angle:before{content:"\f4c4"}.fa-location-dot:before,.fa-map-marker-alt:before{content:"\f3c5"}.fa-file:before{content:"\f15b"}.fa-greater-than:before{content:"\3e"}.fa-person-swimming:before,.fa-swimmer:before{content:"\f5c4"}.fa-arrow-down:before{content:"\f063"}.fa-droplet:before,.fa-tint:before{content:"\f043"}.fa-eraser:before{content:"\f12d"}.fa-earth-america:before,.fa-earth-americas:before,.fa-earth:before,.fa-globe-americas:before{content:"\f57d"}.fa-person-burst:before{content:"\e53b"}.fa-dove:before{content:"\f4ba"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-socks:before{content:"\f696"}.fa-inbox:before{content:"\f01c"}.fa-section:before{content:"\e447"}.fa-gauge-high:before,.fa-tachometer-alt-fast:before,.fa-tachometer-alt:before{content:"\f625"}.fa-envelope-open-text:before{content:"\f658"}.fa-hospital-alt:before,.fa-hospital-wide:before,.fa-hospital:before{content:"\f0f8"}.fa-wine-bottle:before{content:"\f72f"}.fa-chess-rook:before{content:"\f447"}.fa-bars-staggered:before,.fa-reorder:before,.fa-stream:before{content:"\f550"}.fa-dharmachakra:before{content:"\f655"}.fa-hotdog:before{content:"\f80f"}.fa-blind:before,.fa-person-walking-with-cane:before{content:"\f29d"}.fa-drum:before{content:"\f569"}.fa-ice-cream:before{content:"\f810"}.fa-heart-circle-bolt:before{content:"\e4fc"}.fa-fax:before{content:"\f1ac"}.fa-paragraph:before{content:"\f1dd"}.fa-check-to-slot:before,.fa-vote-yea:before{content:"\f772"}.fa-star-half:before{content:"\f089"}.fa-boxes-alt:before,.fa-boxes-stacked:before,.fa-boxes:before{content:"\f468"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-assistive-listening-systems:before,.fa-ear-listen:before{content:"\f2a2"}.fa-tree-city:before{content:"\e587"}.fa-play:before{content:"\f04b"}.fa-font:before{content:"\f031"}.fa-rupiah-sign:before{content:"\e23d"}.fa-magnifying-glass:before,.fa-search:before{content:"\f002"}.fa-ping-pong-paddle-ball:before,.fa-table-tennis-paddle-ball:before,.fa-table-tennis:before{content:"\f45d"}.fa-diagnoses:before,.fa-person-dots-from-line:before{content:"\f470"}.fa-trash-can-arrow-up:before,.fa-trash-restore-alt:before{content:"\f82a"}.fa-naira-sign:before{content:"\e1f6"}.fa-cart-arrow-down:before{content:"\f218"}.fa-walkie-talkie:before{content:"\f8ef"}.fa-file-edit:before,.fa-file-pen:before{content:"\f31c"}.fa-receipt:before{content:"\f543"}.fa-pen-square:before,.fa-pencil-square:before,.fa-square-pen:before{content:"\f14b"}.fa-suitcase-rolling:before{content:"\f5c1"}.fa-person-circle-exclamation:before{content:"\e53f"}.fa-chevron-down:before{content:"\f078"}.fa-battery-5:before,.fa-battery-full:before,.fa-battery:before{content:"\f240"}.fa-skull-crossbones:before{content:"\f714"}.fa-code-compare:before{content:"\e13a"}.fa-list-dots:before,.fa-list-ul:before{content:"\f0ca"}.fa-school-lock:before{content:"\e56f"}.fa-tower-cell:before{content:"\e585"}.fa-down-long:before,.fa-long-arrow-alt-down:before{content:"\f309"}.fa-ranking-star:before{content:"\e561"}.fa-chess-king:before{content:"\f43f"}.fa-person-harassing:before{content:"\e549"}.fa-brazilian-real-sign:before{content:"\e46c"}.fa-landmark-alt:before,.fa-landmark-dome:before{content:"\f752"}.fa-arrow-up:before{content:"\f062"}.fa-television:before,.fa-tv-alt:before,.fa-tv:before{content:"\f26c"}.fa-shrimp:before{content:"\e448"}.fa-list-check:before,.fa-tasks:before{content:"\f0ae"}.fa-jug-detergent:before{content:"\e519"}.fa-circle-user:before,.fa-user-circle:before{content:"\f2bd"}.fa-user-shield:before{content:"\f505"}.fa-wind:before{content:"\f72e"}.fa-car-burst:before,.fa-car-crash:before{content:"\f5e1"}.fa-y:before{content:"\59"}.fa-person-snowboarding:before,.fa-snowboarding:before{content:"\f7ce"}.fa-shipping-fast:before,.fa-truck-fast:before{content:"\f48b"}.fa-fish:before{content:"\f578"}.fa-user-graduate:before{content:"\f501"}.fa-adjust:before,.fa-circle-half-stroke:before{content:"\f042"}.fa-clapperboard:before{content:"\e131"}.fa-circle-radiation:before,.fa-radiation-alt:before{content:"\f7ba"}.fa-baseball-ball:before,.fa-baseball:before{content:"\f433"}.fa-jet-fighter-up:before{content:"\e518"}.fa-diagram-project:before,.fa-project-diagram:before{content:"\f542"}.fa-copy:before{content:"\f0c5"}.fa-volume-mute:before,.fa-volume-times:before,.fa-volume-xmark:before{content:"\f6a9"}.fa-hand-sparkles:before{content:"\e05d"}.fa-grip-horizontal:before,.fa-grip:before{content:"\f58d"}.fa-share-from-square:before,.fa-share-square:before{content:"\f14d"}.fa-child-combatant:before,.fa-child-rifle:before{content:"\e4e0"}.fa-gun:before{content:"\e19b"}.fa-phone-square:before,.fa-square-phone:before{content:"\f098"}.fa-add:before,.fa-plus:before{content:"\2b"}.fa-expand:before{content:"\f065"}.fa-computer:before{content:"\e4e5"}.fa-close:before,.fa-multiply:before,.fa-remove:before,.fa-times:before,.fa-xmark:before{content:"\f00d"}.fa-arrows-up-down-left-right:before,.fa-arrows:before{content:"\f047"}.fa-chalkboard-teacher:before,.fa-chalkboard-user:before{content:"\f51c"}.fa-peso-sign:before{content:"\e222"}.fa-building-shield:before{content:"\e4d8"}.fa-baby:before{content:"\f77c"}.fa-users-line:before{content:"\e592"}.fa-quote-left-alt:before,.fa-quote-left:before{content:"\f10d"}.fa-tractor:before{content:"\f722"}.fa-trash-arrow-up:before,.fa-trash-restore:before{content:"\f829"}.fa-arrow-down-up-lock:before{content:"\e4b0"}.fa-lines-leaning:before{content:"\e51e"}.fa-ruler-combined:before{content:"\f546"}.fa-copyright:before{content:"\f1f9"}.fa-equals:before{content:"\3d"}.fa-blender:before{content:"\f517"}.fa-teeth:before{content:"\f62e"}.fa-ils:before,.fa-shekel-sign:before,.fa-shekel:before,.fa-sheqel-sign:before,.fa-sheqel:before{content:"\f20b"}.fa-map:before{content:"\f279"}.fa-rocket:before{content:"\f135"}.fa-photo-film:before,.fa-photo-video:before{content:"\f87c"}.fa-folder-minus:before{content:"\f65d"}.fa-store:before{content:"\f54e"}.fa-arrow-trend-up:before{content:"\e098"}.fa-plug-circle-minus:before{content:"\e55e"}.fa-sign-hanging:before,.fa-sign:before{content:"\f4d9"}.fa-bezier-curve:before{content:"\f55b"}.fa-bell-slash:before{content:"\f1f6"}.fa-tablet-android:before,.fa-tablet:before{content:"\f3fb"}.fa-school-flag:before{content:"\e56e"}.fa-fill:before{content:"\f575"}.fa-angle-up:before{content:"\f106"}.fa-drumstick-bite:before{content:"\f6d7"}.fa-holly-berry:before{content:"\f7aa"}.fa-chevron-left:before{content:"\f053"}.fa-bacteria:before{content:"\e059"}.fa-hand-lizard:before{content:"\f258"}.fa-notdef:before{content:"\e1fe"}.fa-disease:before{content:"\f7fa"}.fa-briefcase-medical:before{content:"\f469"}.fa-genderless:before{content:"\f22d"}.fa-chevron-right:before{content:"\f054"}.fa-retweet:before{content:"\f079"}.fa-car-alt:before,.fa-car-rear:before{content:"\f5de"}.fa-pump-soap:before{content:"\e06b"}.fa-video-slash:before{content:"\f4e2"}.fa-battery-2:before,.fa-battery-quarter:before{content:"\f243"}.fa-radio:before{content:"\f8d7"}.fa-baby-carriage:before,.fa-carriage-baby:before{content:"\f77d"}.fa-traffic-light:before{content:"\f637"}.fa-thermometer:before{content:"\f491"}.fa-vr-cardboard:before{content:"\f729"}.fa-hand-middle-finger:before{content:"\f806"}.fa-percent:before,.fa-percentage:before{content:"\25"}.fa-truck-moving:before{content:"\f4df"}.fa-glass-water-droplet:before{content:"\e4f5"}.fa-display:before{content:"\e163"}.fa-face-smile:before,.fa-smile:before{content:"\f118"}.fa-thumb-tack:before,.fa-thumbtack:before{content:"\f08d"}.fa-trophy:before{content:"\f091"}.fa-person-praying:before,.fa-pray:before{content:"\f683"}.fa-hammer:before{content:"\f6e3"}.fa-hand-peace:before{content:"\f25b"}.fa-rotate:before,.fa-sync-alt:before{content:"\f2f1"}.fa-spinner:before{content:"\f110"}.fa-robot:before{content:"\f544"}.fa-peace:before{content:"\f67c"}.fa-cogs:before,.fa-gears:before{content:"\f085"}.fa-warehouse:before{content:"\f494"}.fa-arrow-up-right-dots:before{content:"\e4b7"}.fa-splotch:before{content:"\f5bc"}.fa-face-grin-hearts:before,.fa-grin-hearts:before{content:"\f584"}.fa-dice-four:before{content:"\f524"}.fa-sim-card:before{content:"\f7c4"}.fa-transgender-alt:before,.fa-transgender:before{content:"\f225"}.fa-mercury:before{content:"\f223"}.fa-arrow-turn-down:before,.fa-level-down:before{content:"\f149"}.fa-person-falling-burst:before{content:"\e547"}.fa-award:before{content:"\f559"}.fa-ticket-alt:before,.fa-ticket-simple:before{content:"\f3ff"}.fa-building:before{content:"\f1ad"}.fa-angle-double-left:before,.fa-angles-left:before{content:"\f100"}.fa-qrcode:before{content:"\f029"}.fa-clock-rotate-left:before,.fa-history:before{content:"\f1da"}.fa-face-grin-beam-sweat:before,.fa-grin-beam-sweat:before{content:"\f583"}.fa-arrow-right-from-file:before,.fa-file-export:before{content:"\f56e"}.fa-shield-blank:before,.fa-shield:before{content:"\f132"}.fa-arrow-up-short-wide:before,.fa-sort-amount-up-alt:before{content:"\f885"}.fa-house-medical:before{content:"\e3b2"}.fa-golf-ball-tee:before,.fa-golf-ball:before{content:"\f450"}.fa-chevron-circle-left:before,.fa-circle-chevron-left:before{content:"\f137"}.fa-house-chimney-window:before{content:"\e00d"}.fa-pen-nib:before{content:"\f5ad"}.fa-tent-arrow-turn-left:before{content:"\e580"}.fa-tents:before{content:"\e582"}.fa-magic:before,.fa-wand-magic:before{content:"\f0d0"}.fa-dog:before{content:"\f6d3"}.fa-carrot:before{content:"\f787"}.fa-moon:before{content:"\f186"}.fa-wine-glass-alt:before,.fa-wine-glass-empty:before{content:"\f5ce"}.fa-cheese:before{content:"\f7ef"}.fa-yin-yang:before{content:"\f6ad"}.fa-music:before{content:"\f001"}.fa-code-commit:before{content:"\f386"}.fa-temperature-low:before{content:"\f76b"}.fa-biking:before,.fa-person-biking:before{content:"\f84a"}.fa-broom:before{content:"\f51a"}.fa-shield-heart:before{content:"\e574"}.fa-gopuram:before{content:"\f664"}.fa-earth-oceania:before,.fa-globe-oceania:before{content:"\e47b"}.fa-square-xmark:before,.fa-times-square:before,.fa-xmark-square:before{content:"\f2d3"}.fa-hashtag:before{content:"\23"}.fa-expand-alt:before,.fa-up-right-and-down-left-from-center:before{content:"\f424"}.fa-oil-can:before{content:"\f613"}.fa-t:before{content:"\54"}.fa-hippo:before{content:"\f6ed"}.fa-chart-column:before{content:"\e0e3"}.fa-infinity:before{content:"\f534"}.fa-vial-circle-check:before{content:"\e596"}.fa-person-arrow-down-to-line:before{content:"\e538"}.fa-voicemail:before{content:"\f897"}.fa-fan:before{content:"\f863"}.fa-person-walking-luggage:before{content:"\e554"}.fa-arrows-alt-v:before,.fa-up-down:before{content:"\f338"}.fa-cloud-moon-rain:before{content:"\f73c"}.fa-calendar:before{content:"\f133"}.fa-trailer:before{content:"\e041"}.fa-bahai:before,.fa-haykal:before{content:"\f666"}.fa-sd-card:before{content:"\f7c2"}.fa-dragon:before{content:"\f6d5"}.fa-shoe-prints:before{content:"\f54b"}.fa-circle-plus:before,.fa-plus-circle:before{content:"\f055"}.fa-face-grin-tongue-wink:before,.fa-grin-tongue-wink:before{content:"\f58b"}.fa-hand-holding:before{content:"\f4bd"}.fa-plug-circle-exclamation:before{content:"\e55d"}.fa-chain-broken:before,.fa-chain-slash:before,.fa-link-slash:before,.fa-unlink:before{content:"\f127"}.fa-clone:before{content:"\f24d"}.fa-person-walking-arrow-loop-left:before{content:"\e551"}.fa-arrow-up-z-a:before,.fa-sort-alpha-up-alt:before{content:"\f882"}.fa-fire-alt:before,.fa-fire-flame-curved:before{content:"\f7e4"}.fa-tornado:before{content:"\f76f"}.fa-file-circle-plus:before{content:"\e494"}.fa-book-quran:before,.fa-quran:before{content:"\f687"}.fa-anchor:before{content:"\f13d"}.fa-border-all:before{content:"\f84c"}.fa-angry:before,.fa-face-angry:before{content:"\f556"}.fa-cookie-bite:before{content:"\f564"}.fa-arrow-trend-down:before{content:"\e097"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-draw-polygon:before{content:"\f5ee"}.fa-balance-scale:before,.fa-scale-balanced:before{content:"\f24e"}.fa-gauge-simple-high:before,.fa-tachometer-fast:before,.fa-tachometer:before{content:"\f62a"}.fa-shower:before{content:"\f2cc"}.fa-desktop-alt:before,.fa-desktop:before{content:"\f390"}.fa-m:before{content:"\4d"}.fa-table-list:before,.fa-th-list:before{content:"\f00b"}.fa-comment-sms:before,.fa-sms:before{content:"\f7cd"}.fa-book:before{content:"\f02d"}.fa-user-plus:before{content:"\f234"}.fa-check:before{content:"\f00c"}.fa-battery-4:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-house-circle-check:before{content:"\e509"}.fa-angle-left:before{content:"\f104"}.fa-diagram-successor:before{content:"\e47a"}.fa-truck-arrow-right:before{content:"\e58b"}.fa-arrows-split-up-and-left:before{content:"\e4bc"}.fa-fist-raised:before,.fa-hand-fist:before{content:"\f6de"}.fa-cloud-moon:before{content:"\f6c3"}.fa-briefcase:before{content:"\f0b1"}.fa-person-falling:before{content:"\e546"}.fa-image-portrait:before,.fa-portrait:before{content:"\f3e0"}.fa-user-tag:before{content:"\f507"}.fa-rug:before{content:"\e569"}.fa-earth-europe:before,.fa-globe-europe:before{content:"\f7a2"}.fa-cart-flatbed-suitcase:before,.fa-luggage-cart:before{content:"\f59d"}.fa-rectangle-times:before,.fa-rectangle-xmark:before,.fa-times-rectangle:before,.fa-window-close:before{content:"\f410"}.fa-baht-sign:before{content:"\e0ac"}.fa-book-open:before{content:"\f518"}.fa-book-journal-whills:before,.fa-journal-whills:before{content:"\f66a"}.fa-handcuffs:before{content:"\e4f8"}.fa-exclamation-triangle:before,.fa-triangle-exclamation:before,.fa-warning:before{content:"\f071"}.fa-database:before{content:"\f1c0"}.fa-arrow-turn-right:before,.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-bottle-droplet:before{content:"\e4c4"}.fa-mask-face:before{content:"\e1d7"}.fa-hill-rockslide:before{content:"\e508"}.fa-exchange-alt:before,.fa-right-left:before{content:"\f362"}.fa-paper-plane:before{content:"\f1d8"}.fa-road-circle-exclamation:before{content:"\e565"}.fa-dungeon:before{content:"\f6d9"}.fa-align-right:before{content:"\f038"}.fa-money-bill-1-wave:before,.fa-money-bill-wave-alt:before{content:"\f53b"}.fa-life-ring:before{content:"\f1cd"}.fa-hands:before,.fa-sign-language:before,.fa-signing:before{content:"\f2a7"}.fa-calendar-day:before{content:"\f783"}.fa-ladder-water:before,.fa-swimming-pool:before,.fa-water-ladder:before{content:"\f5c5"}.fa-arrows-up-down:before,.fa-arrows-v:before{content:"\f07d"}.fa-face-grimace:before,.fa-grimace:before{content:"\f57f"}.fa-wheelchair-alt:before,.fa-wheelchair-move:before{content:"\e2ce"}.fa-level-down-alt:before,.fa-turn-down:before{content:"\f3be"}.fa-person-walking-arrow-right:before{content:"\e552"}.fa-envelope-square:before,.fa-square-envelope:before{content:"\f199"}.fa-dice:before{content:"\f522"}.fa-bowling-ball:before{content:"\f436"}.fa-brain:before{content:"\f5dc"}.fa-band-aid:before,.fa-bandage:before{content:"\f462"}.fa-calendar-minus:before{content:"\f272"}.fa-circle-xmark:before,.fa-times-circle:before,.fa-xmark-circle:before{content:"\f057"}.fa-gifts:before{content:"\f79c"}.fa-hotel:before{content:"\f594"}.fa-earth-asia:before,.fa-globe-asia:before{content:"\f57e"}.fa-id-card-alt:before,.fa-id-card-clip:before{content:"\f47f"}.fa-magnifying-glass-plus:before,.fa-search-plus:before{content:"\f00e"}.fa-thumbs-up:before{content:"\f164"}.fa-user-clock:before{content:"\f4fd"}.fa-allergies:before,.fa-hand-dots:before{content:"\f461"}.fa-file-invoice:before{content:"\f570"}.fa-window-minimize:before{content:"\f2d1"}.fa-coffee:before,.fa-mug-saucer:before{content:"\f0f4"}.fa-brush:before{content:"\f55d"}.fa-mask:before{content:"\f6fa"}.fa-magnifying-glass-minus:before,.fa-search-minus:before{content:"\f010"}.fa-ruler-vertical:before{content:"\f548"}.fa-user-alt:before,.fa-user-large:before{content:"\f406"}.fa-train-tram:before{content:"\e5b4"}.fa-user-nurse:before{content:"\f82f"}.fa-syringe:before{content:"\f48e"}.fa-cloud-sun:before{content:"\f6c4"}.fa-stopwatch-20:before{content:"\e06f"}.fa-square-full:before{content:"\f45c"}.fa-magnet:before{content:"\f076"}.fa-jar:before{content:"\e516"}.fa-note-sticky:before,.fa-sticky-note:before{content:"\f249"}.fa-bug-slash:before{content:"\e490"}.fa-arrow-up-from-water-pump:before{content:"\e4b6"}.fa-bone:before{content:"\f5d7"}.fa-user-injured:before{content:"\f728"}.fa-face-sad-tear:before,.fa-sad-tear:before{content:"\f5b4"}.fa-plane:before{content:"\f072"}.fa-tent-arrows-down:before{content:"\e581"}.fa-exclamation:before{content:"\21"}.fa-arrows-spin:before{content:"\e4bb"}.fa-print:before{content:"\f02f"}.fa-try:before,.fa-turkish-lira-sign:before,.fa-turkish-lira:before{content:"\e2bb"}.fa-dollar-sign:before,.fa-dollar:before,.fa-usd:before{content:"\24"}.fa-x:before{content:"\58"}.fa-magnifying-glass-dollar:before,.fa-search-dollar:before{content:"\f688"}.fa-users-cog:before,.fa-users-gear:before{content:"\f509"}.fa-person-military-pointing:before{content:"\e54a"}.fa-bank:before,.fa-building-columns:before,.fa-institution:before,.fa-museum:before,.fa-university:before{content:"\f19c"}.fa-umbrella:before{content:"\f0e9"}.fa-trowel:before{content:"\e589"}.fa-d:before{content:"\44"}.fa-stapler:before{content:"\e5af"}.fa-masks-theater:before,.fa-theater-masks:before{content:"\f630"}.fa-kip-sign:before{content:"\e1c4"}.fa-hand-point-left:before{content:"\f0a5"}.fa-handshake-alt:before,.fa-handshake-simple:before{content:"\f4c6"}.fa-fighter-jet:before,.fa-jet-fighter:before{content:"\f0fb"}.fa-share-alt-square:before,.fa-square-share-nodes:before{content:"\f1e1"}.fa-barcode:before{content:"\f02a"}.fa-plus-minus:before{content:"\e43c"}.fa-video-camera:before,.fa-video:before{content:"\f03d"}.fa-graduation-cap:before,.fa-mortar-board:before{content:"\f19d"}.fa-hand-holding-medical:before{content:"\e05c"}.fa-person-circle-check:before{content:"\e53e"}.fa-level-up-alt:before,.fa-turn-up:before{content:"\f3bf"} +.fa-sr-only,.fa-sr-only-focusable:not(:focus),.sr-only,.sr-only-focusable:not(:focus){position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}:host,:root{--fa-style-family-brands:"Font Awesome 6 Brands";--fa-font-brands:normal 400 1em/1 "Font Awesome 6 Brands"}@font-face{font-family:"Font Awesome 6 Brands";font-style:normal;font-weight:400;font-display:block;src:url(/vendor/font-awesome/webfonts/fa-brands-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-brands-400.ttf) format("truetype")}.fa-brands,.fab{font-weight:400}.fa-monero:before{content:"\f3d0"}.fa-hooli:before{content:"\f427"}.fa-yelp:before{content:"\f1e9"}.fa-cc-visa:before{content:"\f1f0"}.fa-lastfm:before{content:"\f202"}.fa-shopware:before{content:"\f5b5"}.fa-creative-commons-nc:before{content:"\f4e8"}.fa-aws:before{content:"\f375"}.fa-redhat:before{content:"\f7bc"}.fa-yoast:before{content:"\f2b1"}.fa-cloudflare:before{content:"\e07d"}.fa-ups:before{content:"\f7e0"}.fa-wpexplorer:before{content:"\f2de"}.fa-dyalog:before{content:"\f399"}.fa-bity:before{content:"\f37a"}.fa-stackpath:before{content:"\f842"}.fa-buysellads:before{content:"\f20d"}.fa-first-order:before{content:"\f2b0"}.fa-modx:before{content:"\f285"}.fa-guilded:before{content:"\e07e"}.fa-vnv:before{content:"\f40b"}.fa-js-square:before,.fa-square-js:before{content:"\f3b9"}.fa-microsoft:before{content:"\f3ca"}.fa-qq:before{content:"\f1d6"}.fa-orcid:before{content:"\f8d2"}.fa-java:before{content:"\f4e4"}.fa-invision:before{content:"\f7b0"}.fa-creative-commons-pd-alt:before{content:"\f4ed"}.fa-centercode:before{content:"\f380"}.fa-glide-g:before{content:"\f2a6"}.fa-drupal:before{content:"\f1a9"}.fa-hire-a-helper:before{content:"\f3b0"}.fa-creative-commons-by:before{content:"\f4e7"}.fa-unity:before{content:"\e049"}.fa-whmcs:before{content:"\f40d"}.fa-rocketchat:before{content:"\f3e8"}.fa-vk:before{content:"\f189"}.fa-untappd:before{content:"\f405"}.fa-mailchimp:before{content:"\f59e"}.fa-css3-alt:before{content:"\f38b"}.fa-reddit-square:before,.fa-square-reddit:before{content:"\f1a2"}.fa-vimeo-v:before{content:"\f27d"}.fa-contao:before{content:"\f26d"}.fa-square-font-awesome:before{content:"\e5ad"}.fa-deskpro:before{content:"\f38f"}.fa-sistrix:before{content:"\f3ee"}.fa-instagram-square:before,.fa-square-instagram:before{content:"\e055"}.fa-battle-net:before{content:"\f835"}.fa-the-red-yeti:before{content:"\f69d"}.fa-hacker-news-square:before,.fa-square-hacker-news:before{content:"\f3af"}.fa-edge:before{content:"\f282"}.fa-napster:before{content:"\f3d2"}.fa-snapchat-square:before,.fa-square-snapchat:before{content:"\f2ad"}.fa-google-plus-g:before{content:"\f0d5"}.fa-artstation:before{content:"\f77a"}.fa-markdown:before{content:"\f60f"}.fa-sourcetree:before{content:"\f7d3"}.fa-google-plus:before{content:"\f2b3"}.fa-diaspora:before{content:"\f791"}.fa-foursquare:before{content:"\f180"}.fa-stack-overflow:before{content:"\f16c"}.fa-github-alt:before{content:"\f113"}.fa-phoenix-squadron:before{content:"\f511"}.fa-pagelines:before{content:"\f18c"}.fa-algolia:before{content:"\f36c"}.fa-red-river:before{content:"\f3e3"}.fa-creative-commons-sa:before{content:"\f4ef"}.fa-safari:before{content:"\f267"}.fa-google:before{content:"\f1a0"}.fa-font-awesome-alt:before,.fa-square-font-awesome-stroke:before{content:"\f35c"}.fa-atlassian:before{content:"\f77b"}.fa-linkedin-in:before{content:"\f0e1"}.fa-digital-ocean:before{content:"\f391"}.fa-nimblr:before{content:"\f5a8"}.fa-chromecast:before{content:"\f838"}.fa-evernote:before{content:"\f839"}.fa-hacker-news:before{content:"\f1d4"}.fa-creative-commons-sampling:before{content:"\f4f0"}.fa-adversal:before{content:"\f36a"}.fa-creative-commons:before{content:"\f25e"}.fa-watchman-monitoring:before{content:"\e087"}.fa-fonticons:before{content:"\f280"}.fa-weixin:before{content:"\f1d7"}.fa-shirtsinbulk:before{content:"\f214"}.fa-codepen:before{content:"\f1cb"}.fa-git-alt:before{content:"\f841"}.fa-lyft:before{content:"\f3c3"}.fa-rev:before{content:"\f5b2"}.fa-windows:before{content:"\f17a"}.fa-wizards-of-the-coast:before{content:"\f730"}.fa-square-viadeo:before,.fa-viadeo-square:before{content:"\f2aa"}.fa-meetup:before{content:"\f2e0"}.fa-centos:before{content:"\f789"}.fa-adn:before{content:"\f170"}.fa-cloudsmith:before{content:"\f384"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-dribbble-square:before,.fa-square-dribbble:before{content:"\f397"}.fa-codiepie:before{content:"\f284"}.fa-node:before{content:"\f419"}.fa-mix:before{content:"\f3cb"}.fa-steam:before{content:"\f1b6"}.fa-cc-apple-pay:before{content:"\f416"}.fa-scribd:before{content:"\f28a"}.fa-openid:before{content:"\f19b"}.fa-instalod:before{content:"\e081"}.fa-expeditedssl:before{content:"\f23e"}.fa-sellcast:before{content:"\f2da"}.fa-square-twitter:before,.fa-twitter-square:before{content:"\f081"}.fa-r-project:before{content:"\f4f7"}.fa-delicious:before{content:"\f1a5"}.fa-freebsd:before{content:"\f3a4"}.fa-vuejs:before{content:"\f41f"}.fa-accusoft:before{content:"\f369"}.fa-ioxhost:before{content:"\f208"}.fa-fonticons-fi:before{content:"\f3a2"}.fa-app-store:before{content:"\f36f"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-itunes-note:before{content:"\f3b5"}.fa-golang:before{content:"\e40f"}.fa-kickstarter:before{content:"\f3bb"}.fa-grav:before{content:"\f2d6"}.fa-weibo:before{content:"\f18a"}.fa-uncharted:before{content:"\e084"}.fa-firstdraft:before{content:"\f3a1"}.fa-square-youtube:before,.fa-youtube-square:before{content:"\f431"}.fa-wikipedia-w:before{content:"\f266"}.fa-rendact:before,.fa-wpressr:before{content:"\f3e4"}.fa-angellist:before{content:"\f209"}.fa-galactic-republic:before{content:"\f50c"}.fa-nfc-directional:before{content:"\e530"}.fa-skype:before{content:"\f17e"}.fa-joget:before{content:"\f3b7"}.fa-fedora:before{content:"\f798"}.fa-stripe-s:before{content:"\f42a"}.fa-meta:before{content:"\e49b"}.fa-laravel:before{content:"\f3bd"}.fa-hotjar:before{content:"\f3b1"}.fa-bluetooth-b:before{content:"\f294"}.fa-sticker-mule:before{content:"\f3f7"}.fa-creative-commons-zero:before{content:"\f4f3"}.fa-hips:before{content:"\f452"}.fa-behance:before{content:"\f1b4"}.fa-reddit:before{content:"\f1a1"}.fa-discord:before{content:"\f392"}.fa-chrome:before{content:"\f268"}.fa-app-store-ios:before{content:"\f370"}.fa-cc-discover:before{content:"\f1f2"}.fa-wpbeginner:before{content:"\f297"}.fa-confluence:before{content:"\f78d"}.fa-mdb:before{content:"\f8ca"}.fa-dochub:before{content:"\f394"}.fa-accessible-icon:before{content:"\f368"}.fa-ebay:before{content:"\f4f4"}.fa-amazon:before{content:"\f270"}.fa-unsplash:before{content:"\e07c"}.fa-yarn:before{content:"\f7e3"}.fa-square-steam:before,.fa-steam-square:before{content:"\f1b7"}.fa-500px:before{content:"\f26e"}.fa-square-vimeo:before,.fa-vimeo-square:before{content:"\f194"}.fa-asymmetrik:before{content:"\f372"}.fa-font-awesome-flag:before,.fa-font-awesome-logo-full:before,.fa-font-awesome:before{content:"\f2b4"}.fa-gratipay:before{content:"\f184"}.fa-apple:before{content:"\f179"}.fa-hive:before{content:"\e07f"}.fa-gitkraken:before{content:"\f3a6"}.fa-keybase:before{content:"\f4f5"}.fa-apple-pay:before{content:"\f415"}.fa-padlet:before{content:"\e4a0"}.fa-amazon-pay:before{content:"\f42c"}.fa-github-square:before,.fa-square-github:before{content:"\f092"}.fa-stumbleupon:before{content:"\f1a4"}.fa-fedex:before{content:"\f797"}.fa-phoenix-framework:before{content:"\f3dc"}.fa-shopify:before{content:"\e057"}.fa-neos:before{content:"\f612"}.fa-hackerrank:before{content:"\f5f7"}.fa-researchgate:before{content:"\f4f8"}.fa-swift:before{content:"\f8e1"}.fa-angular:before{content:"\f420"}.fa-speakap:before{content:"\f3f3"}.fa-angrycreative:before{content:"\f36e"}.fa-y-combinator:before{content:"\f23b"}.fa-empire:before{content:"\f1d1"}.fa-envira:before{content:"\f299"}.fa-gitlab-square:before,.fa-square-gitlab:before{content:"\e5ae"}.fa-studiovinari:before{content:"\f3f8"}.fa-pied-piper:before{content:"\f2ae"}.fa-wordpress:before{content:"\f19a"}.fa-product-hunt:before{content:"\f288"}.fa-firefox:before{content:"\f269"}.fa-linode:before{content:"\f2b8"}.fa-goodreads:before{content:"\f3a8"}.fa-odnoklassniki-square:before,.fa-square-odnoklassniki:before{content:"\f264"}.fa-jsfiddle:before{content:"\f1cc"}.fa-sith:before{content:"\f512"}.fa-themeisle:before{content:"\f2b2"}.fa-page4:before{content:"\f3d7"}.fa-hashnode:before{content:"\e499"}.fa-react:before{content:"\f41b"}.fa-cc-paypal:before{content:"\f1f4"}.fa-squarespace:before{content:"\f5be"}.fa-cc-stripe:before{content:"\f1f5"}.fa-creative-commons-share:before{content:"\f4f2"}.fa-bitcoin:before{content:"\f379"}.fa-keycdn:before{content:"\f3ba"}.fa-opera:before{content:"\f26a"}.fa-itch-io:before{content:"\f83a"}.fa-umbraco:before{content:"\f8e8"}.fa-galactic-senate:before{content:"\f50d"}.fa-ubuntu:before{content:"\f7df"}.fa-draft2digital:before{content:"\f396"}.fa-stripe:before{content:"\f429"}.fa-houzz:before{content:"\f27c"}.fa-gg:before{content:"\f260"}.fa-dhl:before{content:"\f790"}.fa-pinterest-square:before,.fa-square-pinterest:before{content:"\f0d3"}.fa-xing:before{content:"\f168"}.fa-blackberry:before{content:"\f37b"}.fa-creative-commons-pd:before{content:"\f4ec"}.fa-playstation:before{content:"\f3df"}.fa-quinscape:before{content:"\f459"}.fa-less:before{content:"\f41d"}.fa-blogger-b:before{content:"\f37d"}.fa-opencart:before{content:"\f23d"}.fa-vine:before{content:"\f1ca"}.fa-paypal:before{content:"\f1ed"}.fa-gitlab:before{content:"\f296"}.fa-typo3:before{content:"\f42b"}.fa-reddit-alien:before{content:"\f281"}.fa-yahoo:before{content:"\f19e"}.fa-dailymotion:before{content:"\e052"}.fa-affiliatetheme:before{content:"\f36b"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-bootstrap:before{content:"\f836"}.fa-odnoklassniki:before{content:"\f263"}.fa-nfc-symbol:before{content:"\e531"}.fa-ethereum:before{content:"\f42e"}.fa-speaker-deck:before{content:"\f83c"}.fa-creative-commons-nc-eu:before{content:"\f4e9"}.fa-patreon:before{content:"\f3d9"}.fa-avianex:before{content:"\f374"}.fa-ello:before{content:"\f5f1"}.fa-gofore:before{content:"\f3a7"}.fa-bimobject:before{content:"\f378"}.fa-facebook-f:before{content:"\f39e"}.fa-google-plus-square:before,.fa-square-google-plus:before{content:"\f0d4"}.fa-mandalorian:before{content:"\f50f"}.fa-first-order-alt:before{content:"\f50a"}.fa-osi:before{content:"\f41a"}.fa-google-wallet:before{content:"\f1ee"}.fa-d-and-d-beyond:before{content:"\f6ca"}.fa-periscope:before{content:"\f3da"}.fa-fulcrum:before{content:"\f50b"}.fa-cloudscale:before{content:"\f383"}.fa-forumbee:before{content:"\f211"}.fa-mizuni:before{content:"\f3cc"}.fa-schlix:before{content:"\f3ea"}.fa-square-xing:before,.fa-xing-square:before{content:"\f169"}.fa-bandcamp:before{content:"\f2d5"}.fa-wpforms:before{content:"\f298"}.fa-cloudversify:before{content:"\f385"}.fa-usps:before{content:"\f7e1"}.fa-megaport:before{content:"\f5a3"}.fa-magento:before{content:"\f3c4"}.fa-spotify:before{content:"\f1bc"}.fa-optin-monster:before{content:"\f23c"}.fa-fly:before{content:"\f417"}.fa-aviato:before{content:"\f421"}.fa-itunes:before{content:"\f3b4"}.fa-cuttlefish:before{content:"\f38c"}.fa-blogger:before{content:"\f37c"}.fa-flickr:before{content:"\f16e"}.fa-viber:before{content:"\f409"}.fa-soundcloud:before{content:"\f1be"}.fa-digg:before{content:"\f1a6"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-symfony:before{content:"\f83d"}.fa-maxcdn:before{content:"\f136"}.fa-etsy:before{content:"\f2d7"}.fa-facebook-messenger:before{content:"\f39f"}.fa-audible:before{content:"\f373"}.fa-think-peaks:before{content:"\f731"}.fa-bilibili:before{content:"\e3d9"}.fa-erlang:before{content:"\f39d"}.fa-cotton-bureau:before{content:"\f89e"}.fa-dashcube:before{content:"\f210"}.fa-42-group:before,.fa-innosoft:before{content:"\e080"}.fa-stack-exchange:before{content:"\f18d"}.fa-elementor:before{content:"\f430"}.fa-pied-piper-square:before,.fa-square-pied-piper:before{content:"\e01e"}.fa-creative-commons-nd:before{content:"\f4eb"}.fa-palfed:before{content:"\f3d8"}.fa-superpowers:before{content:"\f2dd"}.fa-resolving:before{content:"\f3e7"}.fa-xbox:before{content:"\f412"}.fa-searchengin:before{content:"\f3eb"}.fa-tiktok:before{content:"\e07b"}.fa-facebook-square:before,.fa-square-facebook:before{content:"\f082"}.fa-renren:before{content:"\f18b"}.fa-linux:before{content:"\f17c"}.fa-glide:before{content:"\f2a5"}.fa-linkedin:before{content:"\f08c"}.fa-hubspot:before{content:"\f3b2"}.fa-deploydog:before{content:"\f38e"}.fa-twitch:before{content:"\f1e8"}.fa-ravelry:before{content:"\f2d9"}.fa-mixer:before{content:"\e056"}.fa-lastfm-square:before,.fa-square-lastfm:before{content:"\f203"}.fa-vimeo:before{content:"\f40a"}.fa-mendeley:before{content:"\f7b3"}.fa-uniregistry:before{content:"\f404"}.fa-figma:before{content:"\f799"}.fa-creative-commons-remix:before{content:"\f4ee"}.fa-cc-amazon-pay:before{content:"\f42d"}.fa-dropbox:before{content:"\f16b"}.fa-instagram:before{content:"\f16d"}.fa-cmplid:before{content:"\e360"}.fa-facebook:before{content:"\f09a"}.fa-gripfire:before{content:"\f3ac"}.fa-jedi-order:before{content:"\f50e"}.fa-uikit:before{content:"\f403"}.fa-fort-awesome-alt:before{content:"\f3a3"}.fa-phabricator:before{content:"\f3db"}.fa-ussunnah:before{content:"\f407"}.fa-earlybirds:before{content:"\f39a"}.fa-trade-federation:before{content:"\f513"}.fa-autoprefixer:before{content:"\f41c"}.fa-whatsapp:before{content:"\f232"}.fa-slideshare:before{content:"\f1e7"}.fa-google-play:before{content:"\f3ab"}.fa-viadeo:before{content:"\f2a9"}.fa-line:before{content:"\f3c0"}.fa-google-drive:before{content:"\f3aa"}.fa-servicestack:before{content:"\f3ec"}.fa-simplybuilt:before{content:"\f215"}.fa-bitbucket:before{content:"\f171"}.fa-imdb:before{content:"\f2d8"}.fa-deezer:before{content:"\e077"}.fa-raspberry-pi:before{content:"\f7bb"}.fa-jira:before{content:"\f7b1"}.fa-docker:before{content:"\f395"}.fa-screenpal:before{content:"\e570"}.fa-bluetooth:before{content:"\f293"}.fa-gitter:before{content:"\f426"}.fa-d-and-d:before{content:"\f38d"}.fa-microblog:before{content:"\e01a"}.fa-cc-diners-club:before{content:"\f24c"}.fa-gg-circle:before{content:"\f261"}.fa-pied-piper-hat:before{content:"\f4e5"}.fa-kickstarter-k:before{content:"\f3bc"}.fa-yandex:before{content:"\f413"}.fa-readme:before{content:"\f4d5"}.fa-html5:before{content:"\f13b"}.fa-sellsy:before{content:"\f213"}.fa-sass:before{content:"\f41e"}.fa-wirsindhandwerk:before,.fa-wsh:before{content:"\e2d0"}.fa-buromobelexperte:before{content:"\f37f"}.fa-salesforce:before{content:"\f83b"}.fa-octopus-deploy:before{content:"\e082"}.fa-medapps:before{content:"\f3c6"}.fa-ns8:before{content:"\f3d5"}.fa-pinterest-p:before{content:"\f231"}.fa-apper:before{content:"\f371"}.fa-fort-awesome:before{content:"\f286"}.fa-waze:before{content:"\f83f"}.fa-cc-jcb:before{content:"\f24b"}.fa-snapchat-ghost:before,.fa-snapchat:before{content:"\f2ab"}.fa-fantasy-flight-games:before{content:"\f6dc"}.fa-rust:before{content:"\e07a"}.fa-wix:before{content:"\f5cf"}.fa-behance-square:before,.fa-square-behance:before{content:"\f1b5"}.fa-supple:before{content:"\f3f9"}.fa-rebel:before{content:"\f1d0"}.fa-css3:before{content:"\f13c"}.fa-staylinked:before{content:"\f3f5"}.fa-kaggle:before{content:"\f5fa"}.fa-space-awesome:before{content:"\e5ac"}.fa-deviantart:before{content:"\f1bd"}.fa-cpanel:before{content:"\f388"}.fa-goodreads-g:before{content:"\f3a9"}.fa-git-square:before,.fa-square-git:before{content:"\f1d2"}.fa-square-tumblr:before,.fa-tumblr-square:before{content:"\f174"}.fa-trello:before{content:"\f181"}.fa-creative-commons-nc-jp:before{content:"\f4ea"}.fa-get-pocket:before{content:"\f265"}.fa-perbyte:before{content:"\e083"}.fa-grunt:before{content:"\f3ad"}.fa-weebly:before{content:"\f5cc"}.fa-connectdevelop:before{content:"\f20e"}.fa-leanpub:before{content:"\f212"}.fa-black-tie:before{content:"\f27e"}.fa-themeco:before{content:"\f5c6"}.fa-python:before{content:"\f3e2"}.fa-android:before{content:"\f17b"}.fa-bots:before{content:"\e340"}.fa-free-code-camp:before{content:"\f2c5"}.fa-hornbill:before{content:"\f592"}.fa-js:before{content:"\f3b8"}.fa-ideal:before{content:"\e013"}.fa-git:before{content:"\f1d3"}.fa-dev:before{content:"\f6cc"}.fa-sketch:before{content:"\f7c6"}.fa-yandex-international:before{content:"\f414"}.fa-cc-amex:before{content:"\f1f3"}.fa-uber:before{content:"\f402"}.fa-github:before{content:"\f09b"}.fa-php:before{content:"\f457"}.fa-alipay:before{content:"\f642"}.fa-youtube:before{content:"\f167"}.fa-skyatlas:before{content:"\f216"}.fa-firefox-browser:before{content:"\e007"}.fa-replyd:before{content:"\f3e6"}.fa-suse:before{content:"\f7d6"}.fa-jenkins:before{content:"\f3b6"}.fa-twitter:before{content:"\f099"}.fa-rockrms:before{content:"\f3e9"}.fa-pinterest:before{content:"\f0d2"}.fa-buffer:before{content:"\f837"}.fa-npm:before{content:"\f3d4"}.fa-yammer:before{content:"\f840"}.fa-btc:before{content:"\f15a"}.fa-dribbble:before{content:"\f17d"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-internet-explorer:before{content:"\f26b"}.fa-stubber:before{content:"\e5c7"}.fa-telegram-plane:before,.fa-telegram:before{content:"\f2c6"}.fa-old-republic:before{content:"\f510"}.fa-odysee:before{content:"\e5c6"}.fa-square-whatsapp:before,.fa-whatsapp-square:before{content:"\f40c"}.fa-node-js:before{content:"\f3d3"}.fa-edge-legacy:before{content:"\e078"}.fa-slack-hash:before,.fa-slack:before{content:"\f198"}.fa-medrt:before{content:"\f3c8"}.fa-usb:before{content:"\f287"}.fa-tumblr:before{content:"\f173"}.fa-vaadin:before{content:"\f408"}.fa-quora:before{content:"\f2c4"}.fa-reacteurope:before{content:"\f75d"}.fa-medium-m:before,.fa-medium:before{content:"\f23a"}.fa-amilia:before{content:"\f36d"}.fa-mixcloud:before{content:"\f289"}.fa-flipboard:before{content:"\f44d"}.fa-viacoin:before{content:"\f237"}.fa-critical-role:before{content:"\f6c9"}.fa-sitrox:before{content:"\e44a"}.fa-discourse:before{content:"\f393"}.fa-joomla:before{content:"\f1aa"}.fa-mastodon:before{content:"\f4f6"}.fa-airbnb:before{content:"\f834"}.fa-wolf-pack-battalion:before{content:"\f514"}.fa-buy-n-large:before{content:"\f8a6"}.fa-gulp:before{content:"\f3ae"}.fa-creative-commons-sampling-plus:before{content:"\f4f1"}.fa-strava:before{content:"\f428"}.fa-ember:before{content:"\f423"}.fa-canadian-maple-leaf:before{content:"\f785"}.fa-teamspeak:before{content:"\f4f9"}.fa-pushed:before{content:"\f3e1"}.fa-wordpress-simple:before{content:"\f411"}.fa-nutritionix:before{content:"\f3d6"}.fa-wodu:before{content:"\e088"}.fa-google-pay:before{content:"\e079"}.fa-intercom:before{content:"\f7af"}.fa-zhihu:before{content:"\f63f"}.fa-korvue:before{content:"\f42f"}.fa-pix:before{content:"\e43a"}.fa-steam-symbol:before{content:"\f3f6"}:host,:root{--fa-font-regular:normal 400 1em/1 "Font Awesome 6 Free"}@font-face{font-family:"Font Awesome 6 Free";font-style:normal;font-weight:400;font-display:block;src:url(/vendor/font-awesome/webfonts/fa-regular-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-regular-400.ttf) format("truetype")}.fa-regular,.far{font-weight:400}:host,:root{--fa-style-family-classic:"Font Awesome 6 Free";--fa-font-solid:normal 900 1em/1 "Font Awesome 6 Free"}@font-face{font-family:"Font Awesome 6 Free";font-style:normal;font-weight:900;font-display:block;src:url(/vendor/font-awesome/webfonts/fa-solid-900.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-solid-900.ttf) format("truetype")}.fa-solid,.fas{font-weight:900}@font-face{font-family:"Font Awesome 5 Brands";font-display:block;font-weight:400;src:url(/vendor/font-awesome/webfonts/fa-brands-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-brands-400.ttf) format("truetype")}@font-face{font-family:"Font Awesome 5 Free";font-display:block;font-weight:900;src:url(/vendor/font-awesome/webfonts/fa-solid-900.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-solid-900.ttf) format("truetype")}@font-face{font-family:"Font Awesome 5 Free";font-display:block;font-weight:400;src:url(/vendor/font-awesome/webfonts/fa-regular-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-regular-400.ttf) format("truetype")}@font-face{font-family:"FontAwesome";font-display:block;src:url(/vendor/font-awesome/webfonts/fa-solid-900.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-solid-900.ttf) format("truetype")}@font-face{font-family:"FontAwesome";font-display:block;src:url(/vendor/font-awesome/webfonts/fa-brands-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-brands-400.ttf) format("truetype")}@font-face{font-family:"FontAwesome";font-display:block;src:url(/vendor/font-awesome/webfonts/fa-regular-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-regular-400.ttf) format("truetype");unicode-range:u+f003,u+f006,u+f014,u+f016-f017,u+f01a-f01b,u+f01d,u+f022,u+f03e,u+f044,u+f046,u+f05c-f05d,u+f06e,u+f070,u+f087-f088,u+f08a,u+f094,u+f096-f097,u+f09d,u+f0a0,u+f0a2,u+f0a4-f0a7,u+f0c5,u+f0c7,u+f0e5-f0e6,u+f0eb,u+f0f6-f0f8,u+f10c,u+f114-f115,u+f118-f11a,u+f11c-f11d,u+f133,u+f147,u+f14e,u+f150-f152,u+f185-f186,u+f18e,u+f190-f192,u+f196,u+f1c1-f1c9,u+f1d9,u+f1db,u+f1e3,u+f1ea,u+f1f7,u+f1f9,u+f20a,u+f247-f248,u+f24a,u+f24d,u+f255-f25b,u+f25d,u+f271-f274,u+f278,u+f27b,u+f28c,u+f28e,u+f29c,u+f2b5,u+f2b7,u+f2ba,u+f2bc,u+f2be,u+f2c0-f2c1,u+f2c3,u+f2d0,u+f2d2,u+f2d4,u+f2dc}@font-face{font-family:"FontAwesome";font-display:block;src:url(/vendor/font-awesome/webfonts/fa-v4compatibility.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-v4compatibility.ttf) format("truetype");unicode-range:u+f041,u+f047,u+f065-f066,u+f07d-f07e,u+f080,u+f08b,u+f08e,u+f090,u+f09a,u+f0ac,u+f0ae,u+f0b2,u+f0d0,u+f0d6,u+f0e4,u+f0ec,u+f10a-f10b,u+f123,u+f13e,u+f148-f149,u+f14c,u+f156,u+f15e,u+f160-f161,u+f163,u+f175-f178,u+f195,u+f1f8,u+f219,u+f27a} \ No newline at end of file diff --git a/src/public/vendor/font-awesome/webfonts/fa-brands-400.woff2 b/src/public/vendor/font-awesome/webfonts/fa-brands-400.woff2 new file mode 100644 index 0000000..71e3185 Binary files /dev/null and b/src/public/vendor/font-awesome/webfonts/fa-brands-400.woff2 differ diff --git a/src/public/vendor/font-awesome/webfonts/fa-regular-400.woff2 b/src/public/vendor/font-awesome/webfonts/fa-regular-400.woff2 new file mode 100644 index 0000000..7f02168 Binary files /dev/null and b/src/public/vendor/font-awesome/webfonts/fa-regular-400.woff2 differ diff --git a/src/public/vendor/font-awesome/webfonts/fa-solid-900.woff2 b/src/public/vendor/font-awesome/webfonts/fa-solid-900.woff2 new file mode 100644 index 0000000..5c16cd3 Binary files /dev/null and b/src/public/vendor/font-awesome/webfonts/fa-solid-900.woff2 differ diff --git a/src/public/vendor/font-awesome/webfonts/fa-v4compatibility.woff2 b/src/public/vendor/font-awesome/webfonts/fa-v4compatibility.woff2 new file mode 100644 index 0000000..9027e38 Binary files /dev/null and b/src/public/vendor/font-awesome/webfonts/fa-v4compatibility.woff2 differ diff --git a/src/public/vendor/marked.min.js b/src/public/vendor/marked.min.js new file mode 100644 index 0000000..b4e0d73 --- /dev/null +++ b/src/public/vendor/marked.min.js @@ -0,0 +1,69 @@ +/** + * marked v15.0.12 - a markdown parser + * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ +(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; +"use strict";var H=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var ye=(l,e)=>{for(var t in e)H(l,t,{get:e[t],enumerable:!0})},Re=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Te(e))!we.call(l,s)&&s!==t&&H(l,s,{get:()=>e[s],enumerable:!(n=be(e,s))||n.enumerable});return l};var Se=l=>Re(H({},"__esModule",{value:!0}),l);var kt={};ye(kt,{Hooks:()=>L,Lexer:()=>x,Marked:()=>E,Parser:()=>b,Renderer:()=>$,TextRenderer:()=>_,Tokenizer:()=>S,defaults:()=>w,getDefaults:()=>z,lexer:()=>ht,marked:()=>k,options:()=>it,parse:()=>pt,parseInline:()=>ct,parser:()=>ut,setOptions:()=>ot,use:()=>lt,walkTokens:()=>at});module.exports=Se(kt);function z(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var w=z();function N(l){w=l}var I={exec:()=>null};function h(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(s,i)=>{let r=typeof i=="string"?i:i.source;return r=r.replace(m.caret,"$1"),t=t.replace(s,r),n},getRegex:()=>new RegExp(t,e)};return n}var m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i")},$e=/^(?:[ \t]*(?:\n|$))+/,_e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Le=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,O=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ze=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,F=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oe=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Me=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pe=/^[^\n]+/,U=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ae=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,F).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/|$))/,Ce=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",K).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=h(Q).replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Ie=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),X={blockquote:Ie,code:_e,def:Ae,fences:Le,heading:ze,hr:O,html:Ce,lheading:oe,list:Ee,newline:$e,paragraph:le,table:I,text:Pe},re=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Oe={...X,lheading:Me,table:re,paragraph:h(Q).replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",re).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},Be={...X,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:I,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(Q).replace("hr",O).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",oe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ve=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ae=/^( {2,}|\\)\n(?!\s*$)/,De=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,ue=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,je=h(ue,"u").replace(/punct/g,D).getRegex(),Fe=h(ue,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qe=h(he,"gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Ue=h(he,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Ge).replace(/punct/g,pe).getRegex(),Ke=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Xe=h(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),We=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Je=h(K).replace("(?:-->|$)","-->").getRegex(),Ve=h("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Je).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ye=h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=h(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",U).getRegex(),ge=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),et=h("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",ge).getRegex(),J={_backpedal:I,anyPunctuation:Xe,autolink:We,blockSkip:Ne,br:ae,code:ve,del:I,emStrongLDelim:je,emStrongRDelimAst:Qe,emStrongRDelimUnd:Ke,escape:qe,link:Ye,nolink:ge,punctuation:Ze,reflink:ke,reflinkSearch:et,tag:Ve,text:De,url:I},tt={...J,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},j={...J,emStrongRDelimAst:Ue,emStrongLDelim:Fe,url:h(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},fe=l=>st[l];function R(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,fe);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(i,r,o)=>{let a=!1,c=r;for(;--c>=0&&o[c]==="\\";)a=!a;return a?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function me(l,e,t,n,s){let i=e.href,r=e.title||null,o=l[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let a={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:r,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,a}function rt(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(` +`).map(i=>{let r=i.match(t.other.beginningSpace);if(r===null)return i;let[o]=r;return o.length>=s.length?i.slice(s.length):i}).join(` +`)}var S=class{options;rules;lexer;constructor(e){this.options=e||w}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:A(n,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=rt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=A(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:A(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=A(t[0],` +`).split(` +`),s="",i="",r=[];for(;n.length>0;){let o=!1,a=[],c;for(c=0;c1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=t[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,Z=>" ".repeat(3*Z.length)),g=e.split(` +`,1)[0],T=!d.trim(),f=0;if(this.options.pedantic?(f=2,u=d.trimStart()):T?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,u=d.slice(f),f+=t[1].length),T&&this.rules.other.blankLine.test(g)&&(p+=g+` +`,e=e.substring(g.length+1),c=!0),!c){let Z=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),se=this.rules.other.headingBeginRegex(f),xe=this.rules.other.htmlBeginRegex(f);for(;e;){let G=e.split(` +`,1)[0],C;if(g=G,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),C=g):C=g.replace(this.rules.other.tabCharGlobal," "),ne.test(g)||se.test(g)||xe.test(g)||Z.test(g)||te.test(g))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!g.trim())u+=` +`+C.slice(f);else{if(T||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(d)||se.test(d)||te.test(d))break;u+=` +`+g}!T&&!g.trim()&&(T=!0),p+=G+` +`,e=e.substring(G.length+1),d=C.slice(f)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(o=!0));let y=null,ee;this.options.gfm&&(y=this.rules.other.listIsTask.exec(u),y&&(ee=y[0]!=="[ ] ",u=u.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:p,task:!!y,checked:ee,loose:!1,text:u,tokens:[]}),i.raw+=p}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c=0;cd.type==="space"),u=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=u}if(i.loose)for(let c=0;c({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let r=A(n.slice(0,-1),"\\");if((n.length-r.length)%2===0)return}else{let r=de(t[2],"()");if(r===-2)return;if(r>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let s=t[2],i="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],i=r[3])}else i=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),me(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[s.toLowerCase()];if(!i){let r=n[0].charAt(0);return{type:"text",raw:r,text:r}}return me(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let r=[...s[0]].length-1,o,a,c=r,p=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+r);(s=u.exec(t))!=null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(a=[...o].length,s[3]||s[4]){c+=a;continue}else if((s[5]||s[6])&&r%3&&!((r+a)%3)){p+=a;continue}if(c-=a,c>0)continue;a=Math.min(a,a+c+p);let d=[...s[0]][0].length,g=e.slice(0,r+s.index+d+a);if(Math.min(r,a)%2){let f=g.slice(1,-1);return{type:"em",raw:g,text:f,tokens:this.lexer.inlineTokens(f)}}let T=g.slice(2,-2);return{type:"strong",raw:g,text:T,tokens:this.lexer.inlineTokens(T)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||w,this.options.tokenizer=this.options.tokenizer||new S,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:B.normal,inline:P.normal};this.options.pedantic?(t.block=B.pedantic,t.inline=P.pedantic):this.options.gfm&&(t.block=B.gfm,this.options.breaks?t.inline=P.breaks:t.inline=P.gfm),this.tokenizer.rules=t}static get rules(){return{block:B,inline:P}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(s=r.call({lexer:this},e,t))?(e=e.substring(s.raw.length),t.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let r=t.at(-1);s.raw.length===1&&r!==void 0?r.raw+=` +`:t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=` +`+s.raw,r.text+=` +`+s.text,this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=` +`+s.raw,r.text+=` +`+s.raw,this.inlineQueue.at(-1).src=r.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title});continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let r=1/0,o=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},o),typeof a=="number"&&a>=0&&(r=Math.min(r,a))}),r<1/0&&r>=0&&(i=e.substring(0,r+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let r=t.at(-1);n&&r?.type==="paragraph"?(r.raw+=` +`+s.raw,r.text+=` +`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="text"?(r.raw+=` +`+s.raw,r.text+=` +`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(e){let r="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(r);break}else throw new Error(r)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,s=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,s.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let i=!1,r="";for(;e;){i||(r=""),i=!1;let o;if(this.options.extensions?.inline?.some(c=>(o=c.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let c=t.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,r)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},p),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(r=o.raw.slice(-1)),i=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}};var $=class{options;parser;constructor(e){this.options=e||w}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` +`;return s?'
'+(n?i:R(i,!0))+`
+`:"
"+(n?i:R(i,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o +`+s+" +`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+R(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • +`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let i=0;i${s}`),` + +`+t+` +`+s+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${R(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=V(e);if(i===null)return s;e=i;let r='
    ",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=V(e);if(i===null)return R(n);e=i;let r=`${n}{let o=i[r].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let r=t.renderers[i.name];r?t.renderers[i.name]=function(...o){let a=i.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[i.level];r?r.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new $(this.defaults);for(let r in n.renderer){if(!(r in i))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u||""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new S(this.defaults);for(let r in n.tokenizer){if(!(r in i))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new L;for(let r in n.hooks){if(!(r in i))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],c=i[o];L.passThroughHooks.has(r)?i[o]=p=>{if(this.defaults.async)return Promise.resolve(a.call(i,p)).then(d=>c.call(i,d));let u=a.call(i,p);return c.call(i,u)}:i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),i&&(a=a.concat(i.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=e);let a=r.hooks?r.hooks.provideLexer():e?x.lex:x.lexInline,c=r.hooks?r.hooks.provideParser():e?b.parse:b.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(p=>a(p,r)).then(p=>r.hooks?r.hooks.processAllTokens(p):p).then(p=>r.walkTokens?Promise.all(this.walkTokens(p,r.walkTokens)).then(()=>p):p).then(p=>c(p,r)).then(p=>r.hooks?r.hooks.postprocess(p):p).catch(o);try{r.hooks&&(n=r.hooks.preprocess(n));let p=a(n,r);r.hooks&&(p=r.hooks.processAllTokens(p)),r.walkTokens&&this.walkTokens(p,r.walkTokens);let u=c(p,r);return r.hooks&&(u=r.hooks.postprocess(u)),u}catch(p){return o(p)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+R(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var M=new E;function k(l,e){return M.parse(l,e)}k.options=k.setOptions=function(l){return M.setOptions(l),k.defaults=M.defaults,N(k.defaults),k};k.getDefaults=z;k.defaults=w;k.use=function(...l){return M.use(...l),k.defaults=M.defaults,N(k.defaults),k};k.walkTokens=function(l,e){return M.walkTokens(l,e)};k.parseInline=M.parseInline;k.Parser=b;k.parser=b.parse;k.Renderer=$;k.TextRenderer=_;k.Lexer=x;k.lexer=x.lex;k.Tokenizer=S;k.Hooks=L;k.parse=k;var it=k.options,ot=k.setOptions,lt=k.use,at=k.walkTokens,ct=k.parseInline,pt=k,ut=b.parse,ht=x.lex; + +if(__exports != exports)module.exports = exports;return module.exports})); diff --git a/src/public/vendor/tailwindcss.js b/src/public/vendor/tailwindcss.js new file mode 100644 index 0000000..573c165 --- /dev/null +++ b/src/public/vendor/tailwindcss.js @@ -0,0 +1,83 @@ +(()=>{var qv=Object.create;var Hi=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var Mv=Object.getPrototypeOf,Nv=Object.prototype.hasOwnProperty;var df=r=>Hi(r,"__esModule",{value:!0});var hf=r=>{if(typeof require!="undefined")return require(r);throw new Error('Dynamic require of "'+r+'" is not supported')};var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var x=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ge=(r,e)=>{df(r);for(var t in e)Hi(r,t,{get:e[t],enumerable:!0})},Bv=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lv(e))!Nv.call(r,i)&&i!=="default"&&Hi(r,i,{get:()=>e[i],enumerable:!(t=$v(e,i))||t.enumerable});return r},pe=r=>Bv(df(Hi(r!=null?qv(Mv(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var m,u=P(()=>{m={platform:"",env:{},versions:{node:"14.17.6"}}});var Fv,be,ft=P(()=>{u();Fv=0,be={readFileSync:r=>self[r]||"",statSync:()=>({mtimeMs:Fv++}),promises:{readFile:r=>Promise.resolve(self[r]||"")}}});var Fs=x((oP,gf)=>{u();"use strict";var mf=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||1/0,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[t,i]of e)this.onEviction(t,i.value)}_deleteIfExpired(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,t.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,t){if(this._deleteIfExpired(e,t)===!1)return t.value}_getItemValue(e,t){return t.expiry?this._getOrDeleteIfExpired(e,t):t.value}_peek(e,t){let i=t.get(e);return this._getItemValue(e,i)}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,t){this.oldCache.delete(e),this._set(e,t)}*_entriesAscending(){for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield e)}for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let t=this.cache.get(e);return this._getItemValue(e,t)}if(this.oldCache.has(e)){let t=this.oldCache.get(e);if(this._deleteIfExpired(e,t)===!1)return this._moveToRecent(e,t),t.value}}set(e,t,{maxAge:i=this.maxAge===1/0?void 0:Date.now()+this.maxAge}={}){this.cache.has(e)?this.cache.set(e,{value:t,maxAge:i}):this._set(e,{value:t,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this._entriesAscending()],i=t.length-e;i<0?(this.cache=new Map(t),this.oldCache=new Map,this._size=t.length):(i>0&&this._emitEvictions(t.slice(0,i)),this.oldCache=new Map(t.slice(i)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}}*entriesDescending(){let e=[...this.cache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}e=[...this.oldCache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this.cache.has(n)||this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}}*entriesAscending(){for(let[e,t]of this._entriesAscending())yield[e,t.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};gf.exports=mf});var yf,bf=P(()=>{u();yf=r=>r&&r._hash});function Wi(r){return yf(r,{ignoreUnknown:!0})}var wf=P(()=>{u();bf()});function xt(r){if(r=`${r}`,r==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(r))return r.replace(/^[+-]?/,t=>t==="-"?"":"-");let e=["var","calc","min","max","clamp"];for(let t of e)if(r.includes(`${t}(`))return`calc(${r} * -1)`}var Gi=P(()=>{u()});var vf,xf=P(()=>{u();vf=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","size","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","captionSide","borderCollapse","borderSpacing","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","listStyleImage","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","hyphens","whitespace","textWrap","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","textDecorationStyle","textDecorationThickness","textUnderlineOffset","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","contain","content","forcedColorAdjust"]});function kf(r,e){return r===void 0?e:Array.isArray(r)?r:[...new Set(e.filter(i=>r!==!1&&r[i]!==!1).concat(Object.keys(r).filter(i=>r[i]!==!1)))]}var Sf=P(()=>{u()});var Af={};Ge(Af,{default:()=>Qe});var Qe,Qi=P(()=>{u();Qe=new Proxy({},{get:()=>String})});function js(r,e,t){typeof m!="undefined"&&m.env.JEST_WORKER_ID||t&&Cf.has(t)||(t&&Cf.add(t),console.warn(""),e.forEach(i=>console.warn(r,"-",i)))}function zs(r){return Qe.dim(r)}var Cf,G,Be=P(()=>{u();Qi();Cf=new Set;G={info(r,e){js(Qe.bold(Qe.cyan("info")),...Array.isArray(r)?[r]:[e,r])},warn(r,e){["content-problems"].includes(r)||js(Qe.bold(Qe.yellow("warn")),...Array.isArray(r)?[r]:[e,r])},risk(r,e){js(Qe.bold(Qe.magenta("risk")),...Array.isArray(r)?[r]:[e,r])}}});var _f={};Ge(_f,{default:()=>Us});function qr({version:r,from:e,to:t}){G.warn(`${e}-color-renamed`,[`As of Tailwind CSS ${r}, \`${e}\` has been renamed to \`${t}\`.`,"Update your configuration file to silence this warning."])}var Us,Vs=P(()=>{u();Be();Us={inherit:"inherit",current:"currentColor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"#f8fafc",100:"#f1f5f9",200:"#e2e8f0",300:"#cbd5e1",400:"#94a3b8",500:"#64748b",600:"#475569",700:"#334155",800:"#1e293b",900:"#0f172a",950:"#020617"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},zinc:{50:"#fafafa",100:"#f4f4f5",200:"#e4e4e7",300:"#d4d4d8",400:"#a1a1aa",500:"#71717a",600:"#52525b",700:"#3f3f46",800:"#27272a",900:"#18181b",950:"#09090b"},neutral:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},stone:{50:"#fafaf9",100:"#f5f5f4",200:"#e7e5e4",300:"#d6d3d1",400:"#a8a29e",500:"#78716c",600:"#57534e",700:"#44403c",800:"#292524",900:"#1c1917",950:"#0c0a09"},red:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d",950:"#450a0a"},orange:{50:"#fff7ed",100:"#ffedd5",200:"#fed7aa",300:"#fdba74",400:"#fb923c",500:"#f97316",600:"#ea580c",700:"#c2410c",800:"#9a3412",900:"#7c2d12",950:"#431407"},amber:{50:"#fffbeb",100:"#fef3c7",200:"#fde68a",300:"#fcd34d",400:"#fbbf24",500:"#f59e0b",600:"#d97706",700:"#b45309",800:"#92400e",900:"#78350f",950:"#451a03"},yellow:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12",950:"#422006"},lime:{50:"#f7fee7",100:"#ecfccb",200:"#d9f99d",300:"#bef264",400:"#a3e635",500:"#84cc16",600:"#65a30d",700:"#4d7c0f",800:"#3f6212",900:"#365314",950:"#1a2e05"},green:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d",950:"#052e16"},emerald:{50:"#ecfdf5",100:"#d1fae5",200:"#a7f3d0",300:"#6ee7b7",400:"#34d399",500:"#10b981",600:"#059669",700:"#047857",800:"#065f46",900:"#064e3b",950:"#022c22"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"},cyan:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},sky:{50:"#f0f9ff",100:"#e0f2fe",200:"#bae6fd",300:"#7dd3fc",400:"#38bdf8",500:"#0ea5e9",600:"#0284c7",700:"#0369a1",800:"#075985",900:"#0c4a6e",950:"#082f49"},blue:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},indigo:{50:"#eef2ff",100:"#e0e7ff",200:"#c7d2fe",300:"#a5b4fc",400:"#818cf8",500:"#6366f1",600:"#4f46e5",700:"#4338ca",800:"#3730a3",900:"#312e81",950:"#1e1b4b"},violet:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},fuchsia:{50:"#fdf4ff",100:"#fae8ff",200:"#f5d0fe",300:"#f0abfc",400:"#e879f9",500:"#d946ef",600:"#c026d3",700:"#a21caf",800:"#86198f",900:"#701a75",950:"#4a044e"},pink:{50:"#fdf2f8",100:"#fce7f3",200:"#fbcfe8",300:"#f9a8d4",400:"#f472b6",500:"#ec4899",600:"#db2777",700:"#be185d",800:"#9d174d",900:"#831843",950:"#500724"},rose:{50:"#fff1f2",100:"#ffe4e6",200:"#fecdd3",300:"#fda4af",400:"#fb7185",500:"#f43f5e",600:"#e11d48",700:"#be123c",800:"#9f1239",900:"#881337",950:"#4c0519"},get lightBlue(){return qr({version:"v2.2",from:"lightBlue",to:"sky"}),this.sky},get warmGray(){return qr({version:"v3.0",from:"warmGray",to:"stone"}),this.stone},get trueGray(){return qr({version:"v3.0",from:"trueGray",to:"neutral"}),this.neutral},get coolGray(){return qr({version:"v3.0",from:"coolGray",to:"gray"}),this.gray},get blueGray(){return qr({version:"v3.0",from:"blueGray",to:"slate"}),this.slate}}});function Hs(r,...e){for(let t of e){for(let i in t)r?.hasOwnProperty?.(i)||(r[i]=t[i]);for(let i of Object.getOwnPropertySymbols(t))r?.hasOwnProperty?.(i)||(r[i]=t[i])}return r}var Ef=P(()=>{u()});function kt(r){if(Array.isArray(r))return r;let e=r.split("[").length-1,t=r.split("]").length-1;if(e!==t)throw new Error(`Path is invalid. Has unbalanced brackets: ${r}`);return r.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean)}var Yi=P(()=>{u()});function we(r,e){return Ki.future.includes(e)?r.future==="all"||(r?.future?.[e]??Of[e]??!1):Ki.experimental.includes(e)?r.experimental==="all"||(r?.experimental?.[e]??Of[e]??!1):!1}function Tf(r){return r.experimental==="all"?Ki.experimental:Object.keys(r?.experimental??{}).filter(e=>Ki.experimental.includes(e)&&r.experimental[e])}function Rf(r){if(m.env.JEST_WORKER_ID===void 0&&Tf(r).length>0){let e=Tf(r).map(t=>Qe.yellow(t)).join(", ");G.warn("experimental-flags-enabled",[`You have enabled experimental features: ${e}`,"Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time."])}}var Of,Ki,ct=P(()=>{u();Qi();Be();Of={optimizeUniversalDefaults:!1,generalizedModifiers:!0,disableColorOpacityUtilitiesByDefault:!1,relativeContentPathsByDefault:!1},Ki={future:["hoverOnlyWhenSupported","respectDefaultRingColorOpacity","disableColorOpacityUtilitiesByDefault","relativeContentPathsByDefault"],experimental:["optimizeUniversalDefaults","generalizedModifiers"]}});function Pf(r){(()=>{if(r.purge||!r.content||!Array.isArray(r.content)&&!(typeof r.content=="object"&&r.content!==null))return!1;if(Array.isArray(r.content))return r.content.every(t=>typeof t=="string"?!0:!(typeof t?.raw!="string"||t?.extension&&typeof t?.extension!="string"));if(typeof r.content=="object"&&r.content!==null){if(Object.keys(r.content).some(t=>!["files","relative","extract","transform"].includes(t)))return!1;if(Array.isArray(r.content.files)){if(!r.content.files.every(t=>typeof t=="string"?!0:!(typeof t?.raw!="string"||t?.extension&&typeof t?.extension!="string")))return!1;if(typeof r.content.extract=="object"){for(let t of Object.values(r.content.extract))if(typeof t!="function")return!1}else if(!(r.content.extract===void 0||typeof r.content.extract=="function"))return!1;if(typeof r.content.transform=="object"){for(let t of Object.values(r.content.transform))if(typeof t!="function")return!1}else if(!(r.content.transform===void 0||typeof r.content.transform=="function"))return!1;if(typeof r.content.relative!="boolean"&&typeof r.content.relative!="undefined")return!1}return!0}return!1})()||G.warn("purge-deprecation",["The `purge`/`content` options have changed in Tailwind CSS v3.0.","Update your configuration file to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#configure-content-sources"]),r.safelist=(()=>{let{content:t,purge:i,safelist:n}=r;return Array.isArray(n)?n:Array.isArray(t?.safelist)?t.safelist:Array.isArray(i?.safelist)?i.safelist:Array.isArray(i?.options?.safelist)?i.options.safelist:[]})(),r.blocklist=(()=>{let{blocklist:t}=r;if(Array.isArray(t)){if(t.every(i=>typeof i=="string"))return t;G.warn("blocklist-invalid",["The `blocklist` option must be an array of strings.","https://tailwindcss.com/docs/content-configuration#discarding-classes"])}return[]})(),typeof r.prefix=="function"?(G.warn("prefix-function",["As of Tailwind CSS v3.0, `prefix` cannot be a function.","Update `prefix` in your configuration to be a string to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#prefix-cannot-be-a-function"]),r.prefix=""):r.prefix=r.prefix??"",r.content={relative:(()=>{let{content:t}=r;return t?.relative?t.relative:we(r,"relativeContentPathsByDefault")})(),files:(()=>{let{content:t,purge:i}=r;return Array.isArray(i)?i:Array.isArray(i?.content)?i.content:Array.isArray(t)?t:Array.isArray(t?.content)?t.content:Array.isArray(t?.files)?t.files:[]})(),extract:(()=>{let t=(()=>r.purge?.extract?r.purge.extract:r.content?.extract?r.content.extract:r.purge?.extract?.DEFAULT?r.purge.extract.DEFAULT:r.content?.extract?.DEFAULT?r.content.extract.DEFAULT:r.purge?.options?.extractors?r.purge.options.extractors:r.content?.options?.extractors?r.content.options.extractors:{})(),i={},n=(()=>{if(r.purge?.options?.defaultExtractor)return r.purge.options.defaultExtractor;if(r.content?.options?.defaultExtractor)return r.content.options.defaultExtractor})();if(n!==void 0&&(i.DEFAULT=n),typeof t=="function")i.DEFAULT=t;else if(Array.isArray(t))for(let{extensions:s,extractor:a}of t??[])for(let o of s)i[o]=a;else typeof t=="object"&&t!==null&&Object.assign(i,t);return i})(),transform:(()=>{let t=(()=>r.purge?.transform?r.purge.transform:r.content?.transform?r.content.transform:r.purge?.transform?.DEFAULT?r.purge.transform.DEFAULT:r.content?.transform?.DEFAULT?r.content.transform.DEFAULT:{})(),i={};return typeof t=="function"?i.DEFAULT=t:typeof t=="object"&&t!==null&&Object.assign(i,t),i})()};for(let t of r.content.files)if(typeof t=="string"&&/{([^,]*?)}/g.test(t)){G.warn("invalid-glob-braces",[`The glob pattern ${zs(t)} in your Tailwind CSS configuration is invalid.`,`Update it to ${zs(t.replace(/{([^,]*?)}/g,"$1"))} to silence this warning.`]);break}return r}var If=P(()=>{u();ct();Be()});function ke(r){if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||Object.getPrototypeOf(e)===null}var Kt=P(()=>{u()});function St(r){return Array.isArray(r)?r.map(e=>St(e)):typeof r=="object"&&r!==null?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,St(t)])):r}var Xi=P(()=>{u()});function jt(r){return r.replace(/\\,/g,"\\2c ")}var Zi=P(()=>{u()});var Ws,Df=P(()=>{u();Ws={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});function $r(r,{loose:e=!1}={}){if(typeof r!="string")return null;if(r=r.trim(),r==="transparent")return{mode:"rgb",color:["0","0","0"],alpha:"0"};if(r in Ws)return{mode:"rgb",color:Ws[r].map(s=>s.toString())};let t=r.replace(zv,(s,a,o,l,c)=>["#",a,a,o,o,l,l,c?c+c:""].join("")).match(jv);if(t!==null)return{mode:"rgb",color:[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)].map(s=>s.toString()),alpha:t[4]?(parseInt(t[4],16)/255).toString():void 0};let i=r.match(Uv)??r.match(Vv);if(i===null)return null;let n=[i[2],i[3],i[4]].filter(Boolean).map(s=>s.toString());return n.length===2&&n[0].startsWith("var(")?{mode:i[1],color:[n[0]],alpha:n[1]}:!e&&n.length!==3||n.length<3&&!n.some(s=>/^var\(.*?\)$/.test(s))?null:{mode:i[1],color:n,alpha:i[5]?.toString?.()}}function Gs({mode:r,color:e,alpha:t}){let i=t!==void 0;return r==="rgba"||r==="hsla"?`${r}(${e.join(", ")}${i?`, ${t}`:""})`:`${r}(${e.join(" ")}${i?` / ${t}`:""})`}var jv,zv,At,Ji,qf,Ct,Uv,Vv,Qs=P(()=>{u();Df();jv=/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,zv=/^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i,At=/(?:\d+|\d*\.\d+)%?/,Ji=/(?:\s*,\s*|\s+)/,qf=/\s*[,/]\s*/,Ct=/var\(--(?:[^ )]*?)(?:,(?:[^ )]*?|var\(--[^ )]*?\)))?\)/,Uv=new RegExp(`^(rgba?)\\(\\s*(${At.source}|${Ct.source})(?:${Ji.source}(${At.source}|${Ct.source}))?(?:${Ji.source}(${At.source}|${Ct.source}))?(?:${qf.source}(${At.source}|${Ct.source}))?\\s*\\)$`),Vv=new RegExp(`^(hsla?)\\(\\s*((?:${At.source})(?:deg|rad|grad|turn)?|${Ct.source})(?:${Ji.source}(${At.source}|${Ct.source}))?(?:${Ji.source}(${At.source}|${Ct.source}))?(?:${qf.source}(${At.source}|${Ct.source}))?\\s*\\)$`)});function Je(r,e,t){if(typeof r=="function")return r({opacityValue:e});let i=$r(r,{loose:!0});return i===null?t:Gs({...i,alpha:e})}function Ae({color:r,property:e,variable:t}){let i=[].concat(e);if(typeof r=="function")return{[t]:"1",...Object.fromEntries(i.map(s=>[s,r({opacityVariable:t,opacityValue:`var(${t}, 1)`})]))};let n=$r(r);return n===null?Object.fromEntries(i.map(s=>[s,r])):n.alpha!==void 0?Object.fromEntries(i.map(s=>[s,r])):{[t]:"1",...Object.fromEntries(i.map(s=>[s,Gs({...n,alpha:`var(${t}, 1)`})]))}}var Lr=P(()=>{u();Qs()});function ve(r,e){let t=[],i=[],n=0,s=!1;for(let a=0;a{u()});function en(r){return ve(r,",").map(t=>{let i=t.trim(),n={raw:i},s=i.split(Wv),a=new Set;for(let o of s)$f.lastIndex=0,!a.has("KEYWORD")&&Hv.has(o)?(n.keyword=o,a.add("KEYWORD")):$f.test(o)?a.has("X")?a.has("Y")?a.has("BLUR")?a.has("SPREAD")||(n.spread=o,a.add("SPREAD")):(n.blur=o,a.add("BLUR")):(n.y=o,a.add("Y")):(n.x=o,a.add("X")):n.color?(n.unknown||(n.unknown=[]),n.unknown.push(o)):n.color=o;return n.valid=n.x!==void 0&&n.y!==void 0,n})}function Lf(r){return r.map(e=>e.valid?[e.keyword,e.x,e.y,e.blur,e.spread,e.color].filter(Boolean).join(" "):e.raw).join(", ")}var Hv,Wv,$f,Ys=P(()=>{u();zt();Hv=new Set(["inset","inherit","initial","revert","unset"]),Wv=/\ +(?![^(]*\))/g,$f=/^-?(\d+|\.\d+)(.*?)$/g});function Ks(r){return Gv.some(e=>new RegExp(`^${e}\\(.*\\)`).test(r))}function K(r,e=null,t=!0){let i=e&&Qv.has(e.property);return r.startsWith("--")&&!i?`var(${r})`:r.includes("url(")?r.split(/(url\(.*?\))/g).filter(Boolean).map(n=>/^url\(.*?\)$/.test(n)?n:K(n,e,!1)).join(""):(r=r.replace(/([^\\])_+/g,(n,s)=>s+" ".repeat(n.length-1)).replace(/^_/g," ").replace(/\\_/g,"_"),t&&(r=r.trim()),r=Yv(r),r)}function Ye(r){return r.includes("=")&&(r=r.replace(/(=.*)/g,(e,t)=>{if(t[1]==="'"||t[1]==='"')return t;if(t.length>2){let i=t[t.length-1];if(t[t.length-2]===" "&&(i==="i"||i==="I"||i==="s"||i==="S"))return`="${t.slice(1,-2)}" ${t[t.length-1]}`}return`="${t.slice(1)}"`})),r}function Yv(r){let e=["theme"],t=["min-content","max-content","fit-content","safe-area-inset-top","safe-area-inset-right","safe-area-inset-bottom","safe-area-inset-left","titlebar-area-x","titlebar-area-y","titlebar-area-width","titlebar-area-height","keyboard-inset-top","keyboard-inset-right","keyboard-inset-bottom","keyboard-inset-left","keyboard-inset-width","keyboard-inset-height","radial-gradient","linear-gradient","conic-gradient","repeating-radial-gradient","repeating-linear-gradient","repeating-conic-gradient","anchor-size"];return r.replace(/(calc|min|max|clamp)\(.+\)/g,i=>{let n="";function s(){let a=n.trimEnd();return a[a.length-1]}for(let a=0;ai[a+p]===d)},l=function(f){let d=1/0;for(let h of f){let b=i.indexOf(h,a);b!==-1&&bo(f))){let f=t.find(d=>o(d));n+=f,a+=f.length-1}else e.some(f=>o(f))?n+=l([")"]):o("[")?n+=l(["]"]):["+","-","*","/"].includes(c)&&!["(","+","-","*","/",","].includes(s())?n+=` ${c} `:n+=c}return n.replace(/\s+/g," ")})}function Xs(r){return r.startsWith("url(")}function Zs(r){return!isNaN(Number(r))||Ks(r)}function Mr(r){return r.endsWith("%")&&Zs(r.slice(0,-1))||Ks(r)}function Nr(r){return r==="0"||new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${Xv}$`).test(r)||Ks(r)}function Mf(r){return Zv.has(r)}function Nf(r){let e=en(K(r));for(let t of e)if(!t.valid)return!1;return!0}function Bf(r){let e=0;return ve(r,"_").every(i=>(i=K(i),i.startsWith("var(")?!0:$r(i,{loose:!0})!==null?(e++,!0):!1))?e>0:!1}function Ff(r){let e=0;return ve(r,",").every(i=>(i=K(i),i.startsWith("var(")?!0:Xs(i)||ex(i)||["element(","image(","cross-fade(","image-set("].some(n=>i.startsWith(n))?(e++,!0):!1))?e>0:!1}function ex(r){r=K(r);for(let e of Jv)if(r.startsWith(`${e}(`))return!0;return!1}function jf(r){let e=0;return ve(r,"_").every(i=>(i=K(i),i.startsWith("var(")?!0:tx.has(i)||Nr(i)||Mr(i)?(e++,!0):!1))?e>0:!1}function zf(r){let e=0;return ve(r,",").every(i=>(i=K(i),i.startsWith("var(")?!0:i.includes(" ")&&!/(['"])([^"']+)\1/g.test(i)||/^\d/g.test(i)?!1:(e++,!0)))?e>0:!1}function Uf(r){return rx.has(r)}function Vf(r){return ix.has(r)}function Hf(r){return nx.has(r)}var Gv,Qv,Kv,Xv,Zv,Jv,tx,rx,ix,nx,Br=P(()=>{u();Qs();Ys();zt();Gv=["min","max","clamp","calc"];Qv=new Set(["scroll-timeline-name","timeline-scope","view-timeline-name","font-palette","anchor-name","anchor-scope","position-anchor","position-try-options","scroll-timeline","animation-timeline","view-timeline","position-try"]);Kv=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],Xv=`(?:${Kv.join("|")})`;Zv=new Set(["thin","medium","thick"]);Jv=new Set(["conic-gradient","linear-gradient","radial-gradient","repeating-conic-gradient","repeating-linear-gradient","repeating-radial-gradient"]);tx=new Set(["center","top","right","bottom","left"]);rx=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]);ix=new Set(["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large"]);nx=new Set(["larger","smaller"])});function Wf(r){let e=["cover","contain"];return ve(r,",").every(t=>{let i=ve(t,"_").filter(Boolean);return i.length===1&&e.includes(i[0])?!0:i.length!==1&&i.length!==2?!1:i.every(n=>Nr(n)||Mr(n)||n==="auto")})}var Gf=P(()=>{u();Br();zt()});function Qf(r,e){r.walkClasses(t=>{t.value=e(t.value),t.raws&&t.raws.value&&(t.raws.value=jt(t.raws.value))})}function Yf(r,e){if(!_t(r))return;let t=r.slice(1,-1);if(!!e(t))return K(t)}function sx(r,e={},t){let i=e[r];if(i!==void 0)return xt(i);if(_t(r)){let n=Yf(r,t);return n===void 0?void 0:xt(n)}}function tn(r,e={},{validate:t=()=>!0}={}){let i=e.values?.[r];return i!==void 0?i:e.supportsNegativeValues&&r.startsWith("-")?sx(r.slice(1),e.values,t):Yf(r,t)}function _t(r){return r.startsWith("[")&&r.endsWith("]")}function Kf(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("[",e),i=r.indexOf("]",e);return r[e-1]==="]"||r[e+1]==="["||t!==-1&&i!==-1&&t")){let e=r;return({opacityValue:t=1})=>e.replace(//g,t)}return r}function Xf(r){return K(r.slice(1,-1))}function ax(r,e={},{tailwindConfig:t={}}={}){if(e.values?.[r]!==void 0)return Xt(e.values?.[r]);let[i,n]=Kf(r);if(n!==void 0){let s=e.values?.[i]??(_t(i)?i.slice(1,-1):void 0);return s===void 0?void 0:(s=Xt(s),_t(n)?Je(s,Xf(n)):t.theme?.opacity?.[n]===void 0?void 0:Je(s,t.theme.opacity[n]))}return tn(r,e,{validate:Bf})}function ox(r,e={}){return e.values?.[r]}function qe(r){return(e,t)=>tn(e,t,{validate:r})}function lx(r,e){let t=r.indexOf(e);return t===-1?[void 0,r]:[r.slice(0,t),r.slice(t+1)]}function ea(r,e,t,i){if(t.values&&e in t.values)for(let{type:s}of r??[]){let a=Js[s](e,t,{tailwindConfig:i});if(a!==void 0)return[a,s,null]}if(_t(e)){let s=e.slice(1,-1),[a,o]=lx(s,":");if(!/^[\w-_]+$/g.test(a))o=s;else if(a!==void 0&&!Zf.includes(a))return[];if(o.length>0&&Zf.includes(a))return[tn(`[${o}]`,t),a,null]}let n=ta(r,e,t,i);for(let s of n)return s;return[]}function*ta(r,e,t,i){let n=we(i,"generalizedModifiers"),[s,a]=Kf(e);if(n&&t.modifiers!=null&&(t.modifiers==="any"||typeof t.modifiers=="object"&&(a&&_t(a)||a in t.modifiers))||(s=e,a=void 0),a!==void 0&&s===""&&(s="DEFAULT"),a!==void 0&&typeof t.modifiers=="object"){let l=t.modifiers?.[a]??null;l!==null?a=l:_t(a)&&(a=Xf(a))}for(let{type:l}of r??[]){let c=Js[l](s,t,{tailwindConfig:i});c!==void 0&&(yield[c,l,a??null])}}var Js,Zf,Fr=P(()=>{u();Zi();Lr();Br();Gi();Gf();ct();Js={any:tn,color:ax,url:qe(Xs),image:qe(Ff),length:qe(Nr),percentage:qe(Mr),position:qe(jf),lookup:ox,"generic-name":qe(Uf),"family-name":qe(zf),number:qe(Zs),"line-width":qe(Mf),"absolute-size":qe(Vf),"relative-size":qe(Hf),shadow:qe(Nf),size:qe(Wf)},Zf=Object.keys(Js)});function X(r){return typeof r=="function"?r({}):r}var ra=P(()=>{u()});function Zt(r){return typeof r=="function"}function jr(r,...e){let t=e.pop();for(let i of e)for(let n in i){let s=t(r[n],i[n]);s===void 0?ke(r[n])&&ke(i[n])?r[n]=jr({},r[n],i[n],t):r[n]=i[n]:r[n]=s}return r}function ux(r,...e){return Zt(r)?r(...e):r}function fx(r){return r.reduce((e,{extend:t})=>jr(e,t,(i,n)=>i===void 0?[n]:Array.isArray(i)?[n,...i]:[n,i]),{})}function cx(r){return{...r.reduce((e,t)=>Hs(e,t),{}),extend:fx(r)}}function Jf(r,e){if(Array.isArray(r)&&ke(r[0]))return r.concat(e);if(Array.isArray(e)&&ke(e[0])&&ke(r))return[r,...e];if(Array.isArray(e))return e}function px({extend:r,...e}){return jr(e,r,(t,i)=>!Zt(t)&&!i.some(Zt)?jr({},t,...i,Jf):(n,s)=>jr({},...[t,...i].map(a=>ux(a,n,s)),Jf))}function*dx(r){let e=kt(r);if(e.length===0||(yield e,Array.isArray(r)))return;let t=/^(.*?)\s*\/\s*([^/]+)$/,i=r.match(t);if(i!==null){let[,n,s]=i,a=kt(n);a.alpha=s,yield a}}function hx(r){let e=(t,i)=>{for(let n of dx(t)){let s=0,a=r;for(;a!=null&&s(t[i]=Zt(r[i])?r[i](e,ia):r[i],t),{})}function ec(r){let e=[];return r.forEach(t=>{e=[...e,t];let i=t?.plugins??[];i.length!==0&&i.forEach(n=>{n.__isOptionsFunction&&(n=n()),e=[...e,...ec([n?.config??{}])]})}),e}function mx(r){return[...r].reduceRight((t,i)=>Zt(i)?i({corePlugins:t}):kf(i,t),vf)}function gx(r){return[...r].reduceRight((t,i)=>[...t,...i],[])}function na(r){let e=[...ec(r),{prefix:"",important:!1,separator:":"}];return Pf(Hs({theme:hx(px(cx(e.map(t=>t?.theme??{})))),corePlugins:mx(e.map(t=>t.corePlugins)),plugins:gx(r.map(t=>t?.plugins??[]))},...e))}var ia,tc=P(()=>{u();Gi();xf();Sf();Vs();Ef();Yi();If();Kt();Xi();Fr();Lr();ra();ia={colors:Us,negative(r){return Object.keys(r).filter(e=>r[e]!=="0").reduce((e,t)=>{let i=xt(r[t]);return i!==void 0&&(e[`-${t}`]=i),e},{})},breakpoints(r){return Object.keys(r).filter(e=>typeof r[e]=="string").reduce((e,t)=>({...e,[`screen-${t}`]:r[t]}),{})}}});var rn=x((f3,rc)=>{u();rc.exports={content:[],presets:[],darkMode:"media",theme:{accentColor:({theme:r})=>({...r("colors"),auto:"auto"}),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9"},backdropBlur:({theme:r})=>r("blur"),backdropBrightness:({theme:r})=>r("brightness"),backdropContrast:({theme:r})=>r("contrast"),backdropGrayscale:({theme:r})=>r("grayscale"),backdropHueRotate:({theme:r})=>r("hueRotate"),backdropInvert:({theme:r})=>r("invert"),backdropOpacity:({theme:r})=>r("opacity"),backdropSaturate:({theme:r})=>r("saturate"),backdropSepia:({theme:r})=>r("sepia"),backgroundColor:({theme:r})=>r("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:r})=>r("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:r})=>({...r("colors"),DEFAULT:r("colors.gray.200","currentColor")}),borderOpacity:({theme:r})=>r("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:r})=>({...r("spacing")}),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px"},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:r})=>r("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2"},caretColor:({theme:r})=>r("colors"),colors:({colors:r})=>({inherit:r.inherit,current:r.current,transparent:r.transparent,black:r.black,white:r.white,slate:r.slate,gray:r.gray,zinc:r.zinc,neutral:r.neutral,stone:r.stone,red:r.red,orange:r.orange,amber:r.amber,yellow:r.yellow,lime:r.lime,green:r.green,emerald:r.emerald,teal:r.teal,cyan:r.cyan,sky:r.sky,blue:r.blue,indigo:r.indigo,violet:r.violet,purple:r.purple,fuchsia:r.fuchsia,pink:r.pink,rose:r.rose}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem"},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2"},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:r})=>r("borderColor"),divideOpacity:({theme:r})=>r("borderOpacity"),divideWidth:({theme:r})=>r("borderWidth"),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:r})=>({none:"none",...r("colors")}),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:r})=>({auto:"auto",...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%"}),flexGrow:{0:"0",DEFAULT:"1"},flexShrink:{0:"0",DEFAULT:"1"},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:r})=>r("spacing"),gradientColorStops:({theme:r})=>r("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%"},grayscale:{0:"0",DEFAULT:"100%"},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},height:({theme:r})=>({auto:"auto",...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg"},inset:({theme:r})=>({auto:"auto",...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),invert:{0:"0",DEFAULT:"100%"},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:r})=>({auto:"auto",...r("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"},maxHeight:({theme:r})=>({...r("spacing"),none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),maxWidth:({theme:r,breakpoints:e})=>({...r("spacing"),none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e(r("screens"))}),minHeight:({theme:r})=>({...r("spacing"),full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),minWidth:({theme:r})=>({...r("spacing"),full:"100%",min:"min-content",max:"max-content",fit:"fit-content"}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1"},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12"},outlineColor:({theme:r})=>r("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},padding:({theme:r})=>r("spacing"),placeholderColor:({theme:r})=>r("colors"),placeholderOpacity:({theme:r})=>r("opacity"),ringColor:({theme:r})=>({DEFAULT:r("colors.blue.500","#3b82f6"),...r("colors")}),ringOffsetColor:({theme:r})=>r("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},ringOpacity:({theme:r})=>({DEFAULT:"0.5",...r("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg"},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2"},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5"},screens:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},scrollMargin:({theme:r})=>({...r("spacing")}),scrollPadding:({theme:r})=>r("spacing"),sepia:{0:"0",DEFAULT:"100%"},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg"},space:({theme:r})=>({...r("spacing")}),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:r})=>({none:"none",...r("colors")}),strokeWidth:{0:"0",1:"1",2:"2"},supports:{},data:{},textColor:({theme:r})=>r("colors"),textDecorationColor:({theme:r})=>r("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},textIndent:({theme:r})=>({...r("spacing")}),textOpacity:({theme:r})=>r("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:r})=>({...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),size:({theme:r})=>({auto:"auto",...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content"}),width:({theme:r})=>({auto:"auto",...r("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content"}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50"}},plugins:[]}});function nn(r){let e=(r?.presets??[ic.default]).slice().reverse().flatMap(n=>nn(n instanceof Function?n():n)),t={respectDefaultRingColorOpacity:{theme:{ringColor:({theme:n})=>({DEFAULT:"#3b82f67f",...n("colors")})}},disableColorOpacityUtilitiesByDefault:{corePlugins:{backgroundOpacity:!1,borderOpacity:!1,divideOpacity:!1,placeholderOpacity:!1,ringOpacity:!1,textOpacity:!1}}},i=Object.keys(t).filter(n=>we(r,n)).map(n=>t[n]);return[r,...i,...e]}var ic,nc=P(()=>{u();ic=pe(rn());ct()});var sc={};Ge(sc,{default:()=>zr});function zr(...r){let[,...e]=nn(r[0]);return na([...r,...e])}var sa=P(()=>{u();tc();nc()});var Ur={};Ge(Ur,{default:()=>me});var me,et=P(()=>{u();me={resolve:r=>r,extname:r=>"."+r.split(".").pop()}});function sn(r){return typeof r=="object"&&r!==null}function bx(r){return Object.keys(r).length===0}function ac(r){return typeof r=="string"||r instanceof String}function aa(r){return sn(r)&&r.config===void 0&&!bx(r)?null:sn(r)&&r.config!==void 0&&ac(r.config)?me.resolve(r.config):sn(r)&&r.config!==void 0&&sn(r.config)?null:ac(r)?me.resolve(r):wx()}function wx(){for(let r of yx)try{let e=me.resolve(r);return be.accessSync(e),e}catch(e){}return null}var yx,oc=P(()=>{u();ft();et();yx=["./tailwind.config.js","./tailwind.config.cjs","./tailwind.config.mjs","./tailwind.config.ts","./tailwind.config.cts","./tailwind.config.mts"]});var lc={};Ge(lc,{default:()=>oa});var oa,la=P(()=>{u();oa={parse:r=>({href:r})}});var ua=x(()=>{u()});var an=x((v3,cc)=>{u();"use strict";var uc=(Qi(),Af),fc=ua(),Jt=class extends Error{constructor(e,t,i,n,s,a){super(e);this.name="CssSyntaxError",this.reason=e,s&&(this.file=s),n&&(this.source=n),a&&(this.plugin=a),typeof t!="undefined"&&typeof i!="undefined"&&(typeof t=="number"?(this.line=t,this.column=i):(this.line=t.line,this.column=t.column,this.endLine=i.line,this.endColumn=i.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,Jt)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",typeof this.line!="undefined"&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;e==null&&(e=uc.isColorSupported);let i=f=>f,n=f=>f,s=f=>f;if(e){let{bold:f,gray:d,red:p}=uc.createColors(!0);n=h=>f(p(h)),i=h=>d(h),fc&&(s=h=>fc(h))}let a=t.split(/\r?\n/),o=Math.max(this.line-3,0),l=Math.min(this.line+2,a.length),c=String(l).length;return a.slice(o,l).map((f,d)=>{let p=o+1+d,h=" "+(" "+p).slice(-c)+" | ";if(p===this.line){if(f.length>160){let v=20,y=Math.max(0,this.column-v),w=Math.max(this.column+v,this.endColumn+v),k=f.slice(y,w),S=i(h.replace(/\d/g," "))+f.slice(0,Math.min(this.column-1,v-1)).replace(/[^\t]/g," ");return n(">")+i(h)+s(k)+` + `+S+n("^")}let b=i(h.replace(/\d/g," "))+f.slice(0,this.column-1).replace(/[^\t]/g," ");return n(">")+i(h)+s(f)+` + `+b+n("^")}return" "+i(h)+s(f)}).join(` +`)}toString(){let e=this.showSourceCode();return e&&(e=` + +`+e+` +`),this.name+": "+this.message+e}};cc.exports=Jt;Jt.default=Jt});var fa=x((x3,dc)=>{u();"use strict";var pc={after:` +`,beforeClose:` +`,beforeComment:` +`,beforeDecl:` +`,beforeOpen:" ",beforeRule:` +`,colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};function vx(r){return r[0].toUpperCase()+r.slice(1)}var on=class{constructor(e){this.builder=e}atrule(e,t){let i="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(typeof e.raws.afterName!="undefined"?i+=e.raws.afterName:n&&(i+=" "),e.nodes)this.block(e,i+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(i+n+s,e)}}beforeAfter(e,t){let i;e.type==="decl"?i=this.raw(e,null,"beforeDecl"):e.type==="comment"?i=this.raw(e,null,"beforeComment"):t==="before"?i=this.raw(e,null,"beforeRule"):i=this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&n.type!=="root";)s+=1,n=n.parent;if(i.includes(` +`)){let a=this.raw(e,null,"indent");if(a.length)for(let o=0;o0&&e.nodes[t].type==="comment";)t-=1;let i=this.raw(e,"semicolon");for(let n=0;n{if(n=l.raws[t],typeof n!="undefined")return!1})}return typeof n=="undefined"&&(n=pc[i]),a.rawCache[i]=n,n}rawBeforeClose(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length>0&&typeof i.raws.after!="undefined")return t=i.raws.after,t.includes(` +`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let i;return e.walkComments(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(` +`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeDecl"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeDecl(e,t){let i;return e.walkDecls(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(` +`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeRule"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeOpen(e){let t;return e.walk(i=>{if(i.type!=="decl"&&(t=i.raws.between,typeof t!="undefined"))return!1}),t}rawBeforeRule(e){let t;return e.walk(i=>{if(i.nodes&&(i.parent!==e||e.first!==i)&&typeof i.raws.before!="undefined")return t=i.raws.before,t.includes(` +`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(i=>{if(typeof i.raws.between!="undefined")return t=i.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length===0&&(t=i.raws.after,typeof t!="undefined"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(i=>{let n=i.parent;if(n&&n!==e&&n.parent&&n.parent===e&&typeof i.raws.before!="undefined"){let s=i.raws.before.split(` +`);return t=s[s.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length&&i.last.type==="decl"&&(t=i.raws.semicolon,typeof t!="undefined"))return!1}),t}rawValue(e,t){let i=e[t],n=e.raws[t];return n&&n.value===i?n.raw:i}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};dc.exports=on;on.default=on});var Vr=x((k3,hc)=>{u();"use strict";var xx=fa();function ca(r,e){new xx(e).stringify(r)}hc.exports=ca;ca.default=ca});var ln=x((S3,pa)=>{u();"use strict";pa.exports.isClean=Symbol("isClean");pa.exports.my=Symbol("my")});var Gr=x((A3,mc)=>{u();"use strict";var kx=an(),Sx=fa(),Ax=Vr(),{isClean:Hr,my:Cx}=ln();function da(r,e){let t=new r.constructor;for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i)||i==="proxyCache")continue;let n=r[i],s=typeof n;i==="parent"&&s==="object"?e&&(t[i]=e):i==="source"?t[i]=n:Array.isArray(n)?t[i]=n.map(a=>da(a,t)):(s==="object"&&n!==null&&(n=da(n)),t[i]=n)}return t}function Wr(r,e){if(e&&typeof e.offset!="undefined")return e.offset;let t=1,i=1,n=0;for(let s=0;se.root().toProxy():e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="prop"||t==="value"||t==="name"||t==="params"||t==="important"||t==="text")&&e.markDirty()),!0}}}markClean(){this[Hr]=!0}markDirty(){if(this[Hr]){this[Hr]=!1;let e=this;for(;e=e.parent;)e[Hr]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e){let t=this.source.start;if(e.index)t=this.positionInside(e.index);else if(e.word){let n=this.source.input.css.slice(Wr(this.source.input.css,this.source.start),Wr(this.source.input.css,this.source.end)).indexOf(e.word);n!==-1&&(t=this.positionInside(n))}return t}positionInside(e){let t=this.source.start.column,i=this.source.start.line,n=Wr(this.source.input.css,this.source.start),s=n+e;for(let a=n;atypeof l=="object"&&l.toJSON?l.toJSON(null,t):l);else if(typeof o=="object"&&o.toJSON)i[a]=o.toJSON(null,t);else if(a==="source"){let l=t.get(o.input);l==null&&(l=s,t.set(o.input,s),s++),i[a]={end:o.end,inputId:l,start:o.start}}else i[a]=o}return n&&(i.inputs=[...t.keys()].map(a=>a.toJSON())),i}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Ax){e.stringify&&(e=e.stringify);let t="";return e(this,i=>{t+=i}),t}warn(e,t,i){let n={node:this};for(let s in i)n[s]=i[s];return e.warn(t,n)}get proxyOf(){return this}};mc.exports=un;un.default=un});var Qr=x((C3,gc)=>{u();"use strict";var _x=Gr(),fn=class extends _x{constructor(e){super(e);this.type="comment"}};gc.exports=fn;fn.default=fn});var Yr=x((_3,yc)=>{u();"use strict";var Ex=Gr(),cn=class extends Ex{constructor(e){e&&typeof e.value!="undefined"&&typeof e.value!="string"&&(e={...e,value:String(e.value)});super(e);this.type="decl"}get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}};yc.exports=cn;cn.default=cn});var Et=x((E3,_c)=>{u();"use strict";var bc=Qr(),wc=Yr(),Ox=Gr(),{isClean:vc,my:xc}=ln(),ha,kc,Sc,ma;function Ac(r){return r.map(e=>(e.nodes&&(e.nodes=Ac(e.nodes)),delete e.source,e))}function Cc(r){if(r[vc]=!1,r.proxyOf.nodes)for(let e of r.proxyOf.nodes)Cc(e)}var Fe=class extends Ox{append(...e){for(let t of e){let i=this.normalize(t,this.last);for(let n of i)this.proxyOf.nodes.push(n)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),i,n;for(;this.indexes[t]e[t](...i.map(n=>typeof n=="function"?(s,a)=>n(s.toProxy(),a):n)):t==="every"||t==="some"?i=>e[t]((n,...s)=>i(n.toProxy(),...s)):t==="root"?()=>e.root().toProxy():t==="nodes"?e.nodes.map(i=>i.toProxy()):t==="first"||t==="last"?e[t].toProxy():e[t]:e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="name"||t==="params"||t==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let i=this.index(e),n=this.normalize(t,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of n)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i(n[xc]||Fe.rebuild(n),n=n.proxyOf,n.parent&&n.parent.removeChild(n),n[vc]&&Cc(n),n.raws||(n.raws={}),typeof n.raws.before=="undefined"&&t&&typeof t.raws.before!="undefined"&&(n.raws.before=t.raws.before.replace(/\S/g,"")),n.parent=this.proxyOf,n))}prepend(...e){e=e.reverse();for(let t of e){let i=this.normalize(t,this.first,"prepend").reverse();for(let n of i)this.proxyOf.nodes.unshift(n);for(let n in this.indexes)this.indexes[n]=this.indexes[n]+i.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let t;for(let i in this.indexes)t=this.indexes[i],t>=e&&(this.indexes[i]=t-1);return this.markDirty(),this}replaceValues(e,t,i){return i||(i=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,i))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,i)=>{let n;try{n=e(t,i)}catch(s){throw t.addToError(s)}return n!==!1&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="atrule"&&e.test(i.name))return t(i,n)}):this.walk((i,n)=>{if(i.type==="atrule"&&i.name===e)return t(i,n)}):(t=e,this.walk((i,n)=>{if(i.type==="atrule")return t(i,n)}))}walkComments(e){return this.walk((t,i)=>{if(t.type==="comment")return e(t,i)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="decl"&&e.test(i.prop))return t(i,n)}):this.walk((i,n)=>{if(i.type==="decl"&&i.prop===e)return t(i,n)}):(t=e,this.walk((i,n)=>{if(i.type==="decl")return t(i,n)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="rule"&&e.test(i.selector))return t(i,n)}):this.walk((i,n)=>{if(i.type==="rule"&&i.selector===e)return t(i,n)}):(t=e,this.walk((i,n)=>{if(i.type==="rule")return t(i,n)}))}get first(){if(!!this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(!!this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Fe.registerParse=r=>{kc=r};Fe.registerRule=r=>{ma=r};Fe.registerAtRule=r=>{ha=r};Fe.registerRoot=r=>{Sc=r};_c.exports=Fe;Fe.default=Fe;Fe.rebuild=r=>{r.type==="atrule"?Object.setPrototypeOf(r,ha.prototype):r.type==="rule"?Object.setPrototypeOf(r,ma.prototype):r.type==="decl"?Object.setPrototypeOf(r,wc.prototype):r.type==="comment"?Object.setPrototypeOf(r,bc.prototype):r.type==="root"&&Object.setPrototypeOf(r,Sc.prototype),r[xc]=!0,r.nodes&&r.nodes.forEach(e=>{Fe.rebuild(e)})}});var pn=x((O3,Oc)=>{u();"use strict";var Ec=Et(),Kr=class extends Ec{constructor(e){super(e);this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};Oc.exports=Kr;Kr.default=Kr;Ec.registerAtRule(Kr)});var dn=x((T3,Pc)=>{u();"use strict";var Tx=Et(),Tc,Rc,er=class extends Tx{constructor(e){super({type:"document",...e});this.nodes||(this.nodes=[])}toResult(e={}){return new Tc(new Rc,this,e).stringify()}};er.registerLazyResult=r=>{Tc=r};er.registerProcessor=r=>{Rc=r};Pc.exports=er;er.default=er});var Dc=x((R3,Ic)=>{u();var Rx="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Px=(r,e=21)=>(t=e)=>{let i="",n=t;for(;n--;)i+=r[Math.random()*r.length|0];return i},Ix=(r=21)=>{let e="",t=r;for(;t--;)e+=Rx[Math.random()*64|0];return e};Ic.exports={nanoid:Ix,customAlphabet:Px}});var qc=x(()=>{u()});var ga=x((D3,$c)=>{u();$c.exports={}});var mn=x((q3,Bc)=>{u();"use strict";var{nanoid:Dx}=Dc(),{isAbsolute:ya,resolve:ba}=(et(),Ur),{SourceMapConsumer:qx,SourceMapGenerator:$x}=qc(),{fileURLToPath:Lc,pathToFileURL:hn}=(la(),lc),Mc=an(),Lx=ga(),wa=ua(),va=Symbol("fromOffsetCache"),Mx=Boolean(qx&&$x),Nc=Boolean(ba&&ya),Xr=class{constructor(e,t={}){if(e===null||typeof e=="undefined"||typeof e=="object"&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),this.css[0]==="\uFEFF"||this.css[0]==="\uFFFE"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!Nc||/^\w+:\/\//.test(t.from)||ya(t.from)?this.file=t.from:this.file=ba(t.from)),Nc&&Mx){let i=new Lx(this.css,t);if(i.text){this.map=i;let n=i.consumer().file;!this.file&&n&&(this.file=this.mapResolve(n))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,i,n={}){let s,a,o;if(t&&typeof t=="object"){let c=t,f=i;if(typeof c.offset=="number"){let d=this.fromOffset(c.offset);t=d.line,i=d.col}else t=c.line,i=c.column;if(typeof f.offset=="number"){let d=this.fromOffset(f.offset);a=d.line,s=d.col}else a=f.line,s=f.column}else if(!i){let c=this.fromOffset(t);t=c.line,i=c.col}let l=this.origin(t,i,a,s);return l?o=new Mc(e,l.endLine===void 0?l.line:{column:l.column,line:l.line},l.endLine===void 0?l.column:{column:l.endColumn,line:l.endLine},l.source,l.file,n.plugin):o=new Mc(e,a===void 0?t:{column:i,line:t},a===void 0?i:{column:s,line:a},this.css,this.file,n.plugin),o.input={column:i,endColumn:s,endLine:a,line:t,source:this.css},this.file&&(hn&&(o.input.url=hn(this.file).toString()),o.input.file=this.file),o}fromOffset(e){let t,i;if(this[va])i=this[va];else{let s=this.css.split(` +`);i=new Array(s.length);let a=0;for(let o=0,l=s.length;o=t)n=i.length-1;else{let s=i.length-2,a;for(;n>1),e=i[a+1])n=a+1;else{n=a;break}}return{col:e-i[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:ba(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,i,n){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;let o;typeof i=="number"&&(o=s.originalPositionFor({column:n,line:i}));let l;ya(a.source)?l=hn(a.source):l=new URL(a.source,this.map.consumer().sourceRoot||hn(this.map.mapFile));let c={column:a.column,endColumn:o&&o.column,endLine:o&&o.line,line:a.line,url:l.toString()};if(l.protocol==="file:")if(Lc)c.file=Lc(l);else throw new Error("file: protocol is not available in this PostCSS build");let f=s.sourceContentFor(a.source);return f&&(c.source=f),c}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};Bc.exports=Xr;Xr.default=Xr;wa&&wa.registerInput&&wa.registerInput(Xr)});var tr=x(($3,Uc)=>{u();"use strict";var Fc=Et(),jc,zc,Ut=class extends Fc{constructor(e){super(e);this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,i){let n=super.normalize(e);if(t){if(i==="prepend")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let s of n)s.raws.before=t.raws.before}return n}removeChild(e,t){let i=this.index(e);return!t&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}toResult(e={}){return new jc(new zc,this,e).stringify()}};Ut.registerLazyResult=r=>{jc=r};Ut.registerProcessor=r=>{zc=r};Uc.exports=Ut;Ut.default=Ut;Fc.registerRoot(Ut)});var xa=x((L3,Vc)=>{u();"use strict";var Zr={comma(r){return Zr.split(r,[","],!0)},space(r){let e=[" ",` +`," "];return Zr.split(r,e)},split(r,e,t){let i=[],n="",s=!1,a=0,o=!1,l="",c=!1;for(let f of r)c?c=!1:f==="\\"?c=!0:o?f===l&&(o=!1):f==='"'||f==="'"?(o=!0,l=f):f==="("?a+=1:f===")"?a>0&&(a-=1):a===0&&e.includes(f)&&(s=!0),s?(n!==""&&i.push(n.trim()),n="",s=!1):n+=f;return(t||n!=="")&&i.push(n.trim()),i}};Vc.exports=Zr;Zr.default=Zr});var gn=x((M3,Wc)=>{u();"use strict";var Hc=Et(),Nx=xa(),Jr=class extends Hc{constructor(e){super(e);this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Nx.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,i=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}};Wc.exports=Jr;Jr.default=Jr;Hc.registerRule(Jr)});var Qc=x((N3,Gc)=>{u();"use strict";var Bx=pn(),Fx=Qr(),jx=Yr(),zx=mn(),Ux=ga(),Vx=tr(),Hx=gn();function ei(r,e){if(Array.isArray(r))return r.map(n=>ei(n));let{inputs:t,...i}=r;if(t){e=[];for(let n of t){let s={...n,__proto__:zx.prototype};s.map&&(s.map={...s.map,__proto__:Ux.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=r.nodes.map(n=>ei(n,e))),i.source){let{inputId:n,...s}=i.source;i.source=s,n!=null&&(i.source.input=e[n])}if(i.type==="root")return new Vx(i);if(i.type==="decl")return new jx(i);if(i.type==="rule")return new Hx(i);if(i.type==="comment")return new Fx(i);if(i.type==="atrule")return new Bx(i);throw new Error("Unknown node type: "+r.type)}Gc.exports=ei;ei.default=ei});var ka=x((B3,Yc)=>{u();Yc.exports=function(r,e){return{generate:()=>{let t="";return r(e,i=>{t+=i}),[t]}}}});var ep=x((F3,Jc)=>{u();"use strict";var Sa="'".charCodeAt(0),Kc='"'.charCodeAt(0),yn="\\".charCodeAt(0),Xc="/".charCodeAt(0),bn=` +`.charCodeAt(0),ti=" ".charCodeAt(0),wn="\f".charCodeAt(0),vn=" ".charCodeAt(0),xn="\r".charCodeAt(0),Wx="[".charCodeAt(0),Gx="]".charCodeAt(0),Qx="(".charCodeAt(0),Yx=")".charCodeAt(0),Kx="{".charCodeAt(0),Xx="}".charCodeAt(0),Zx=";".charCodeAt(0),Jx="*".charCodeAt(0),e1=":".charCodeAt(0),t1="@".charCodeAt(0),kn=/[\t\n\f\r "#'()/;[\\\]{}]/g,Sn=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,r1=/.[\r\n"'(/\\]/,Zc=/[\da-f]/i;Jc.exports=function(e,t={}){let i=e.css.valueOf(),n=t.ignoreErrors,s,a,o,l,c,f,d,p,h,b,v=i.length,y=0,w=[],k=[];function S(){return y}function E(R){throw e.error("Unclosed "+R,y)}function T(){return k.length===0&&y>=v}function B(R){if(k.length)return k.pop();if(y>=v)return;let F=R?R.ignoreUnclosed:!1;switch(s=i.charCodeAt(y),s){case bn:case ti:case vn:case xn:case wn:{l=y;do l+=1,s=i.charCodeAt(l);while(s===ti||s===bn||s===vn||s===xn||s===wn);f=["space",i.slice(y,l)],y=l-1;break}case Wx:case Gx:case Kx:case Xx:case e1:case Zx:case Yx:{let Y=String.fromCharCode(s);f=[Y,Y,y];break}case Qx:{if(b=w.length?w.pop()[1]:"",h=i.charCodeAt(y+1),b==="url"&&h!==Sa&&h!==Kc&&h!==ti&&h!==bn&&h!==vn&&h!==wn&&h!==xn){l=y;do{if(d=!1,l=i.indexOf(")",l+1),l===-1)if(n||F){l=y;break}else E("bracket");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["brackets",i.slice(y,l+1),y,l],y=l}else l=i.indexOf(")",y+1),a=i.slice(y,l+1),l===-1||r1.test(a)?f=["(","(",y]:(f=["brackets",a,y,l],y=l);break}case Sa:case Kc:{c=s===Sa?"'":'"',l=y;do{if(d=!1,l=i.indexOf(c,l+1),l===-1)if(n||F){l=y+1;break}else E("string");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["string",i.slice(y,l+1),y,l],y=l;break}case t1:{kn.lastIndex=y+1,kn.test(i),kn.lastIndex===0?l=i.length-1:l=kn.lastIndex-2,f=["at-word",i.slice(y,l+1),y,l],y=l;break}case yn:{for(l=y,o=!0;i.charCodeAt(l+1)===yn;)l+=1,o=!o;if(s=i.charCodeAt(l+1),o&&s!==Xc&&s!==ti&&s!==bn&&s!==vn&&s!==xn&&s!==wn&&(l+=1,Zc.test(i.charAt(l)))){for(;Zc.test(i.charAt(l+1));)l+=1;i.charCodeAt(l+1)===ti&&(l+=1)}f=["word",i.slice(y,l+1),y,l],y=l;break}default:{s===Xc&&i.charCodeAt(y+1)===Jx?(l=i.indexOf("*/",y+2)+1,l===0&&(n||F?l=i.length:E("comment")),f=["comment",i.slice(y,l+1),y,l],y=l):(Sn.lastIndex=y+1,Sn.test(i),Sn.lastIndex===0?l=i.length-1:l=Sn.lastIndex-2,f=["word",i.slice(y,l+1),y,l],w.push(f),y=l);break}}return y++,f}function N(R){k.push(R)}return{back:N,endOfFile:T,nextToken:B,position:S}}});var sp=x((j3,np)=>{u();"use strict";var i1=pn(),n1=Qr(),s1=Yr(),a1=tr(),tp=gn(),o1=ep(),rp={empty:!0,space:!0};function l1(r){for(let e=r.length-1;e>=0;e--){let t=r[e],i=t[3]||t[2];if(i)return i}}var ip=class{constructor(e){this.input=e,this.root=new a1,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new i1;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,n,s,a=!1,o=!1,l=[],c=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?c.push(i==="("?")":"]"):i==="{"&&c.length>0?c.push("}"):i===c[c.length-1]&&c.pop(),c.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(l.length>0){for(s=l.length-1,n=l[s];n&&n[0]==="space";)n=l[--s];n&&(t.source.end=this.getPosition(n[3]||n[2]),t.source.end.offset++)}this.end(e);break}else l.push(e);else l.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(l),l.length?(t.raws.afterName=this.spacesAndCommentsFromStart(l),this.raw(t,"params",l),a&&(e=l[l.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between="")):(t.raws.afterName="",t.params=""),o&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let i=0,n;for(let s=t-1;s>=0&&(n=e[s],!(n[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",n[0]==="word"?n[3]+1:n[2])}colon(e){let t=0,i,n,s;for(let[a,o]of e.entries()){if(n=o,s=n[0],s==="("&&(t+=1),s===")"&&(t-=1),t===0&&s===":")if(!i)this.doubleColon(n);else{if(i[0]==="word"&&i[1]==="progid")continue;return a}i=n}return!1}comment(e){let t=new n1;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let i=e[1].slice(2,-2);if(/^\s*$/.test(i))t.text="",t.raws.left=i,t.raws.right="";else{let n=i.match(/^(\s*)([^]*\S)(\s*)$/);t.text=n[2],t.raws.left=n[1],t.raws.right=n[3]}}createTokenizer(){this.tokenizer=o1(this.input)}decl(e,t){let i=new s1;this.init(i,e[0][2]);let n=e[e.length-1];for(n[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(n[3]||n[2]||l1(e)),i.source.end.offset++;e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let c=e[0][0];if(c===":"||c==="space"||c==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1];break}else s[0]==="word"&&/\w/.test(s[1])&&this.unknownWord([s]),i.raws.between+=s[1];(i.prop[0]==="_"||i.prop[0]==="*")&&(i.raws.before+=i.prop[0],i.prop=i.prop.slice(1));let a=[],o;for(;e.length&&(o=e[0][0],!(o!=="space"&&o!=="comment"));)a.push(e.shift());this.precheckMissedSemicolon(e);for(let c=e.length-1;c>=0;c--){if(s=e[c],s[1].toLowerCase()==="!important"){i.important=!0;let f=this.stringFrom(e,c);f=this.spacesFromEnd(e)+f,f!==" !important"&&(i.raws.important=f);break}else if(s[1].toLowerCase()==="important"){let f=e.slice(0),d="";for(let p=c;p>0;p--){let h=f[p][0];if(d.trim().startsWith("!")&&h!=="space")break;d=f.pop()[1]+d}d.trim().startsWith("!")&&(i.important=!0,i.raws.important=d,e=f)}if(s[0]!=="space"&&s[0]!=="comment")break}e.some(c=>c[0]!=="space"&&c[0]!=="comment")&&(i.raws.between+=a.map(c=>c[1]).join(""),a=[]),this.raw(i,"value",a.concat(e),t),i.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new tp;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let t=this.current.nodes[this.current.nodes.length-1];t&&t.type==="rule"&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="",e.type!=="comment"&&(this.semicolon=!1)}other(e){let t=!1,i=null,n=!1,s=null,a=[],o=e[1].startsWith("--"),l=[],c=e;for(;c;){if(i=c[0],l.push(c),i==="("||i==="[")s||(s=c),a.push(i==="("?")":"]");else if(o&&n&&i==="{")s||(s=c),a.push("}");else if(a.length===0)if(i===";")if(n){this.decl(l,o);return}else break;else if(i==="{"){this.rule(l);return}else if(i==="}"){this.tokenizer.back(l.pop()),t=!0;break}else i===":"&&(n=!0);else i===a[a.length-1]&&(a.pop(),a.length===0&&(s=null));c=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),a.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;l.length&&(c=l[l.length-1][0],!(c!=="space"&&c!=="comment"));)this.tokenizer.back(l.pop());this.decl(l,o)}else this.unknownWord(l)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}precheckMissedSemicolon(){}raw(e,t,i,n){let s,a,o=i.length,l="",c=!0,f,d;for(let p=0;ph+b[1],"");e.raws[t]={raw:p,value:l}}e[t]=l}rule(e){e.pop();let t=new tp;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],!(t!=="space"&&t!=="comment"));)i=e.pop()[1]+i;return i}spacesAndCommentsFromStart(e){let t,i="";for(;e.length&&(t=e[0][0],!(t!=="space"&&t!=="comment"));)i+=e.shift()[1];return i}spacesFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],t==="space");)i=e.pop()[1]+i;return i}stringFrom(e,t){let i="";for(let n=t;n{u();"use strict";var u1=Et(),f1=mn(),c1=sp();function An(r,e){let t=new f1(r,e),i=new c1(t);try{i.parse()}catch(n){throw n}return i.root}ap.exports=An;An.default=An;u1.registerParse(An)});var Aa=x((U3,op)=>{u();"use strict";var _n=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let i=t.node.rangeBy(t);this.line=i.start.line,this.column=i.start.column,this.endLine=i.end.line,this.endColumn=i.end.column}for(let i in t)this[i]=t[i]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};op.exports=_n;_n.default=_n});var On=x((V3,lp)=>{u();"use strict";var p1=Aa(),En=class{constructor(e,t,i){this.processor=e,this.messages=[],this.root=t,this.opts=i,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let i=new p1(e,t);return this.messages.push(i),i}warnings(){return this.messages.filter(e=>e.type==="warning")}get content(){return this.css}};lp.exports=En;En.default=En});var Ca=x((H3,fp)=>{u();"use strict";var up={};fp.exports=function(e){up[e]||(up[e]=!0,typeof console!="undefined"&&console.warn&&console.warn(e))}});var Oa=x((G3,hp)=>{u();"use strict";var d1=Et(),h1=dn(),m1=ka(),g1=Cn(),cp=On(),y1=tr(),b1=Vr(),{isClean:tt,my:w1}=ln(),W3=Ca(),v1={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},x1={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},k1={Once:!0,postcssPlugin:!0,prepare:!0},rr=0;function ri(r){return typeof r=="object"&&typeof r.then=="function"}function pp(r){let e=!1,t=v1[r.type];return r.type==="decl"?e=r.prop.toLowerCase():r.type==="atrule"&&(e=r.name.toLowerCase()),e&&r.append?[t,t+"-"+e,rr,t+"Exit",t+"Exit-"+e]:e?[t,t+"-"+e,t+"Exit",t+"Exit-"+e]:r.append?[t,rr,t+"Exit"]:[t,t+"Exit"]}function dp(r){let e;return r.type==="document"?e=["Document",rr,"DocumentExit"]:r.type==="root"?e=["Root",rr,"RootExit"]:e=pp(r),{eventIndex:0,events:e,iterator:0,node:r,visitorIndex:0,visitors:[]}}function _a(r){return r[tt]=!1,r.nodes&&r.nodes.forEach(e=>_a(e)),r}var Ea={},pt=class{constructor(e,t,i){this.stringified=!1,this.processed=!1;let n;if(typeof t=="object"&&t!==null&&(t.type==="root"||t.type==="document"))n=_a(t);else if(t instanceof pt||t instanceof cp)n=_a(t.root),t.map&&(typeof i.map=="undefined"&&(i.map={}),i.map.inline||(i.map.inline=!1),i.map.prev=t.map);else{let s=g1;i.syntax&&(s=i.syntax.parse),i.parser&&(s=i.parser),s.parse&&(s=s.parse);try{n=s(t,i)}catch(a){this.processed=!0,this.error=a}n&&!n[w1]&&d1.rebuild(n)}this.result=new cp(e,n,i),this.helpers={...Ea,postcss:Ea,result:this.result},this.plugins=this.processor.plugins.map(s=>typeof s=="object"&&s.prepare?{...s,...s.prepare(this.result)}:s)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let i=this.result.lastPlugin;try{t&&t.addToError(e),this.error=e,e.name==="CssSyntaxError"&&!e.plugin?(e.plugin=i.postcssPlugin,e.setMessage()):i.postcssVersion}catch(n){console&&console.error&&console.error(n)}return e}prepareVisitors(){this.listeners={};let e=(t,i,n)=>{this.listeners[i]||(this.listeners[i]=[]),this.listeners[i].push([t,n])};for(let t of this.plugins)if(typeof t=="object")for(let i in t){if(!x1[i]&&/^[A-Z]/.test(i))throw new Error(`Unknown event ${i} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!k1[i])if(typeof t[i]=="object")for(let n in t[i])n==="*"?e(t,i,t[i][n]):e(t,i+"-"+n.toLowerCase(),t[i][n]);else typeof t[i]=="function"&&e(t,i,t[i])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let i=this.visitTick(t);if(ri(i))try{await i}catch(n){let s=t[t.length-1].node;throw this.handleError(n,s)}}}if(this.listeners.OnceExit)for(let[t,i]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if(e.type==="document"){let n=e.nodes.map(s=>i(s,this.helpers));await Promise.all(n)}else await i(e,this.helpers)}catch(n){throw this.handleError(n)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e=="object"&&e.Once){if(this.result.root.type==="document"){let t=this.result.root.nodes.map(i=>e.Once(i,this.helpers));return ri(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}else if(typeof e=="function")return e(this.result.root,this.result)}catch(t){throw this.handleError(t)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=b1;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let n=new m1(t,this.result.root,this.result.opts).generate();return this.result.css=n[0],this.result.map=n[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let t=this.runOnRoot(e);if(ri(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[tt];)e[tt]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type==="document")for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[i,n]of e){this.result.lastPlugin=i;let s;try{s=n(t,this.helpers)}catch(a){throw this.handleError(a,t.proxyOf)}if(t.type!=="root"&&t.type!=="document"&&!t.parent)return!0;if(ri(s))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:i,visitors:n}=t;if(i.type!=="root"&&i.type!=="document"&&!i.parent){e.pop();return}if(n.length>0&&t.visitorIndex{n[tt]||this.walkSync(n)});else{let n=this.listeners[i];if(n&&this.visitSync(n,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};pt.registerPostcss=r=>{Ea=r};hp.exports=pt;pt.default=pt;y1.registerLazyResult(pt);h1.registerLazyResult(pt)});var gp=x((Y3,mp)=>{u();"use strict";var S1=ka(),A1=Cn(),C1=On(),_1=Vr(),Q3=Ca(),Tn=class{constructor(e,t,i){t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=i,this._map=void 0;let n,s=_1;this.result=new C1(this._processor,n,this._opts),this.result.css=t;let a=this;Object.defineProperty(this.result,"root",{get(){return a.root}});let o=new S1(s,n,this._opts,t);if(o.isMap()){let[l,c]=o.generate();l&&(this.result.css=l),c&&(this.result.map=c)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=A1;try{e=t(this._css,this._opts)}catch(i){this.error=i}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};mp.exports=Tn;Tn.default=Tn});var bp=x((K3,yp)=>{u();"use strict";var E1=dn(),O1=Oa(),T1=gp(),R1=tr(),ir=class{constructor(e=[]){this.version="8.4.49",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let i of e)if(i.postcss===!0?i=i():i.postcss&&(i=i.postcss),typeof i=="object"&&Array.isArray(i.plugins))t=t.concat(i.plugins);else if(typeof i=="object"&&i.postcssPlugin)t.push(i);else if(typeof i=="function")t.push(i);else if(!(typeof i=="object"&&(i.parse||i.stringify)))throw new Error(i+" is not a PostCSS plugin");return t}process(e,t={}){return!this.plugins.length&&!t.parser&&!t.stringifier&&!t.syntax?new T1(this,e,t):new O1(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};yp.exports=ir;ir.default=ir;R1.registerProcessor(ir);E1.registerProcessor(ir)});var $e=x((X3,Cp)=>{u();"use strict";var wp=pn(),vp=Qr(),P1=Et(),I1=an(),xp=Yr(),kp=dn(),D1=Qc(),q1=mn(),$1=Oa(),L1=xa(),M1=Gr(),N1=Cn(),Ta=bp(),B1=On(),Sp=tr(),Ap=gn(),F1=Vr(),j1=Aa();function J(...r){return r.length===1&&Array.isArray(r[0])&&(r=r[0]),new Ta(r)}J.plugin=function(e,t){let i=!1;function n(...a){console&&console.warn&&!i&&(i=!0,console.warn(e+`: postcss.plugin was deprecated. Migration guide: +https://evilmartians.com/chronicles/postcss-8-plugin-migration`),m.env.LANG&&m.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357: +https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new Ta().version,o}let s;return Object.defineProperty(n,"postcss",{get(){return s||(s=n()),s}}),n.process=function(a,o,l){return J([n(l)]).process(a,o)},n};J.stringify=F1;J.parse=N1;J.fromJSON=D1;J.list=L1;J.comment=r=>new vp(r);J.atRule=r=>new wp(r);J.decl=r=>new xp(r);J.rule=r=>new Ap(r);J.root=r=>new Sp(r);J.document=r=>new kp(r);J.CssSyntaxError=I1;J.Declaration=xp;J.Container=P1;J.Processor=Ta;J.Document=kp;J.Comment=vp;J.Warning=j1;J.AtRule=wp;J.Result=B1;J.Input=q1;J.Rule=Ap;J.Root=Sp;J.Node=M1;$1.registerPostcss(J);Cp.exports=J;J.default=J});var re,ee,Z3,J3,eI,tI,rI,iI,nI,sI,aI,oI,lI,uI,fI,cI,pI,dI,hI,mI,gI,yI,bI,wI,vI,xI,Ot=P(()=>{u();re=pe($e()),ee=re.default,Z3=re.default.stringify,J3=re.default.fromJSON,eI=re.default.plugin,tI=re.default.parse,rI=re.default.list,iI=re.default.document,nI=re.default.comment,sI=re.default.atRule,aI=re.default.rule,oI=re.default.decl,lI=re.default.root,uI=re.default.CssSyntaxError,fI=re.default.Declaration,cI=re.default.Container,pI=re.default.Processor,dI=re.default.Document,hI=re.default.Comment,mI=re.default.Warning,gI=re.default.AtRule,yI=re.default.Result,bI=re.default.Input,wI=re.default.Rule,vI=re.default.Root,xI=re.default.Node});var Ra=x((SI,_p)=>{u();_p.exports=function(r,e,t,i,n){for(e=e.split?e.split("."):e,i=0;i{u();"use strict";Rn.__esModule=!0;Rn.default=V1;function z1(r){for(var e=r.toLowerCase(),t="",i=!1,n=0;n<6&&e[n]!==void 0;n++){var s=e.charCodeAt(n),a=s>=97&&s<=102||s>=48&&s<=57;if(i=s===32,!a)break;t+=e[n]}if(t.length!==0){var o=parseInt(t,16),l=o>=55296&&o<=57343;return l||o===0||o>1114111?["\uFFFD",t.length+(i?1:0)]:[String.fromCodePoint(o),t.length+(i?1:0)]}}var U1=/\\/;function V1(r){var e=U1.test(r);if(!e)return r;for(var t="",i=0;i{u();"use strict";In.__esModule=!0;In.default=H1;function H1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i0;){var n=t.shift();if(!r[n])return;r=r[n]}return r}Op.exports=In.default});var Pp=x((Dn,Rp)=>{u();"use strict";Dn.__esModule=!0;Dn.default=W1;function W1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i0;){var n=t.shift();r[n]||(r[n]={}),r=r[n]}}Rp.exports=Dn.default});var Dp=x((qn,Ip)=>{u();"use strict";qn.__esModule=!0;qn.default=G1;function G1(r){for(var e="",t=r.indexOf("/*"),i=0;t>=0;){e=e+r.slice(i,t);var n=r.indexOf("*/",t+2);if(n<0)return e;i=n+2,t=r.indexOf("/*",i)}return e=e+r.slice(i),e}Ip.exports=qn.default});var ii=x(rt=>{u();"use strict";rt.__esModule=!0;rt.unesc=rt.stripComments=rt.getProp=rt.ensureObject=void 0;var Q1=$n(Pn());rt.unesc=Q1.default;var Y1=$n(Tp());rt.getProp=Y1.default;var K1=$n(Pp());rt.ensureObject=K1.default;var X1=$n(Dp());rt.stripComments=X1.default;function $n(r){return r&&r.__esModule?r:{default:r}}});var dt=x((ni,Lp)=>{u();"use strict";ni.__esModule=!0;ni.default=void 0;var qp=ii();function $p(r,e){for(var t=0;ti||this.source.end.linen||this.source.end.line===i&&this.source.end.column{u();"use strict";ie.__esModule=!0;ie.UNIVERSAL=ie.TAG=ie.STRING=ie.SELECTOR=ie.ROOT=ie.PSEUDO=ie.NESTING=ie.ID=ie.COMMENT=ie.COMBINATOR=ie.CLASS=ie.ATTRIBUTE=void 0;var tk="tag";ie.TAG=tk;var rk="string";ie.STRING=rk;var ik="selector";ie.SELECTOR=ik;var nk="root";ie.ROOT=nk;var sk="pseudo";ie.PSEUDO=sk;var ak="nesting";ie.NESTING=ak;var ok="id";ie.ID=ok;var lk="comment";ie.COMMENT=lk;var uk="combinator";ie.COMBINATOR=uk;var fk="class";ie.CLASS=fk;var ck="attribute";ie.ATTRIBUTE=ck;var pk="universal";ie.UNIVERSAL=pk});var Ln=x((si,Fp)=>{u();"use strict";si.__esModule=!0;si.default=void 0;var dk=mk(dt()),ht=hk(Se());function Mp(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(Mp=function(n){return n?t:e})(r)}function hk(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=Mp(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}function mk(r){return r&&r.__esModule?r:{default:r}}function gk(r,e){var t=typeof Symbol!="undefined"&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=yk(r))||e&&r&&typeof r.length=="number"){t&&(r=t);var i=0;return function(){return i>=r.length?{done:!0}:{done:!1,value:r[i++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yk(r,e){if(!!r){if(typeof r=="string")return Np(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Np(r,e)}}function Np(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,i=new Array(e);t=n&&(this.indexes[a]=s-1);return this},t.removeAll=function(){for(var n=gk(this.nodes),s;!(s=n()).done;){var a=s.value;a.parent=void 0}return this.nodes=[],this},t.empty=function(){return this.removeAll()},t.insertAfter=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a+1,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],a<=o&&(this.indexes[l]=o+1);return this},t.insertBefore=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],o<=a&&(this.indexes[l]=o+1);return this},t._findChildAtPosition=function(n,s){var a=void 0;return this.each(function(o){if(o.atPosition){var l=o.atPosition(n,s);if(l)return a=l,!1}else if(o.isAtPosition(n,s))return a=o,!1}),a},t.atPosition=function(n,s){if(this.isAtPosition(n,s))return this._findChildAtPosition(n,s)||this},t._inferEndPosition=function(){this.last&&this.last.source&&this.last.source.end&&(this.source=this.source||{},this.source.end=this.source.end||{},Object.assign(this.source.end,this.last.source.end))},t.each=function(n){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach++;var s=this.lastEach;if(this.indexes[s]=0,!!this.length){for(var a,o;this.indexes[s]{u();"use strict";ai.__esModule=!0;ai.default=void 0;var xk=Sk(Ln()),kk=Se();function Sk(r){return r&&r.__esModule?r:{default:r}}function jp(r,e){for(var t=0;t{u();"use strict";oi.__esModule=!0;oi.default=void 0;var Ek=Tk(Ln()),Ok=Se();function Tk(r){return r&&r.__esModule?r:{default:r}}function Rk(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,qa(r,e)}function qa(r,e){return qa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},qa(r,e)}var Pk=function(r){Rk(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=Ok.SELECTOR,i}return e}(Ek.default);oi.default=Pk;Up.exports=oi.default});var Mn=x((_I,Vp)=>{u();"use strict";var Ik={},Dk=Ik.hasOwnProperty,qk=function(e,t){if(!e)return t;var i={};for(var n in t)i[n]=Dk.call(e,n)?e[n]:t[n];return i},$k=/[ -,\.\/:-@\[-\^`\{-~]/,Lk=/[ -,\.\/:-@\[\]\^`\{-~]/,Mk=/(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g,La=function r(e,t){t=qk(t,r.options),t.quotes!="single"&&t.quotes!="double"&&(t.quotes="single");for(var i=t.quotes=="double"?'"':"'",n=t.isIdentifier,s=e.charAt(0),a="",o=0,l=e.length;o126){if(f>=55296&&f<=56319&&o{u();"use strict";li.__esModule=!0;li.default=void 0;var Nk=Hp(Mn()),Bk=ii(),Fk=Hp(dt()),jk=Se();function Hp(r){return r&&r.__esModule?r:{default:r}}function Wp(r,e){for(var t=0;t{u();"use strict";ui.__esModule=!0;ui.default=void 0;var Hk=Gk(dt()),Wk=Se();function Gk(r){return r&&r.__esModule?r:{default:r}}function Qk(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Ba(r,e)}function Ba(r,e){return Ba=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Ba(r,e)}var Yk=function(r){Qk(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=Wk.COMMENT,i}return e}(Hk.default);ui.default=Yk;Qp.exports=ui.default});var za=x((fi,Yp)=>{u();"use strict";fi.__esModule=!0;fi.default=void 0;var Kk=Zk(dt()),Xk=Se();function Zk(r){return r&&r.__esModule?r:{default:r}}function Jk(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,ja(r,e)}function ja(r,e){return ja=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},ja(r,e)}var eS=function(r){Jk(e,r);function e(i){var n;return n=r.call(this,i)||this,n.type=Xk.ID,n}var t=e.prototype;return t.valueToString=function(){return"#"+r.prototype.valueToString.call(this)},e}(Kk.default);fi.default=eS;Yp.exports=fi.default});var Nn=x((ci,Zp)=>{u();"use strict";ci.__esModule=!0;ci.default=void 0;var tS=Kp(Mn()),rS=ii(),iS=Kp(dt());function Kp(r){return r&&r.__esModule?r:{default:r}}function Xp(r,e){for(var t=0;t{u();"use strict";pi.__esModule=!0;pi.default=void 0;var oS=uS(Nn()),lS=Se();function uS(r){return r&&r.__esModule?r:{default:r}}function fS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Va(r,e)}function Va(r,e){return Va=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Va(r,e)}var cS=function(r){fS(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=lS.TAG,i}return e}(oS.default);pi.default=cS;Jp.exports=pi.default});var Ga=x((di,ed)=>{u();"use strict";di.__esModule=!0;di.default=void 0;var pS=hS(dt()),dS=Se();function hS(r){return r&&r.__esModule?r:{default:r}}function mS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Wa(r,e)}function Wa(r,e){return Wa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Wa(r,e)}var gS=function(r){mS(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=dS.STRING,i}return e}(pS.default);di.default=gS;ed.exports=di.default});var Ya=x((hi,td)=>{u();"use strict";hi.__esModule=!0;hi.default=void 0;var yS=wS(Ln()),bS=Se();function wS(r){return r&&r.__esModule?r:{default:r}}function vS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Qa(r,e)}function Qa(r,e){return Qa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Qa(r,e)}var xS=function(r){vS(e,r);function e(i){var n;return n=r.call(this,i)||this,n.type=bS.PSEUDO,n}var t=e.prototype;return t.toString=function(){var n=this.length?"("+this.map(String).join(",")+")":"";return[this.rawSpaceBefore,this.stringifyProperty("value"),n,this.rawSpaceAfter].join("")},e}(yS.default);hi.default=xS;td.exports=hi.default});var Bn={};Ge(Bn,{deprecate:()=>kS});function kS(r){return r}var Fn=P(()=>{u()});var id=x((EI,rd)=>{u();rd.exports=(Fn(),Bn).deprecate});var to=x(yi=>{u();"use strict";yi.__esModule=!0;yi.default=void 0;yi.unescapeValue=Ja;var mi=Xa(Mn()),SS=Xa(Pn()),AS=Xa(Nn()),CS=Se(),Ka;function Xa(r){return r&&r.__esModule?r:{default:r}}function nd(r,e){for(var t=0;t0&&!n.quoted&&o.before.length===0&&!(n.spaces.value&&n.spaces.value.after)&&(o.before=" "),sd(a,o)}))),s.push("]"),s.push(this.rawSpaceAfter),s.join("")},_S(e,[{key:"quoted",get:function(){var n=this.quoteMark;return n==="'"||n==='"'},set:function(n){RS()}},{key:"quoteMark",get:function(){return this._quoteMark},set:function(n){if(!this._constructed){this._quoteMark=n;return}this._quoteMark!==n&&(this._quoteMark=n,this._syncRawValue())}},{key:"qualifiedAttribute",get:function(){return this.qualifiedName(this.raws.attribute||this.attribute)}},{key:"insensitiveFlag",get:function(){return this.insensitive?"i":""}},{key:"value",get:function(){return this._value},set:function(n){if(this._constructed){var s=Ja(n),a=s.deprecatedUsage,o=s.unescaped,l=s.quoteMark;if(a&&TS(),o===this._value&&l===this._quoteMark)return;this._value=o,this._quoteMark=l,this._syncRawValue()}else this._value=n}},{key:"insensitive",get:function(){return this._insensitive},set:function(n){n||(this._insensitive=!1,this.raws&&(this.raws.insensitiveFlag==="I"||this.raws.insensitiveFlag==="i")&&(this.raws.insensitiveFlag=void 0)),this._insensitive=n}},{key:"attribute",get:function(){return this._attribute},set:function(n){this._handleEscapes("attribute",n),this._attribute=n}}]),e}(AS.default);yi.default=jn;jn.NO_QUOTE=null;jn.SINGLE_QUOTE="'";jn.DOUBLE_QUOTE='"';var eo=(Ka={"'":{quotes:"single",wrap:!0},'"':{quotes:"double",wrap:!0}},Ka[null]={isIdentifier:!0},Ka);function sd(r,e){return""+e.before+r+e.after}});var io=x((bi,ad)=>{u();"use strict";bi.__esModule=!0;bi.default=void 0;var DS=$S(Nn()),qS=Se();function $S(r){return r&&r.__esModule?r:{default:r}}function LS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,ro(r,e)}function ro(r,e){return ro=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},ro(r,e)}var MS=function(r){LS(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=qS.UNIVERSAL,i.value="*",i}return e}(DS.default);bi.default=MS;ad.exports=bi.default});var so=x((wi,od)=>{u();"use strict";wi.__esModule=!0;wi.default=void 0;var NS=FS(dt()),BS=Se();function FS(r){return r&&r.__esModule?r:{default:r}}function jS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,no(r,e)}function no(r,e){return no=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},no(r,e)}var zS=function(r){jS(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=BS.COMBINATOR,i}return e}(NS.default);wi.default=zS;od.exports=wi.default});var oo=x((vi,ld)=>{u();"use strict";vi.__esModule=!0;vi.default=void 0;var US=HS(dt()),VS=Se();function HS(r){return r&&r.__esModule?r:{default:r}}function WS(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,ao(r,e)}function ao(r,e){return ao=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},ao(r,e)}var GS=function(r){WS(e,r);function e(t){var i;return i=r.call(this,t)||this,i.type=VS.NESTING,i.value="&",i}return e}(US.default);vi.default=GS;ld.exports=vi.default});var fd=x((zn,ud)=>{u();"use strict";zn.__esModule=!0;zn.default=QS;function QS(r){return r.sort(function(e,t){return e-t})}ud.exports=zn.default});var lo=x(M=>{u();"use strict";M.__esModule=!0;M.word=M.tilde=M.tab=M.str=M.space=M.slash=M.singleQuote=M.semicolon=M.plus=M.pipe=M.openSquare=M.openParenthesis=M.newline=M.greaterThan=M.feed=M.equals=M.doubleQuote=M.dollar=M.cr=M.comment=M.comma=M.combinator=M.colon=M.closeSquare=M.closeParenthesis=M.caret=M.bang=M.backslash=M.at=M.asterisk=M.ampersand=void 0;var YS=38;M.ampersand=YS;var KS=42;M.asterisk=KS;var XS=64;M.at=XS;var ZS=44;M.comma=ZS;var JS=58;M.colon=JS;var eA=59;M.semicolon=eA;var tA=40;M.openParenthesis=tA;var rA=41;M.closeParenthesis=rA;var iA=91;M.openSquare=iA;var nA=93;M.closeSquare=nA;var sA=36;M.dollar=sA;var aA=126;M.tilde=aA;var oA=94;M.caret=oA;var lA=43;M.plus=lA;var uA=61;M.equals=uA;var fA=124;M.pipe=fA;var cA=62;M.greaterThan=cA;var pA=32;M.space=pA;var cd=39;M.singleQuote=cd;var dA=34;M.doubleQuote=dA;var hA=47;M.slash=hA;var mA=33;M.bang=mA;var gA=92;M.backslash=gA;var yA=13;M.cr=yA;var bA=12;M.feed=bA;var wA=10;M.newline=wA;var vA=9;M.tab=vA;var xA=cd;M.str=xA;var kA=-1;M.comment=kA;var SA=-2;M.word=SA;var AA=-3;M.combinator=AA});var hd=x(xi=>{u();"use strict";xi.__esModule=!0;xi.FIELDS=void 0;xi.default=PA;var D=CA(lo()),nr,te;function pd(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(pd=function(n){return n?t:e})(r)}function CA(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=pd(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}var _A=(nr={},nr[D.tab]=!0,nr[D.newline]=!0,nr[D.cr]=!0,nr[D.feed]=!0,nr),EA=(te={},te[D.space]=!0,te[D.tab]=!0,te[D.newline]=!0,te[D.cr]=!0,te[D.feed]=!0,te[D.ampersand]=!0,te[D.asterisk]=!0,te[D.bang]=!0,te[D.comma]=!0,te[D.colon]=!0,te[D.semicolon]=!0,te[D.openParenthesis]=!0,te[D.closeParenthesis]=!0,te[D.openSquare]=!0,te[D.closeSquare]=!0,te[D.singleQuote]=!0,te[D.doubleQuote]=!0,te[D.plus]=!0,te[D.pipe]=!0,te[D.tilde]=!0,te[D.greaterThan]=!0,te[D.equals]=!0,te[D.dollar]=!0,te[D.caret]=!0,te[D.slash]=!0,te),uo={},dd="0123456789abcdefABCDEF";for(Un=0;Un0?(k=a+v,S=w-y[v].length):(k=a,S=s),T=D.comment,a=k,p=k,d=w-S):c===D.slash?(w=o,T=c,p=a,d=o-s,l=w+1):(w=OA(t,o),T=D.word,p=a,d=w-s),l=w+1;break}e.push([T,a,o-s,p,d,o,l]),S&&(s=S,S=null),o=l}return e}});var kd=x((ki,xd)=>{u();"use strict";ki.__esModule=!0;ki.default=void 0;var IA=je(Da()),fo=je($a()),DA=je(Na()),md=je(Fa()),qA=je(za()),$A=je(Ha()),co=je(Ga()),LA=je(Ya()),gd=Vn(to()),MA=je(io()),po=je(so()),NA=je(oo()),BA=je(fd()),O=Vn(hd()),q=Vn(lo()),FA=Vn(Se()),ue=ii(),Vt,ho;function yd(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(yd=function(n){return n?t:e})(r)}function Vn(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=yd(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}function je(r){return r&&r.__esModule?r:{default:r}}function bd(r,e){for(var t=0;t0){var a=this.current.last;if(a){var o=this.convertWhitespaceNodesToSpace(s),l=o.space,c=o.rawSpace;c!==void 0&&(a.rawSpaceAfter+=c),a.spaces.after+=l}else s.forEach(function(T){return i.newNode(T)})}return}var f=this.currToken,d=void 0;n>this.position&&(d=this.parseWhitespaceEquivalentTokens(n));var p;if(this.isNamedCombinator()?p=this.namedCombinator():this.currToken[O.FIELDS.TYPE]===q.combinator?(p=new po.default({value:this.content(),source:sr(this.currToken),sourceIndex:this.currToken[O.FIELDS.START_POS]}),this.position++):mo[this.currToken[O.FIELDS.TYPE]]||d||this.unexpected(),p){if(d){var h=this.convertWhitespaceNodesToSpace(d),b=h.space,v=h.rawSpace;p.spaces.before=b,p.rawSpaceBefore=v}}else{var y=this.convertWhitespaceNodesToSpace(d,!0),w=y.space,k=y.rawSpace;k||(k=w);var S={},E={spaces:{}};w.endsWith(" ")&&k.endsWith(" ")?(S.before=w.slice(0,w.length-1),E.spaces.before=k.slice(0,k.length-1)):w.startsWith(" ")&&k.startsWith(" ")?(S.after=w.slice(1),E.spaces.after=k.slice(1)):E.value=k,p=new po.default({value:" ",source:go(f,this.tokens[this.position-1]),sourceIndex:f[O.FIELDS.START_POS],spaces:S,raws:E})}return this.currToken&&this.currToken[O.FIELDS.TYPE]===q.space&&(p.spaces.after=this.optionalSpace(this.content()),this.position++),this.newNode(p)},e.comma=function(){if(this.position===this.tokens.length-1){this.root.trailingComma=!0,this.position++;return}this.current._inferEndPosition();var i=new fo.default({source:{start:wd(this.tokens[this.position+1])},sourceIndex:this.tokens[this.position+1][O.FIELDS.START_POS]});this.current.parent.append(i),this.current=i,this.position++},e.comment=function(){var i=this.currToken;this.newNode(new md.default({value:this.content(),source:sr(i),sourceIndex:i[O.FIELDS.START_POS]})),this.position++},e.error=function(i,n){throw this.root.error(i,n)},e.missingBackslash=function(){return this.error("Expected a backslash preceding the semicolon.",{index:this.currToken[O.FIELDS.START_POS]})},e.missingParenthesis=function(){return this.expected("opening parenthesis",this.currToken[O.FIELDS.START_POS])},e.missingSquareBracket=function(){return this.expected("opening square bracket",this.currToken[O.FIELDS.START_POS])},e.unexpected=function(){return this.error("Unexpected '"+this.content()+"'. Escaping special characters with \\ may help.",this.currToken[O.FIELDS.START_POS])},e.unexpectedPipe=function(){return this.error("Unexpected '|'.",this.currToken[O.FIELDS.START_POS])},e.namespace=function(){var i=this.prevToken&&this.content(this.prevToken)||!0;if(this.nextToken[O.FIELDS.TYPE]===q.word)return this.position++,this.word(i);if(this.nextToken[O.FIELDS.TYPE]===q.asterisk)return this.position++,this.universal(i);this.unexpectedPipe()},e.nesting=function(){if(this.nextToken){var i=this.content(this.nextToken);if(i==="|"){this.position++;return}}var n=this.currToken;this.newNode(new NA.default({value:this.content(),source:sr(n),sourceIndex:n[O.FIELDS.START_POS]})),this.position++},e.parentheses=function(){var i=this.current.last,n=1;if(this.position++,i&&i.type===FA.PSEUDO){var s=new fo.default({source:{start:wd(this.tokens[this.position])},sourceIndex:this.tokens[this.position][O.FIELDS.START_POS]}),a=this.current;for(i.append(s),this.current=s;this.position1&&i.nextToken&&i.nextToken[O.FIELDS.TYPE]===q.openParenthesis&&i.error("Misplaced parenthesis.",{index:i.nextToken[O.FIELDS.START_POS]})});else return this.expected(["pseudo-class","pseudo-element"],this.currToken[O.FIELDS.START_POS])},e.space=function(){var i=this.content();this.position===0||this.prevToken[O.FIELDS.TYPE]===q.comma||this.prevToken[O.FIELDS.TYPE]===q.openParenthesis||this.current.nodes.every(function(n){return n.type==="comment"})?(this.spaces=this.optionalSpace(i),this.position++):this.position===this.tokens.length-1||this.nextToken[O.FIELDS.TYPE]===q.comma||this.nextToken[O.FIELDS.TYPE]===q.closeParenthesis?(this.current.last.spaces.after=this.optionalSpace(i),this.position++):this.combinator()},e.string=function(){var i=this.currToken;this.newNode(new co.default({value:this.content(),source:sr(i),sourceIndex:i[O.FIELDS.START_POS]})),this.position++},e.universal=function(i){var n=this.nextToken;if(n&&this.content(n)==="|")return this.position++,this.namespace();var s=this.currToken;this.newNode(new MA.default({value:this.content(),source:sr(s),sourceIndex:s[O.FIELDS.START_POS]}),i),this.position++},e.splitWord=function(i,n){for(var s=this,a=this.nextToken,o=this.content();a&&~[q.dollar,q.caret,q.equals,q.word].indexOf(a[O.FIELDS.TYPE]);){this.position++;var l=this.content();if(o+=l,l.lastIndexOf("\\")===l.length-1){var c=this.nextToken;c&&c[O.FIELDS.TYPE]===q.space&&(o+=this.requiredSpace(this.content(c)),this.position++)}a=this.nextToken}var f=yo(o,".").filter(function(b){var v=o[b-1]==="\\",y=/^\d+\.\d+%$/.test(o);return!v&&!y}),d=yo(o,"#").filter(function(b){return o[b-1]!=="\\"}),p=yo(o,"#{");p.length&&(d=d.filter(function(b){return!~p.indexOf(b)}));var h=(0,BA.default)(UA([0].concat(f,d)));h.forEach(function(b,v){var y=h[v+1]||o.length,w=o.slice(b,y);if(v===0&&n)return n.call(s,w,h.length);var k,S=s.currToken,E=S[O.FIELDS.START_POS]+h[v],T=Ht(S[1],S[2]+b,S[3],S[2]+(y-1));if(~f.indexOf(b)){var B={value:w.slice(1),source:T,sourceIndex:E};k=new DA.default(ar(B,"value"))}else if(~d.indexOf(b)){var N={value:w.slice(1),source:T,sourceIndex:E};k=new qA.default(ar(N,"value"))}else{var R={value:w,source:T,sourceIndex:E};ar(R,"value"),k=new $A.default(R)}s.newNode(k,i),i=null}),this.position++},e.word=function(i){var n=this.nextToken;return n&&this.content(n)==="|"?(this.position++,this.namespace()):this.splitWord(i)},e.loop=function(){for(;this.position{u();"use strict";Si.__esModule=!0;Si.default=void 0;var HA=WA(kd());function WA(r){return r&&r.__esModule?r:{default:r}}var GA=function(){function r(t,i){this.func=t||function(){},this.funcRes=null,this.options=i}var e=r.prototype;return e._shouldUpdateSelector=function(i,n){n===void 0&&(n={});var s=Object.assign({},this.options,n);return s.updateSelector===!1?!1:typeof i!="string"},e._isLossy=function(i){i===void 0&&(i={});var n=Object.assign({},this.options,i);return n.lossless===!1},e._root=function(i,n){n===void 0&&(n={});var s=new HA.default(i,this._parseOptions(n));return s.root},e._parseOptions=function(i){return{lossy:this._isLossy(i)}},e._run=function(i,n){var s=this;return n===void 0&&(n={}),new Promise(function(a,o){try{var l=s._root(i,n);Promise.resolve(s.func(l)).then(function(c){var f=void 0;return s._shouldUpdateSelector(i,n)&&(f=l.toString(),i.selector=f),{transform:c,root:l,string:f}}).then(a,o)}catch(c){o(c);return}})},e._runSync=function(i,n){n===void 0&&(n={});var s=this._root(i,n),a=this.func(s);if(a&&typeof a.then=="function")throw new Error("Selector processor returned a promise to a synchronous call.");var o=void 0;return n.updateSelector&&typeof i!="string"&&(o=s.toString(),i.selector=o),{transform:a,root:s,string:o}},e.ast=function(i,n){return this._run(i,n).then(function(s){return s.root})},e.astSync=function(i,n){return this._runSync(i,n).root},e.transform=function(i,n){return this._run(i,n).then(function(s){return s.transform})},e.transformSync=function(i,n){return this._runSync(i,n).transform},e.process=function(i,n){return this._run(i,n).then(function(s){return s.string||s.root.toString()})},e.processSync=function(i,n){var s=this._runSync(i,n);return s.string||s.root.toString()},r}();Si.default=GA;Sd.exports=Si.default});var Cd=x(ne=>{u();"use strict";ne.__esModule=!0;ne.universal=ne.tag=ne.string=ne.selector=ne.root=ne.pseudo=ne.nesting=ne.id=ne.comment=ne.combinator=ne.className=ne.attribute=void 0;var QA=ze(to()),YA=ze(Na()),KA=ze(so()),XA=ze(Fa()),ZA=ze(za()),JA=ze(oo()),eC=ze(Ya()),tC=ze(Da()),rC=ze($a()),iC=ze(Ga()),nC=ze(Ha()),sC=ze(io());function ze(r){return r&&r.__esModule?r:{default:r}}var aC=function(e){return new QA.default(e)};ne.attribute=aC;var oC=function(e){return new YA.default(e)};ne.className=oC;var lC=function(e){return new KA.default(e)};ne.combinator=lC;var uC=function(e){return new XA.default(e)};ne.comment=uC;var fC=function(e){return new ZA.default(e)};ne.id=fC;var cC=function(e){return new JA.default(e)};ne.nesting=cC;var pC=function(e){return new eC.default(e)};ne.pseudo=pC;var dC=function(e){return new tC.default(e)};ne.root=dC;var hC=function(e){return new rC.default(e)};ne.selector=hC;var mC=function(e){return new iC.default(e)};ne.string=mC;var gC=function(e){return new nC.default(e)};ne.tag=gC;var yC=function(e){return new sC.default(e)};ne.universal=yC});var Td=x(Z=>{u();"use strict";Z.__esModule=!0;Z.isComment=Z.isCombinator=Z.isClassName=Z.isAttribute=void 0;Z.isContainer=TC;Z.isIdentifier=void 0;Z.isNamespace=RC;Z.isNesting=void 0;Z.isNode=bo;Z.isPseudo=void 0;Z.isPseudoClass=OC;Z.isPseudoElement=Od;Z.isUniversal=Z.isTag=Z.isString=Z.isSelector=Z.isRoot=void 0;var fe=Se(),Oe,bC=(Oe={},Oe[fe.ATTRIBUTE]=!0,Oe[fe.CLASS]=!0,Oe[fe.COMBINATOR]=!0,Oe[fe.COMMENT]=!0,Oe[fe.ID]=!0,Oe[fe.NESTING]=!0,Oe[fe.PSEUDO]=!0,Oe[fe.ROOT]=!0,Oe[fe.SELECTOR]=!0,Oe[fe.STRING]=!0,Oe[fe.TAG]=!0,Oe[fe.UNIVERSAL]=!0,Oe);function bo(r){return typeof r=="object"&&bC[r.type]}function Ue(r,e){return bo(e)&&e.type===r}var _d=Ue.bind(null,fe.ATTRIBUTE);Z.isAttribute=_d;var wC=Ue.bind(null,fe.CLASS);Z.isClassName=wC;var vC=Ue.bind(null,fe.COMBINATOR);Z.isCombinator=vC;var xC=Ue.bind(null,fe.COMMENT);Z.isComment=xC;var kC=Ue.bind(null,fe.ID);Z.isIdentifier=kC;var SC=Ue.bind(null,fe.NESTING);Z.isNesting=SC;var wo=Ue.bind(null,fe.PSEUDO);Z.isPseudo=wo;var AC=Ue.bind(null,fe.ROOT);Z.isRoot=AC;var CC=Ue.bind(null,fe.SELECTOR);Z.isSelector=CC;var _C=Ue.bind(null,fe.STRING);Z.isString=_C;var Ed=Ue.bind(null,fe.TAG);Z.isTag=Ed;var EC=Ue.bind(null,fe.UNIVERSAL);Z.isUniversal=EC;function Od(r){return wo(r)&&r.value&&(r.value.startsWith("::")||r.value.toLowerCase()===":before"||r.value.toLowerCase()===":after"||r.value.toLowerCase()===":first-letter"||r.value.toLowerCase()===":first-line")}function OC(r){return wo(r)&&!Od(r)}function TC(r){return!!(bo(r)&&r.walk)}function RC(r){return _d(r)||Ed(r)}});var Rd=x(Ke=>{u();"use strict";Ke.__esModule=!0;var vo=Se();Object.keys(vo).forEach(function(r){r==="default"||r==="__esModule"||r in Ke&&Ke[r]===vo[r]||(Ke[r]=vo[r])});var xo=Cd();Object.keys(xo).forEach(function(r){r==="default"||r==="__esModule"||r in Ke&&Ke[r]===xo[r]||(Ke[r]=xo[r])});var ko=Td();Object.keys(ko).forEach(function(r){r==="default"||r==="__esModule"||r in Ke&&Ke[r]===ko[r]||(Ke[r]=ko[r])})});var it=x((Ai,Id)=>{u();"use strict";Ai.__esModule=!0;Ai.default=void 0;var PC=qC(Ad()),IC=DC(Rd());function Pd(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(Pd=function(n){return n?t:e})(r)}function DC(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=Pd(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}function qC(r){return r&&r.__esModule?r:{default:r}}var So=function(e){return new PC.default(e)};Object.assign(So,IC);delete So.__esModule;var $C=So;Ai.default=$C;Id.exports=Ai.default});function mt(r){return["fontSize","outline"].includes(r)?e=>(typeof e=="function"&&(e=e({})),Array.isArray(e)&&(e=e[0]),e):r==="fontFamily"?e=>{typeof e=="function"&&(e=e({}));let t=Array.isArray(e)&&ke(e[1])?e[0]:e;return Array.isArray(t)?t.join(", "):t}:["boxShadow","transitionProperty","transitionDuration","transitionDelay","transitionTimingFunction","backgroundImage","backgroundSize","backgroundColor","cursor","animation"].includes(r)?e=>(typeof e=="function"&&(e=e({})),Array.isArray(e)&&(e=e.join(", ")),e):["gridTemplateColumns","gridTemplateRows","objectPosition"].includes(r)?e=>(typeof e=="function"&&(e=e({})),typeof e=="string"&&(e=ee.list.comma(e).join(" ")),e):(e,t={})=>(typeof e=="function"&&(e=e(t)),e)}var Ci=P(()=>{u();Ot();Kt()});var Bd=x((MI,Oo)=>{u();var{AtRule:LC,Rule:Dd}=$e(),qd=it();function Ao(r,e){let t;try{qd(i=>{t=i}).processSync(r)}catch(i){throw r.includes(":")?e?e.error("Missed semicolon"):i:e?e.error(i.message):i}return t.at(0)}function $d(r,e){let t=!1;return r.each(i=>{if(i.type==="nesting"){let n=e.clone({});i.value!=="&"?i.replaceWith(Ao(i.value.replace("&",n.toString()))):i.replaceWith(n),t=!0}else"nodes"in i&&i.nodes&&$d(i,e)&&(t=!0)}),t}function Ld(r,e){let t=[];return r.selectors.forEach(i=>{let n=Ao(i,r);e.selectors.forEach(s=>{if(!s)return;let a=Ao(s,e);$d(a,n)||(a.prepend(qd.combinator({value:" "})),a.prepend(n.clone({}))),t.push(a.toString())})}),t}function Hn(r,e){let t=r.prev();for(e.after(r);t&&t.type==="comment";){let i=t.prev();e.after(t),t=i}return r}function MC(r){return function e(t,i,n,s=n){let a=[];if(i.each(o=>{o.type==="rule"&&n?s&&(o.selectors=Ld(t,o)):o.type==="atrule"&&o.nodes?r[o.name]?e(t,o,s):i[_o]!==!1&&a.push(o):a.push(o)}),n&&a.length){let o=t.clone({nodes:[]});for(let l of a)o.append(l);i.prepend(o)}}}function Co(r,e,t){let i=new Dd({nodes:[],selector:r});return i.append(e),t.after(i),i}function Md(r,e){let t={};for(let i of r)t[i]=!0;if(e)for(let i of e)t[i.replace(/^@/,"")]=!0;return t}function NC(r){r=r.trim();let e=r.match(/^\((.*)\)$/);if(!e)return{selector:r,type:"basic"};let t=e[1].match(/^(with(?:out)?):(.+)$/);if(t){let i=t[1]==="with",n=Object.fromEntries(t[2].trim().split(/\s+/).map(a=>[a,!0]));if(i&&n.all)return{type:"noop"};let s=a=>!!n[a];return n.all?s=()=>!0:i&&(s=a=>a==="all"?!1:!n[a]),{escapes:s,type:"withrules"}}return{type:"unknown"}}function BC(r){let e=[],t=r.parent;for(;t&&t instanceof LC;)e.push(t),t=t.parent;return e}function FC(r){let e=r[Nd];if(!e)r.after(r.nodes);else{let t=r.nodes,i,n=-1,s,a,o,l=BC(r);if(l.forEach((c,f)=>{if(e(c.name))i=c,n=f,a=o;else{let d=o;o=c.clone({nodes:[]}),d&&o.append(d),s=s||o}}),i?a?(s.append(t),i.after(a)):i.after(t):r.after(t),r.next()&&i){let c;l.slice(0,n+1).forEach((f,d,p)=>{let h=c;c=f.clone({nodes:[]}),h&&c.append(h);let b=[],y=(p[d-1]||r).next();for(;y;)b.push(y),y=y.next();c.append(b)}),c&&(a||t[t.length-1]).after(c)}}r.remove()}var _o=Symbol("rootRuleMergeSel"),Nd=Symbol("rootRuleEscapes");function jC(r){let{params:e}=r,{escapes:t,selector:i,type:n}=NC(e);if(n==="unknown")throw r.error(`Unknown @${r.name} parameter ${JSON.stringify(e)}`);if(n==="basic"&&i){let s=new Dd({nodes:r.nodes,selector:i});r.removeAll(),r.append(s)}r[Nd]=t,r[_o]=t?!t("all"):n==="noop"}var Eo=Symbol("hasRootRule");Oo.exports=(r={})=>{let e=Md(["media","supports","layer","container","starting-style"],r.bubble),t=MC(e),i=Md(["document","font-face","keyframes","-webkit-keyframes","-moz-keyframes"],r.unwrap),n=(r.rootRuleName||"at-root").replace(/^@/,""),s=r.preserveEmpty;return{Once(a){a.walkAtRules(n,o=>{jC(o),a[Eo]=!0})},postcssPlugin:"postcss-nested",RootExit(a){a[Eo]&&(a.walkAtRules(n,FC),a[Eo]=!1)},Rule(a){let o=!1,l=a,c=!1,f=[];a.each(d=>{d.type==="rule"?(f.length&&(l=Co(a.selector,f,l),f=[]),c=!0,o=!0,d.selectors=Ld(a,d),l=Hn(d,l)):d.type==="atrule"?(f.length&&(l=Co(a.selector,f,l),f=[]),d.name===n?(o=!0,t(a,d,!0,d[_o]),l=Hn(d,l)):e[d.name]?(c=!0,o=!0,t(a,d,!0),l=Hn(d,l)):i[d.name]?(c=!0,o=!0,t(a,d,!1),l=Hn(d,l)):c&&f.push(d)):d.type==="decl"&&c&&f.push(d)}),f.length&&(l=Co(a.selector,f,l)),o&&s!==!0&&(a.raws.semicolon=!0,a.nodes.length===0&&a.remove())}}};Oo.exports.postcss=!0});var Ud=x((NI,zd)=>{u();"use strict";var Fd=/-(\w|$)/g,jd=(r,e)=>e.toUpperCase(),zC=r=>(r=r.toLowerCase(),r==="float"?"cssFloat":r.startsWith("-ms-")?r.substr(1).replace(Fd,jd):r.replace(Fd,jd));zd.exports=zC});var Po=x((BI,Vd)=>{u();var UC=Ud(),VC={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0};function To(r){return typeof r.nodes=="undefined"?!0:Ro(r)}function Ro(r){let e,t={};return r.each(i=>{if(i.type==="atrule")e="@"+i.name,i.params&&(e+=" "+i.params),typeof t[e]=="undefined"?t[e]=To(i):Array.isArray(t[e])?t[e].push(To(i)):t[e]=[t[e],To(i)];else if(i.type==="rule"){let n=Ro(i);if(t[i.selector])for(let s in n)t[i.selector][s]=n[s];else t[i.selector]=n}else if(i.type==="decl"){i.prop[0]==="-"&&i.prop[1]==="-"||i.parent&&i.parent.selector===":export"?e=i.prop:e=UC(i.prop);let n=i.value;!isNaN(i.value)&&VC[e]&&(n=parseFloat(i.value)),i.important&&(n+=" !important"),typeof t[e]=="undefined"?t[e]=n:Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]}}),t}Vd.exports=Ro});var Wn=x((FI,Qd)=>{u();var _i=$e(),Hd=/\s*!important\s*$/i,HC={"box-flex":!0,"box-flex-group":!0,"column-count":!0,flex:!0,"flex-grow":!0,"flex-positive":!0,"flex-shrink":!0,"flex-negative":!0,"font-weight":!0,"line-clamp":!0,"line-height":!0,opacity:!0,order:!0,orphans:!0,"tab-size":!0,widows:!0,"z-index":!0,zoom:!0,"fill-opacity":!0,"stroke-dashoffset":!0,"stroke-opacity":!0,"stroke-width":!0};function WC(r){return r.replace(/([A-Z])/g,"-$1").replace(/^ms-/,"-ms-").toLowerCase()}function Wd(r,e,t){t===!1||t===null||(e.startsWith("--")||(e=WC(e)),typeof t=="number"&&(t===0||HC[e]?t=t.toString():t+="px"),e==="css-float"&&(e="float"),Hd.test(t)?(t=t.replace(Hd,""),r.push(_i.decl({prop:e,value:t,important:!0}))):r.push(_i.decl({prop:e,value:t})))}function Gd(r,e,t){let i=_i.atRule({name:e[1],params:e[3]||""});typeof t=="object"&&(i.nodes=[],Io(t,i)),r.push(i)}function Io(r,e){let t,i,n;for(t in r)if(i=r[t],!(i===null||typeof i=="undefined"))if(t[0]==="@"){let s=t.match(/@(\S+)(\s+([\W\w]*)\s*)?/);if(Array.isArray(i))for(let a of i)Gd(e,s,a);else Gd(e,s,i)}else if(Array.isArray(i))for(let s of i)Wd(e,t,s);else typeof i=="object"?(n=_i.rule({selector:t}),Io(i,n),e.push(n)):Wd(e,t,i)}Qd.exports=function(r){let e=_i.root();return Io(r,e),e}});var Do=x((jI,Yd)=>{u();var GC=Po();Yd.exports=function(e){return console&&console.warn&&e.warnings().forEach(t=>{let i=t.plugin||"PostCSS";console.warn(i+": "+t.text)}),GC(e.root)}});var Xd=x((zI,Kd)=>{u();var QC=$e(),YC=Do(),KC=Wn();Kd.exports=function(e){let t=QC(e);return async i=>{let n=await t.process(i,{parser:KC,from:void 0});return YC(n)}}});var Jd=x((UI,Zd)=>{u();var XC=$e(),ZC=Do(),JC=Wn();Zd.exports=function(r){let e=XC(r);return t=>{let i=e.process(t,{parser:JC,from:void 0});return ZC(i)}}});var th=x((VI,eh)=>{u();var e_=Po(),t_=Wn(),r_=Xd(),i_=Jd();eh.exports={objectify:e_,parse:t_,async:r_,sync:i_}});var or,rh,HI,WI,GI,QI,ih=P(()=>{u();or=pe(th()),rh=or.default,HI=or.default.objectify,WI=or.default.parse,GI=or.default.async,QI=or.default.sync});function lr(r){return Array.isArray(r)?r.flatMap(e=>ee([(0,nh.default)({bubble:["screen"]})]).process(e,{parser:rh}).root.nodes):lr([r])}var nh,qo=P(()=>{u();Ot();nh=pe(Bd());ih()});function ur(r,e,t=!1){if(r==="")return e;let i=typeof e=="string"?(0,sh.default)().astSync(e):e;return i.walkClasses(n=>{let s=n.value,a=t&&s.startsWith("-");n.value=a?`-${r}${s.slice(1)}`:`${r}${s}`}),typeof e=="string"?i.toString():i}var sh,Gn=P(()=>{u();sh=pe(it())});function Te(r){let e=ah.default.className();return e.value=r,jt(e?.raws?.value??e.value)}var ah,fr=P(()=>{u();ah=pe(it());Zi()});function $o(r){return jt(`.${Te(r)}`)}function Qn(r,e){return $o(Ei(r,e))}function Ei(r,e){return e==="DEFAULT"?r:e==="-"||e==="-DEFAULT"?`-${r}`:e.startsWith("-")?`-${r}${e}`:e.startsWith("/")?`${r}${e}`:`${r}-${e}`}var Lo=P(()=>{u();fr();Zi()});function L(r,e=[[r,[r]]],{filterDefault:t=!1,...i}={}){let n=mt(r);return function({matchUtilities:s,theme:a}){for(let o of e){let l=Array.isArray(o[0])?o:[o];s(l.reduce((c,[f,d])=>Object.assign(c,{[f]:p=>d.reduce((h,b)=>Array.isArray(b)?Object.assign(h,{[b[0]]:b[1]}):Object.assign(h,{[b]:n(p)}),{})}),{}),{...i,values:t?Object.fromEntries(Object.entries(a(r)??{}).filter(([c])=>c!=="DEFAULT")):a(r)})}}}var oh=P(()=>{u();Ci()});function Tt(r){return r=Array.isArray(r)?r:[r],r.map(e=>{let t=e.values.map(i=>i.raw!==void 0?i.raw:[i.min&&`(min-width: ${i.min})`,i.max&&`(max-width: ${i.max})`].filter(Boolean).join(" and "));return e.not?`not all and ${t}`:t}).join(", ")}var Yn=P(()=>{u()});function Mo(r){return r.split(f_).map(t=>{let i=t.trim(),n={value:i},s=i.split(c_),a=new Set;for(let o of s)!a.has("DIRECTIONS")&&n_.has(o)?(n.direction=o,a.add("DIRECTIONS")):!a.has("PLAY_STATES")&&s_.has(o)?(n.playState=o,a.add("PLAY_STATES")):!a.has("FILL_MODES")&&a_.has(o)?(n.fillMode=o,a.add("FILL_MODES")):!a.has("ITERATION_COUNTS")&&(o_.has(o)||p_.test(o))?(n.iterationCount=o,a.add("ITERATION_COUNTS")):!a.has("TIMING_FUNCTION")&&l_.has(o)||!a.has("TIMING_FUNCTION")&&u_.some(l=>o.startsWith(`${l}(`))?(n.timingFunction=o,a.add("TIMING_FUNCTION")):!a.has("DURATION")&&lh.test(o)?(n.duration=o,a.add("DURATION")):!a.has("DELAY")&&lh.test(o)?(n.delay=o,a.add("DELAY")):a.has("NAME")?(n.unknown||(n.unknown=[]),n.unknown.push(o)):(n.name=o,a.add("NAME"));return n})}var n_,s_,a_,o_,l_,u_,f_,c_,lh,p_,uh=P(()=>{u();n_=new Set(["normal","reverse","alternate","alternate-reverse"]),s_=new Set(["running","paused"]),a_=new Set(["none","forwards","backwards","both"]),o_=new Set(["infinite"]),l_=new Set(["linear","ease","ease-in","ease-out","ease-in-out","step-start","step-end"]),u_=["cubic-bezier","steps"],f_=/\,(?![^(]*\))/g,c_=/\ +(?![^(]*\))/g,lh=/^(-?[\d.]+m?s)$/,p_=/^(\d+)$/});var fh,xe,ch=P(()=>{u();fh=r=>Object.assign({},...Object.entries(r??{}).flatMap(([e,t])=>typeof t=="object"?Object.entries(fh(t)).map(([i,n])=>({[e+(i==="DEFAULT"?"":`-${i}`)]:n})):[{[`${e}`]:t}])),xe=fh});var dh,ph=P(()=>{dh="3.4.17"});function Rt(r,e=!0){return Array.isArray(r)?r.map(t=>{if(e&&Array.isArray(t))throw new Error("The tuple syntax is not supported for `screens`.");if(typeof t=="string")return{name:t.toString(),not:!1,values:[{min:t,max:void 0}]};let[i,n]=t;return i=i.toString(),typeof n=="string"?{name:i,not:!1,values:[{min:n,max:void 0}]}:Array.isArray(n)?{name:i,not:!1,values:n.map(s=>mh(s))}:{name:i,not:!1,values:[mh(n)]}}):Rt(Object.entries(r??{}),!1)}function Kn(r){return r.values.length!==1?{result:!1,reason:"multiple-values"}:r.values[0].raw!==void 0?{result:!1,reason:"raw-values"}:r.values[0].min!==void 0&&r.values[0].max!==void 0?{result:!1,reason:"min-and-max"}:{result:!0,reason:null}}function hh(r,e,t){let i=Xn(e,r),n=Xn(t,r),s=Kn(i),a=Kn(n);if(s.reason==="multiple-values"||a.reason==="multiple-values")throw new Error("Attempted to sort a screen with multiple values. This should never happen. Please open a bug report.");if(s.reason==="raw-values"||a.reason==="raw-values")throw new Error("Attempted to sort a screen with raw values. This should never happen. Please open a bug report.");if(s.reason==="min-and-max"||a.reason==="min-and-max")throw new Error("Attempted to sort a screen with both min and max values. This should never happen. Please open a bug report.");let{min:o,max:l}=i.values[0],{min:c,max:f}=n.values[0];e.not&&([o,l]=[l,o]),t.not&&([c,f]=[f,c]),o=o===void 0?o:parseFloat(o),l=l===void 0?l:parseFloat(l),c=c===void 0?c:parseFloat(c),f=f===void 0?f:parseFloat(f);let[d,p]=r==="min"?[o,c]:[f,l];return d-p}function Xn(r,e){return typeof r=="object"?r:{name:"arbitrary-screen",values:[{[e]:r}]}}function mh({"min-width":r,min:e=r,max:t,raw:i}={}){return{min:e,max:t,raw:i}}var Zn=P(()=>{u()});function Jn(r,e){r.walkDecls(t=>{if(e.includes(t.prop)){t.remove();return}for(let i of e)t.value.includes(`/ var(${i})`)?t.value=t.value.replace(`/ var(${i})`,""):t.value.includes(`/ var(${i}, 1)`)&&(t.value=t.value.replace(`/ var(${i}, 1)`,""))})}var gh=P(()=>{u()});var se,Xe,nt,ge,yh,bh=P(()=>{u();ft();et();Ot();oh();Yn();fr();uh();ch();Lr();ra();Kt();Ci();ph();Be();Zn();Ys();gh();ct();Br();Oi();se={childVariant:({addVariant:r})=>{r("*","& > *")},pseudoElementVariants:({addVariant:r})=>{r("first-letter","&::first-letter"),r("first-line","&::first-line"),r("marker",[({container:e})=>(Jn(e,["--tw-text-opacity"]),"& *::marker"),({container:e})=>(Jn(e,["--tw-text-opacity"]),"&::marker")]),r("selection",["& *::selection","&::selection"]),r("file","&::file-selector-button"),r("placeholder","&::placeholder"),r("backdrop","&::backdrop"),r("before",({container:e})=>(e.walkRules(t=>{let i=!1;t.walkDecls("content",()=>{i=!0}),i||t.prepend(ee.decl({prop:"content",value:"var(--tw-content)"}))}),"&::before")),r("after",({container:e})=>(e.walkRules(t=>{let i=!1;t.walkDecls("content",()=>{i=!0}),i||t.prepend(ee.decl({prop:"content",value:"var(--tw-content)"}))}),"&::after"))},pseudoClassVariants:({addVariant:r,matchVariant:e,config:t,prefix:i})=>{let n=[["first","&:first-child"],["last","&:last-child"],["only","&:only-child"],["odd","&:nth-child(odd)"],["even","&:nth-child(even)"],"first-of-type","last-of-type","only-of-type",["visited",({container:a})=>(Jn(a,["--tw-text-opacity","--tw-border-opacity","--tw-bg-opacity"]),"&:visited")],"target",["open","&[open]"],"default","checked","indeterminate","placeholder-shown","autofill","optional","required","valid","invalid","in-range","out-of-range","read-only","empty","focus-within",["hover",we(t(),"hoverOnlyWhenSupported")?"@media (hover: hover) and (pointer: fine) { &:hover }":"&:hover"],"focus","focus-visible","active","enabled","disabled"].map(a=>Array.isArray(a)?a:[a,`&:${a}`]);for(let[a,o]of n)r(a,l=>typeof o=="function"?o(l):o);let s={group:(a,{modifier:o})=>o?[`:merge(${i(".group")}\\/${Te(o)})`," &"]:[`:merge(${i(".group")})`," &"],peer:(a,{modifier:o})=>o?[`:merge(${i(".peer")}\\/${Te(o)})`," ~ &"]:[`:merge(${i(".peer")})`," ~ &"]};for(let[a,o]of Object.entries(s))e(a,(l="",c)=>{let f=K(typeof l=="function"?l(c):l);f.includes("&")||(f="&"+f);let[d,p]=o("",c),h=null,b=null,v=0;for(let y=0;y{r("ltr",'&:where([dir="ltr"], [dir="ltr"] *)'),r("rtl",'&:where([dir="rtl"], [dir="rtl"] *)')},reducedMotionVariants:({addVariant:r})=>{r("motion-safe","@media (prefers-reduced-motion: no-preference)"),r("motion-reduce","@media (prefers-reduced-motion: reduce)")},darkVariants:({config:r,addVariant:e})=>{let[t,i=".dark"]=[].concat(r("darkMode","media"));if(t===!1&&(t="media",G.warn("darkmode-false",["The `darkMode` option in your Tailwind CSS configuration is set to `false`, which now behaves the same as `media`.","Change `darkMode` to `media` or remove it entirely.","https://tailwindcss.com/docs/upgrade-guide#remove-dark-mode-configuration"])),t==="variant"){let n;if(Array.isArray(i)||typeof i=="function"?n=i:typeof i=="string"&&(n=[i]),Array.isArray(n))for(let s of n)s===".dark"?(t=!1,G.warn("darkmode-variant-without-selector",["When using `variant` for `darkMode`, you must provide a selector.",'Example: `darkMode: ["variant", ".your-selector &"]`'])):s.includes("&")||(t=!1,G.warn("darkmode-variant-without-ampersand",["When using `variant` for `darkMode`, your selector must contain `&`.",'Example `darkMode: ["variant", ".your-selector &"]`']));i=n}t==="selector"?e("dark",`&:where(${i}, ${i} *)`):t==="media"?e("dark","@media (prefers-color-scheme: dark)"):t==="variant"?e("dark",i):t==="class"&&e("dark",`&:is(${i} *)`)},printVariant:({addVariant:r})=>{r("print","@media print")},screenVariants:({theme:r,addVariant:e,matchVariant:t})=>{let i=r("screens")??{},n=Object.values(i).every(w=>typeof w=="string"),s=Rt(r("screens")),a=new Set([]);function o(w){return w.match(/(\D+)$/)?.[1]??"(none)"}function l(w){w!==void 0&&a.add(o(w))}function c(w){return l(w),a.size===1}for(let w of s)for(let k of w.values)l(k.min),l(k.max);let f=a.size<=1;function d(w){return Object.fromEntries(s.filter(k=>Kn(k).result).map(k=>{let{min:S,max:E}=k.values[0];if(w==="min"&&S!==void 0)return k;if(w==="min"&&E!==void 0)return{...k,not:!k.not};if(w==="max"&&E!==void 0)return k;if(w==="max"&&S!==void 0)return{...k,not:!k.not}}).map(k=>[k.name,k]))}function p(w){return(k,S)=>hh(w,k.value,S.value)}let h=p("max"),b=p("min");function v(w){return k=>{if(n)if(f){if(typeof k=="string"&&!c(k))return G.warn("minmax-have-mixed-units",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units."]),[]}else return G.warn("mixed-screen-units",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units."]),[];else return G.warn("complex-screen-config",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing objects."]),[];return[`@media ${Tt(Xn(k,w))}`]}}t("max",v("max"),{sort:h,values:n?d("max"):{}});let y="min-screens";for(let w of s)e(w.name,`@media ${Tt(w)}`,{id:y,sort:n&&f?b:void 0,value:w});t("min",v("min"),{id:y,sort:b})},supportsVariants:({matchVariant:r,theme:e})=>{r("supports",(t="")=>{let i=K(t),n=/^\w*\s*\(/.test(i);return i=n?i.replace(/\b(and|or|not)\b/g," $1 "):i,n?`@supports ${i}`:(i.includes(":")||(i=`${i}: var(--tw)`),i.startsWith("(")&&i.endsWith(")")||(i=`(${i})`),`@supports ${i}`)},{values:e("supports")??{}})},hasVariants:({matchVariant:r,prefix:e})=>{r("has",t=>`&:has(${K(t)})`,{values:{},[Pt]:{respectPrefix:!1}}),r("group-has",(t,{modifier:i})=>i?`:merge(${e(".group")}\\/${i}):has(${K(t)}) &`:`:merge(${e(".group")}):has(${K(t)}) &`,{values:{},[Pt]:{respectPrefix:!1}}),r("peer-has",(t,{modifier:i})=>i?`:merge(${e(".peer")}\\/${i}):has(${K(t)}) ~ &`:`:merge(${e(".peer")}):has(${K(t)}) ~ &`,{values:{},[Pt]:{respectPrefix:!1}})},ariaVariants:({matchVariant:r,theme:e})=>{r("aria",t=>`&[aria-${Ye(K(t))}]`,{values:e("aria")??{}}),r("group-aria",(t,{modifier:i})=>i?`:merge(.group\\/${i})[aria-${Ye(K(t))}] &`:`:merge(.group)[aria-${Ye(K(t))}] &`,{values:e("aria")??{}}),r("peer-aria",(t,{modifier:i})=>i?`:merge(.peer\\/${i})[aria-${Ye(K(t))}] ~ &`:`:merge(.peer)[aria-${Ye(K(t))}] ~ &`,{values:e("aria")??{}})},dataVariants:({matchVariant:r,theme:e})=>{r("data",t=>`&[data-${Ye(K(t))}]`,{values:e("data")??{}}),r("group-data",(t,{modifier:i})=>i?`:merge(.group\\/${i})[data-${Ye(K(t))}] &`:`:merge(.group)[data-${Ye(K(t))}] &`,{values:e("data")??{}}),r("peer-data",(t,{modifier:i})=>i?`:merge(.peer\\/${i})[data-${Ye(K(t))}] ~ &`:`:merge(.peer)[data-${Ye(K(t))}] ~ &`,{values:e("data")??{}})},orientationVariants:({addVariant:r})=>{r("portrait","@media (orientation: portrait)"),r("landscape","@media (orientation: landscape)")},prefersContrastVariants:({addVariant:r})=>{r("contrast-more","@media (prefers-contrast: more)"),r("contrast-less","@media (prefers-contrast: less)")},forcedColorsVariants:({addVariant:r})=>{r("forced-colors","@media (forced-colors: active)")}},Xe=["translate(var(--tw-translate-x), var(--tw-translate-y))","rotate(var(--tw-rotate))","skewX(var(--tw-skew-x))","skewY(var(--tw-skew-y))","scaleX(var(--tw-scale-x))","scaleY(var(--tw-scale-y))"].join(" "),nt=["var(--tw-blur)","var(--tw-brightness)","var(--tw-contrast)","var(--tw-grayscale)","var(--tw-hue-rotate)","var(--tw-invert)","var(--tw-saturate)","var(--tw-sepia)","var(--tw-drop-shadow)"].join(" "),ge=["var(--tw-backdrop-blur)","var(--tw-backdrop-brightness)","var(--tw-backdrop-contrast)","var(--tw-backdrop-grayscale)","var(--tw-backdrop-hue-rotate)","var(--tw-backdrop-invert)","var(--tw-backdrop-opacity)","var(--tw-backdrop-saturate)","var(--tw-backdrop-sepia)"].join(" "),yh={preflight:({addBase:r})=>{let e=ee.parse(`*,::after,::before{box-sizing:border-box;border-width:0;border-style:solid;border-color:theme('borderColor.DEFAULT', currentColor)}::after,::before{--tw-content:''}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:theme('fontFamily.sans', ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:theme('fontFamily.sans[1].fontFeatureSettings', normal);font-variation-settings:theme('fontFamily.sans[1].fontVariationSettings', normal);-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:theme('fontFamily.mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:theme('fontFamily.mono[1].fontFeatureSettings', normal);font-variation-settings:theme('fontFamily.mono[1].fontVariationSettings', normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:theme('colors.gray.4', #9ca3af)}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}`);r([ee.comment({text:`! tailwindcss v${dh} | MIT License | https://tailwindcss.com`}),...e.nodes])},container:(()=>{function r(t=[]){return t.flatMap(i=>i.values.map(n=>n.min)).filter(i=>i!==void 0)}function e(t,i,n){if(typeof n=="undefined")return[];if(!(typeof n=="object"&&n!==null))return[{screen:"DEFAULT",minWidth:0,padding:n}];let s=[];n.DEFAULT&&s.push({screen:"DEFAULT",minWidth:0,padding:n.DEFAULT});for(let a of t)for(let o of i)for(let{min:l}of o.values)l===a&&s.push({minWidth:a,padding:n[o.name]});return s}return function({addComponents:t,theme:i}){let n=Rt(i("container.screens",i("screens"))),s=r(n),a=e(s,n,i("container.padding")),o=c=>{let f=a.find(d=>d.minWidth===c);return f?{paddingRight:f.padding,paddingLeft:f.padding}:{}},l=Array.from(new Set(s.slice().sort((c,f)=>parseInt(c)-parseInt(f)))).map(c=>({[`@media (min-width: ${c})`]:{".container":{"max-width":c,...o(c)}}}));t([{".container":Object.assign({width:"100%"},i("container.center",!1)?{marginRight:"auto",marginLeft:"auto"}:{},o(0))},...l])}})(),accessibility:({addUtilities:r})=>{r({".sr-only":{position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"},".not-sr-only":{position:"static",width:"auto",height:"auto",padding:"0",margin:"0",overflow:"visible",clip:"auto",whiteSpace:"normal"}})},pointerEvents:({addUtilities:r})=>{r({".pointer-events-none":{"pointer-events":"none"},".pointer-events-auto":{"pointer-events":"auto"}})},visibility:({addUtilities:r})=>{r({".visible":{visibility:"visible"},".invisible":{visibility:"hidden"},".collapse":{visibility:"collapse"}})},position:({addUtilities:r})=>{r({".static":{position:"static"},".fixed":{position:"fixed"},".absolute":{position:"absolute"},".relative":{position:"relative"},".sticky":{position:"sticky"}})},inset:L("inset",[["inset",["inset"]],[["inset-x",["left","right"]],["inset-y",["top","bottom"]]],[["start",["inset-inline-start"]],["end",["inset-inline-end"]],["top",["top"]],["right",["right"]],["bottom",["bottom"]],["left",["left"]]]],{supportsNegativeValues:!0}),isolation:({addUtilities:r})=>{r({".isolate":{isolation:"isolate"},".isolation-auto":{isolation:"auto"}})},zIndex:L("zIndex",[["z",["zIndex"]]],{supportsNegativeValues:!0}),order:L("order",void 0,{supportsNegativeValues:!0}),gridColumn:L("gridColumn",[["col",["gridColumn"]]]),gridColumnStart:L("gridColumnStart",[["col-start",["gridColumnStart"]]],{supportsNegativeValues:!0}),gridColumnEnd:L("gridColumnEnd",[["col-end",["gridColumnEnd"]]],{supportsNegativeValues:!0}),gridRow:L("gridRow",[["row",["gridRow"]]]),gridRowStart:L("gridRowStart",[["row-start",["gridRowStart"]]],{supportsNegativeValues:!0}),gridRowEnd:L("gridRowEnd",[["row-end",["gridRowEnd"]]],{supportsNegativeValues:!0}),float:({addUtilities:r})=>{r({".float-start":{float:"inline-start"},".float-end":{float:"inline-end"},".float-right":{float:"right"},".float-left":{float:"left"},".float-none":{float:"none"}})},clear:({addUtilities:r})=>{r({".clear-start":{clear:"inline-start"},".clear-end":{clear:"inline-end"},".clear-left":{clear:"left"},".clear-right":{clear:"right"},".clear-both":{clear:"both"},".clear-none":{clear:"none"}})},margin:L("margin",[["m",["margin"]],[["mx",["margin-left","margin-right"]],["my",["margin-top","margin-bottom"]]],[["ms",["margin-inline-start"]],["me",["margin-inline-end"]],["mt",["margin-top"]],["mr",["margin-right"]],["mb",["margin-bottom"]],["ml",["margin-left"]]]],{supportsNegativeValues:!0}),boxSizing:({addUtilities:r})=>{r({".box-border":{"box-sizing":"border-box"},".box-content":{"box-sizing":"content-box"}})},lineClamp:({matchUtilities:r,addUtilities:e,theme:t})=>{r({"line-clamp":i=>({overflow:"hidden",display:"-webkit-box","-webkit-box-orient":"vertical","-webkit-line-clamp":`${i}`})},{values:t("lineClamp")}),e({".line-clamp-none":{overflow:"visible",display:"block","-webkit-box-orient":"horizontal","-webkit-line-clamp":"none"}})},display:({addUtilities:r})=>{r({".block":{display:"block"},".inline-block":{display:"inline-block"},".inline":{display:"inline"},".flex":{display:"flex"},".inline-flex":{display:"inline-flex"},".table":{display:"table"},".inline-table":{display:"inline-table"},".table-caption":{display:"table-caption"},".table-cell":{display:"table-cell"},".table-column":{display:"table-column"},".table-column-group":{display:"table-column-group"},".table-footer-group":{display:"table-footer-group"},".table-header-group":{display:"table-header-group"},".table-row-group":{display:"table-row-group"},".table-row":{display:"table-row"},".flow-root":{display:"flow-root"},".grid":{display:"grid"},".inline-grid":{display:"inline-grid"},".contents":{display:"contents"},".list-item":{display:"list-item"},".hidden":{display:"none"}})},aspectRatio:L("aspectRatio",[["aspect",["aspect-ratio"]]]),size:L("size",[["size",["width","height"]]]),height:L("height",[["h",["height"]]]),maxHeight:L("maxHeight",[["max-h",["maxHeight"]]]),minHeight:L("minHeight",[["min-h",["minHeight"]]]),width:L("width",[["w",["width"]]]),minWidth:L("minWidth",[["min-w",["minWidth"]]]),maxWidth:L("maxWidth",[["max-w",["maxWidth"]]]),flex:L("flex"),flexShrink:L("flexShrink",[["flex-shrink",["flex-shrink"]],["shrink",["flex-shrink"]]]),flexGrow:L("flexGrow",[["flex-grow",["flex-grow"]],["grow",["flex-grow"]]]),flexBasis:L("flexBasis",[["basis",["flex-basis"]]]),tableLayout:({addUtilities:r})=>{r({".table-auto":{"table-layout":"auto"},".table-fixed":{"table-layout":"fixed"}})},captionSide:({addUtilities:r})=>{r({".caption-top":{"caption-side":"top"},".caption-bottom":{"caption-side":"bottom"}})},borderCollapse:({addUtilities:r})=>{r({".border-collapse":{"border-collapse":"collapse"},".border-separate":{"border-collapse":"separate"}})},borderSpacing:({addDefaults:r,matchUtilities:e,theme:t})=>{r("border-spacing",{"--tw-border-spacing-x":0,"--tw-border-spacing-y":0}),e({"border-spacing":i=>({"--tw-border-spacing-x":i,"--tw-border-spacing-y":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"}),"border-spacing-x":i=>({"--tw-border-spacing-x":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"}),"border-spacing-y":i=>({"--tw-border-spacing-y":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"})},{values:t("borderSpacing")})},transformOrigin:L("transformOrigin",[["origin",["transformOrigin"]]]),translate:L("translate",[[["translate-x",[["@defaults transform",{}],"--tw-translate-x",["transform",Xe]]],["translate-y",[["@defaults transform",{}],"--tw-translate-y",["transform",Xe]]]]],{supportsNegativeValues:!0}),rotate:L("rotate",[["rotate",[["@defaults transform",{}],"--tw-rotate",["transform",Xe]]]],{supportsNegativeValues:!0}),skew:L("skew",[[["skew-x",[["@defaults transform",{}],"--tw-skew-x",["transform",Xe]]],["skew-y",[["@defaults transform",{}],"--tw-skew-y",["transform",Xe]]]]],{supportsNegativeValues:!0}),scale:L("scale",[["scale",[["@defaults transform",{}],"--tw-scale-x","--tw-scale-y",["transform",Xe]]],[["scale-x",[["@defaults transform",{}],"--tw-scale-x",["transform",Xe]]],["scale-y",[["@defaults transform",{}],"--tw-scale-y",["transform",Xe]]]]],{supportsNegativeValues:!0}),transform:({addDefaults:r,addUtilities:e})=>{r("transform",{"--tw-translate-x":"0","--tw-translate-y":"0","--tw-rotate":"0","--tw-skew-x":"0","--tw-skew-y":"0","--tw-scale-x":"1","--tw-scale-y":"1"}),e({".transform":{"@defaults transform":{},transform:Xe},".transform-cpu":{transform:Xe},".transform-gpu":{transform:Xe.replace("translate(var(--tw-translate-x), var(--tw-translate-y))","translate3d(var(--tw-translate-x), var(--tw-translate-y), 0)")},".transform-none":{transform:"none"}})},animation:({matchUtilities:r,theme:e,config:t})=>{let i=s=>Te(t("prefix")+s),n=Object.fromEntries(Object.entries(e("keyframes")??{}).map(([s,a])=>[s,{[`@keyframes ${i(s)}`]:a}]));r({animate:s=>{let a=Mo(s);return[...a.flatMap(o=>n[o.name]),{animation:a.map(({name:o,value:l})=>o===void 0||n[o]===void 0?l:l.replace(o,i(o))).join(", ")}]}},{values:e("animation")})},cursor:L("cursor"),touchAction:({addDefaults:r,addUtilities:e})=>{r("touch-action",{"--tw-pan-x":" ","--tw-pan-y":" ","--tw-pinch-zoom":" "});let t="var(--tw-pan-x) var(--tw-pan-y) var(--tw-pinch-zoom)";e({".touch-auto":{"touch-action":"auto"},".touch-none":{"touch-action":"none"},".touch-pan-x":{"@defaults touch-action":{},"--tw-pan-x":"pan-x","touch-action":t},".touch-pan-left":{"@defaults touch-action":{},"--tw-pan-x":"pan-left","touch-action":t},".touch-pan-right":{"@defaults touch-action":{},"--tw-pan-x":"pan-right","touch-action":t},".touch-pan-y":{"@defaults touch-action":{},"--tw-pan-y":"pan-y","touch-action":t},".touch-pan-up":{"@defaults touch-action":{},"--tw-pan-y":"pan-up","touch-action":t},".touch-pan-down":{"@defaults touch-action":{},"--tw-pan-y":"pan-down","touch-action":t},".touch-pinch-zoom":{"@defaults touch-action":{},"--tw-pinch-zoom":"pinch-zoom","touch-action":t},".touch-manipulation":{"touch-action":"manipulation"}})},userSelect:({addUtilities:r})=>{r({".select-none":{"user-select":"none"},".select-text":{"user-select":"text"},".select-all":{"user-select":"all"},".select-auto":{"user-select":"auto"}})},resize:({addUtilities:r})=>{r({".resize-none":{resize:"none"},".resize-y":{resize:"vertical"},".resize-x":{resize:"horizontal"},".resize":{resize:"both"}})},scrollSnapType:({addDefaults:r,addUtilities:e})=>{r("scroll-snap-type",{"--tw-scroll-snap-strictness":"proximity"}),e({".snap-none":{"scroll-snap-type":"none"},".snap-x":{"@defaults scroll-snap-type":{},"scroll-snap-type":"x var(--tw-scroll-snap-strictness)"},".snap-y":{"@defaults scroll-snap-type":{},"scroll-snap-type":"y var(--tw-scroll-snap-strictness)"},".snap-both":{"@defaults scroll-snap-type":{},"scroll-snap-type":"both var(--tw-scroll-snap-strictness)"},".snap-mandatory":{"--tw-scroll-snap-strictness":"mandatory"},".snap-proximity":{"--tw-scroll-snap-strictness":"proximity"}})},scrollSnapAlign:({addUtilities:r})=>{r({".snap-start":{"scroll-snap-align":"start"},".snap-end":{"scroll-snap-align":"end"},".snap-center":{"scroll-snap-align":"center"},".snap-align-none":{"scroll-snap-align":"none"}})},scrollSnapStop:({addUtilities:r})=>{r({".snap-normal":{"scroll-snap-stop":"normal"},".snap-always":{"scroll-snap-stop":"always"}})},scrollMargin:L("scrollMargin",[["scroll-m",["scroll-margin"]],[["scroll-mx",["scroll-margin-left","scroll-margin-right"]],["scroll-my",["scroll-margin-top","scroll-margin-bottom"]]],[["scroll-ms",["scroll-margin-inline-start"]],["scroll-me",["scroll-margin-inline-end"]],["scroll-mt",["scroll-margin-top"]],["scroll-mr",["scroll-margin-right"]],["scroll-mb",["scroll-margin-bottom"]],["scroll-ml",["scroll-margin-left"]]]],{supportsNegativeValues:!0}),scrollPadding:L("scrollPadding",[["scroll-p",["scroll-padding"]],[["scroll-px",["scroll-padding-left","scroll-padding-right"]],["scroll-py",["scroll-padding-top","scroll-padding-bottom"]]],[["scroll-ps",["scroll-padding-inline-start"]],["scroll-pe",["scroll-padding-inline-end"]],["scroll-pt",["scroll-padding-top"]],["scroll-pr",["scroll-padding-right"]],["scroll-pb",["scroll-padding-bottom"]],["scroll-pl",["scroll-padding-left"]]]]),listStylePosition:({addUtilities:r})=>{r({".list-inside":{"list-style-position":"inside"},".list-outside":{"list-style-position":"outside"}})},listStyleType:L("listStyleType",[["list",["listStyleType"]]]),listStyleImage:L("listStyleImage",[["list-image",["listStyleImage"]]]),appearance:({addUtilities:r})=>{r({".appearance-none":{appearance:"none"},".appearance-auto":{appearance:"auto"}})},columns:L("columns",[["columns",["columns"]]]),breakBefore:({addUtilities:r})=>{r({".break-before-auto":{"break-before":"auto"},".break-before-avoid":{"break-before":"avoid"},".break-before-all":{"break-before":"all"},".break-before-avoid-page":{"break-before":"avoid-page"},".break-before-page":{"break-before":"page"},".break-before-left":{"break-before":"left"},".break-before-right":{"break-before":"right"},".break-before-column":{"break-before":"column"}})},breakInside:({addUtilities:r})=>{r({".break-inside-auto":{"break-inside":"auto"},".break-inside-avoid":{"break-inside":"avoid"},".break-inside-avoid-page":{"break-inside":"avoid-page"},".break-inside-avoid-column":{"break-inside":"avoid-column"}})},breakAfter:({addUtilities:r})=>{r({".break-after-auto":{"break-after":"auto"},".break-after-avoid":{"break-after":"avoid"},".break-after-all":{"break-after":"all"},".break-after-avoid-page":{"break-after":"avoid-page"},".break-after-page":{"break-after":"page"},".break-after-left":{"break-after":"left"},".break-after-right":{"break-after":"right"},".break-after-column":{"break-after":"column"}})},gridAutoColumns:L("gridAutoColumns",[["auto-cols",["gridAutoColumns"]]]),gridAutoFlow:({addUtilities:r})=>{r({".grid-flow-row":{gridAutoFlow:"row"},".grid-flow-col":{gridAutoFlow:"column"},".grid-flow-dense":{gridAutoFlow:"dense"},".grid-flow-row-dense":{gridAutoFlow:"row dense"},".grid-flow-col-dense":{gridAutoFlow:"column dense"}})},gridAutoRows:L("gridAutoRows",[["auto-rows",["gridAutoRows"]]]),gridTemplateColumns:L("gridTemplateColumns",[["grid-cols",["gridTemplateColumns"]]]),gridTemplateRows:L("gridTemplateRows",[["grid-rows",["gridTemplateRows"]]]),flexDirection:({addUtilities:r})=>{r({".flex-row":{"flex-direction":"row"},".flex-row-reverse":{"flex-direction":"row-reverse"},".flex-col":{"flex-direction":"column"},".flex-col-reverse":{"flex-direction":"column-reverse"}})},flexWrap:({addUtilities:r})=>{r({".flex-wrap":{"flex-wrap":"wrap"},".flex-wrap-reverse":{"flex-wrap":"wrap-reverse"},".flex-nowrap":{"flex-wrap":"nowrap"}})},placeContent:({addUtilities:r})=>{r({".place-content-center":{"place-content":"center"},".place-content-start":{"place-content":"start"},".place-content-end":{"place-content":"end"},".place-content-between":{"place-content":"space-between"},".place-content-around":{"place-content":"space-around"},".place-content-evenly":{"place-content":"space-evenly"},".place-content-baseline":{"place-content":"baseline"},".place-content-stretch":{"place-content":"stretch"}})},placeItems:({addUtilities:r})=>{r({".place-items-start":{"place-items":"start"},".place-items-end":{"place-items":"end"},".place-items-center":{"place-items":"center"},".place-items-baseline":{"place-items":"baseline"},".place-items-stretch":{"place-items":"stretch"}})},alignContent:({addUtilities:r})=>{r({".content-normal":{"align-content":"normal"},".content-center":{"align-content":"center"},".content-start":{"align-content":"flex-start"},".content-end":{"align-content":"flex-end"},".content-between":{"align-content":"space-between"},".content-around":{"align-content":"space-around"},".content-evenly":{"align-content":"space-evenly"},".content-baseline":{"align-content":"baseline"},".content-stretch":{"align-content":"stretch"}})},alignItems:({addUtilities:r})=>{r({".items-start":{"align-items":"flex-start"},".items-end":{"align-items":"flex-end"},".items-center":{"align-items":"center"},".items-baseline":{"align-items":"baseline"},".items-stretch":{"align-items":"stretch"}})},justifyContent:({addUtilities:r})=>{r({".justify-normal":{"justify-content":"normal"},".justify-start":{"justify-content":"flex-start"},".justify-end":{"justify-content":"flex-end"},".justify-center":{"justify-content":"center"},".justify-between":{"justify-content":"space-between"},".justify-around":{"justify-content":"space-around"},".justify-evenly":{"justify-content":"space-evenly"},".justify-stretch":{"justify-content":"stretch"}})},justifyItems:({addUtilities:r})=>{r({".justify-items-start":{"justify-items":"start"},".justify-items-end":{"justify-items":"end"},".justify-items-center":{"justify-items":"center"},".justify-items-stretch":{"justify-items":"stretch"}})},gap:L("gap",[["gap",["gap"]],[["gap-x",["columnGap"]],["gap-y",["rowGap"]]]]),space:({matchUtilities:r,addUtilities:e,theme:t})=>{r({"space-x":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"--tw-space-x-reverse":"0","margin-right":`calc(${i} * var(--tw-space-x-reverse))`,"margin-left":`calc(${i} * calc(1 - var(--tw-space-x-reverse)))`}}),"space-y":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"--tw-space-y-reverse":"0","margin-top":`calc(${i} * calc(1 - var(--tw-space-y-reverse)))`,"margin-bottom":`calc(${i} * var(--tw-space-y-reverse))`}})},{values:t("space"),supportsNegativeValues:!0}),e({".space-y-reverse > :not([hidden]) ~ :not([hidden])":{"--tw-space-y-reverse":"1"},".space-x-reverse > :not([hidden]) ~ :not([hidden])":{"--tw-space-x-reverse":"1"}})},divideWidth:({matchUtilities:r,addUtilities:e,theme:t})=>{r({"divide-x":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-x-reverse":"0","border-right-width":`calc(${i} * var(--tw-divide-x-reverse))`,"border-left-width":`calc(${i} * calc(1 - var(--tw-divide-x-reverse)))`}}),"divide-y":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-y-reverse":"0","border-top-width":`calc(${i} * calc(1 - var(--tw-divide-y-reverse)))`,"border-bottom-width":`calc(${i} * var(--tw-divide-y-reverse))`}})},{values:t("divideWidth"),type:["line-width","length","any"]}),e({".divide-y-reverse > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-y-reverse":"1"},".divide-x-reverse > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-x-reverse":"1"}})},divideStyle:({addUtilities:r})=>{r({".divide-solid > :not([hidden]) ~ :not([hidden])":{"border-style":"solid"},".divide-dashed > :not([hidden]) ~ :not([hidden])":{"border-style":"dashed"},".divide-dotted > :not([hidden]) ~ :not([hidden])":{"border-style":"dotted"},".divide-double > :not([hidden]) ~ :not([hidden])":{"border-style":"double"},".divide-none > :not([hidden]) ~ :not([hidden])":{"border-style":"none"}})},divideColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({divide:i=>t("divideOpacity")?{["& > :not([hidden]) ~ :not([hidden])"]:Ae({color:i,property:"border-color",variable:"--tw-divide-opacity"})}:{["& > :not([hidden]) ~ :not([hidden])"]:{"border-color":X(i)}}},{values:(({DEFAULT:i,...n})=>n)(xe(e("divideColor"))),type:["color","any"]})},divideOpacity:({matchUtilities:r,theme:e})=>{r({"divide-opacity":t=>({["& > :not([hidden]) ~ :not([hidden])"]:{"--tw-divide-opacity":t}})},{values:e("divideOpacity")})},placeSelf:({addUtilities:r})=>{r({".place-self-auto":{"place-self":"auto"},".place-self-start":{"place-self":"start"},".place-self-end":{"place-self":"end"},".place-self-center":{"place-self":"center"},".place-self-stretch":{"place-self":"stretch"}})},alignSelf:({addUtilities:r})=>{r({".self-auto":{"align-self":"auto"},".self-start":{"align-self":"flex-start"},".self-end":{"align-self":"flex-end"},".self-center":{"align-self":"center"},".self-stretch":{"align-self":"stretch"},".self-baseline":{"align-self":"baseline"}})},justifySelf:({addUtilities:r})=>{r({".justify-self-auto":{"justify-self":"auto"},".justify-self-start":{"justify-self":"start"},".justify-self-end":{"justify-self":"end"},".justify-self-center":{"justify-self":"center"},".justify-self-stretch":{"justify-self":"stretch"}})},overflow:({addUtilities:r})=>{r({".overflow-auto":{overflow:"auto"},".overflow-hidden":{overflow:"hidden"},".overflow-clip":{overflow:"clip"},".overflow-visible":{overflow:"visible"},".overflow-scroll":{overflow:"scroll"},".overflow-x-auto":{"overflow-x":"auto"},".overflow-y-auto":{"overflow-y":"auto"},".overflow-x-hidden":{"overflow-x":"hidden"},".overflow-y-hidden":{"overflow-y":"hidden"},".overflow-x-clip":{"overflow-x":"clip"},".overflow-y-clip":{"overflow-y":"clip"},".overflow-x-visible":{"overflow-x":"visible"},".overflow-y-visible":{"overflow-y":"visible"},".overflow-x-scroll":{"overflow-x":"scroll"},".overflow-y-scroll":{"overflow-y":"scroll"}})},overscrollBehavior:({addUtilities:r})=>{r({".overscroll-auto":{"overscroll-behavior":"auto"},".overscroll-contain":{"overscroll-behavior":"contain"},".overscroll-none":{"overscroll-behavior":"none"},".overscroll-y-auto":{"overscroll-behavior-y":"auto"},".overscroll-y-contain":{"overscroll-behavior-y":"contain"},".overscroll-y-none":{"overscroll-behavior-y":"none"},".overscroll-x-auto":{"overscroll-behavior-x":"auto"},".overscroll-x-contain":{"overscroll-behavior-x":"contain"},".overscroll-x-none":{"overscroll-behavior-x":"none"}})},scrollBehavior:({addUtilities:r})=>{r({".scroll-auto":{"scroll-behavior":"auto"},".scroll-smooth":{"scroll-behavior":"smooth"}})},textOverflow:({addUtilities:r})=>{r({".truncate":{overflow:"hidden","text-overflow":"ellipsis","white-space":"nowrap"},".overflow-ellipsis":{"text-overflow":"ellipsis"},".text-ellipsis":{"text-overflow":"ellipsis"},".text-clip":{"text-overflow":"clip"}})},hyphens:({addUtilities:r})=>{r({".hyphens-none":{hyphens:"none"},".hyphens-manual":{hyphens:"manual"},".hyphens-auto":{hyphens:"auto"}})},whitespace:({addUtilities:r})=>{r({".whitespace-normal":{"white-space":"normal"},".whitespace-nowrap":{"white-space":"nowrap"},".whitespace-pre":{"white-space":"pre"},".whitespace-pre-line":{"white-space":"pre-line"},".whitespace-pre-wrap":{"white-space":"pre-wrap"},".whitespace-break-spaces":{"white-space":"break-spaces"}})},textWrap:({addUtilities:r})=>{r({".text-wrap":{"text-wrap":"wrap"},".text-nowrap":{"text-wrap":"nowrap"},".text-balance":{"text-wrap":"balance"},".text-pretty":{"text-wrap":"pretty"}})},wordBreak:({addUtilities:r})=>{r({".break-normal":{"overflow-wrap":"normal","word-break":"normal"},".break-words":{"overflow-wrap":"break-word"},".break-all":{"word-break":"break-all"},".break-keep":{"word-break":"keep-all"}})},borderRadius:L("borderRadius",[["rounded",["border-radius"]],[["rounded-s",["border-start-start-radius","border-end-start-radius"]],["rounded-e",["border-start-end-radius","border-end-end-radius"]],["rounded-t",["border-top-left-radius","border-top-right-radius"]],["rounded-r",["border-top-right-radius","border-bottom-right-radius"]],["rounded-b",["border-bottom-right-radius","border-bottom-left-radius"]],["rounded-l",["border-top-left-radius","border-bottom-left-radius"]]],[["rounded-ss",["border-start-start-radius"]],["rounded-se",["border-start-end-radius"]],["rounded-ee",["border-end-end-radius"]],["rounded-es",["border-end-start-radius"]],["rounded-tl",["border-top-left-radius"]],["rounded-tr",["border-top-right-radius"]],["rounded-br",["border-bottom-right-radius"]],["rounded-bl",["border-bottom-left-radius"]]]]),borderWidth:L("borderWidth",[["border",[["@defaults border-width",{}],"border-width"]],[["border-x",[["@defaults border-width",{}],"border-left-width","border-right-width"]],["border-y",[["@defaults border-width",{}],"border-top-width","border-bottom-width"]]],[["border-s",[["@defaults border-width",{}],"border-inline-start-width"]],["border-e",[["@defaults border-width",{}],"border-inline-end-width"]],["border-t",[["@defaults border-width",{}],"border-top-width"]],["border-r",[["@defaults border-width",{}],"border-right-width"]],["border-b",[["@defaults border-width",{}],"border-bottom-width"]],["border-l",[["@defaults border-width",{}],"border-left-width"]]]],{type:["line-width","length"]}),borderStyle:({addUtilities:r})=>{r({".border-solid":{"border-style":"solid"},".border-dashed":{"border-style":"dashed"},".border-dotted":{"border-style":"dotted"},".border-double":{"border-style":"double"},".border-hidden":{"border-style":"hidden"},".border-none":{"border-style":"none"}})},borderColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({border:i=>t("borderOpacity")?Ae({color:i,property:"border-color",variable:"--tw-border-opacity"}):{"border-color":X(i)}},{values:(({DEFAULT:i,...n})=>n)(xe(e("borderColor"))),type:["color","any"]}),r({"border-x":i=>t("borderOpacity")?Ae({color:i,property:["border-left-color","border-right-color"],variable:"--tw-border-opacity"}):{"border-left-color":X(i),"border-right-color":X(i)},"border-y":i=>t("borderOpacity")?Ae({color:i,property:["border-top-color","border-bottom-color"],variable:"--tw-border-opacity"}):{"border-top-color":X(i),"border-bottom-color":X(i)}},{values:(({DEFAULT:i,...n})=>n)(xe(e("borderColor"))),type:["color","any"]}),r({"border-s":i=>t("borderOpacity")?Ae({color:i,property:"border-inline-start-color",variable:"--tw-border-opacity"}):{"border-inline-start-color":X(i)},"border-e":i=>t("borderOpacity")?Ae({color:i,property:"border-inline-end-color",variable:"--tw-border-opacity"}):{"border-inline-end-color":X(i)},"border-t":i=>t("borderOpacity")?Ae({color:i,property:"border-top-color",variable:"--tw-border-opacity"}):{"border-top-color":X(i)},"border-r":i=>t("borderOpacity")?Ae({color:i,property:"border-right-color",variable:"--tw-border-opacity"}):{"border-right-color":X(i)},"border-b":i=>t("borderOpacity")?Ae({color:i,property:"border-bottom-color",variable:"--tw-border-opacity"}):{"border-bottom-color":X(i)},"border-l":i=>t("borderOpacity")?Ae({color:i,property:"border-left-color",variable:"--tw-border-opacity"}):{"border-left-color":X(i)}},{values:(({DEFAULT:i,...n})=>n)(xe(e("borderColor"))),type:["color","any"]})},borderOpacity:L("borderOpacity",[["border-opacity",["--tw-border-opacity"]]]),backgroundColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({bg:i=>t("backgroundOpacity")?Ae({color:i,property:"background-color",variable:"--tw-bg-opacity"}):{"background-color":X(i)}},{values:xe(e("backgroundColor")),type:["color","any"]})},backgroundOpacity:L("backgroundOpacity",[["bg-opacity",["--tw-bg-opacity"]]]),backgroundImage:L("backgroundImage",[["bg",["background-image"]]],{type:["lookup","image","url"]}),gradientColorStops:(()=>{function r(e){return Je(e,0,"rgb(255 255 255 / 0)")}return function({matchUtilities:e,theme:t,addDefaults:i}){i("gradient-color-stops",{"--tw-gradient-from-position":" ","--tw-gradient-via-position":" ","--tw-gradient-to-position":" "});let n={values:xe(t("gradientColorStops")),type:["color","any"]},s={values:t("gradientColorStopPositions"),type:["length","percentage"]};e({from:a=>{let o=r(a);return{"@defaults gradient-color-stops":{},"--tw-gradient-from":`${X(a)} var(--tw-gradient-from-position)`,"--tw-gradient-to":`${o} var(--tw-gradient-to-position)`,"--tw-gradient-stops":"var(--tw-gradient-from), var(--tw-gradient-to)"}}},n),e({from:a=>({"--tw-gradient-from-position":a})},s),e({via:a=>{let o=r(a);return{"@defaults gradient-color-stops":{},"--tw-gradient-to":`${o} var(--tw-gradient-to-position)`,"--tw-gradient-stops":`var(--tw-gradient-from), ${X(a)} var(--tw-gradient-via-position), var(--tw-gradient-to)`}}},n),e({via:a=>({"--tw-gradient-via-position":a})},s),e({to:a=>({"@defaults gradient-color-stops":{},"--tw-gradient-to":`${X(a)} var(--tw-gradient-to-position)`})},n),e({to:a=>({"--tw-gradient-to-position":a})},s)}})(),boxDecorationBreak:({addUtilities:r})=>{r({".decoration-slice":{"box-decoration-break":"slice"},".decoration-clone":{"box-decoration-break":"clone"},".box-decoration-slice":{"box-decoration-break":"slice"},".box-decoration-clone":{"box-decoration-break":"clone"}})},backgroundSize:L("backgroundSize",[["bg",["background-size"]]],{type:["lookup","length","percentage","size"]}),backgroundAttachment:({addUtilities:r})=>{r({".bg-fixed":{"background-attachment":"fixed"},".bg-local":{"background-attachment":"local"},".bg-scroll":{"background-attachment":"scroll"}})},backgroundClip:({addUtilities:r})=>{r({".bg-clip-border":{"background-clip":"border-box"},".bg-clip-padding":{"background-clip":"padding-box"},".bg-clip-content":{"background-clip":"content-box"},".bg-clip-text":{"background-clip":"text"}})},backgroundPosition:L("backgroundPosition",[["bg",["background-position"]]],{type:["lookup",["position",{preferOnConflict:!0}]]}),backgroundRepeat:({addUtilities:r})=>{r({".bg-repeat":{"background-repeat":"repeat"},".bg-no-repeat":{"background-repeat":"no-repeat"},".bg-repeat-x":{"background-repeat":"repeat-x"},".bg-repeat-y":{"background-repeat":"repeat-y"},".bg-repeat-round":{"background-repeat":"round"},".bg-repeat-space":{"background-repeat":"space"}})},backgroundOrigin:({addUtilities:r})=>{r({".bg-origin-border":{"background-origin":"border-box"},".bg-origin-padding":{"background-origin":"padding-box"},".bg-origin-content":{"background-origin":"content-box"}})},fill:({matchUtilities:r,theme:e})=>{r({fill:t=>({fill:X(t)})},{values:xe(e("fill")),type:["color","any"]})},stroke:({matchUtilities:r,theme:e})=>{r({stroke:t=>({stroke:X(t)})},{values:xe(e("stroke")),type:["color","url","any"]})},strokeWidth:L("strokeWidth",[["stroke",["stroke-width"]]],{type:["length","number","percentage"]}),objectFit:({addUtilities:r})=>{r({".object-contain":{"object-fit":"contain"},".object-cover":{"object-fit":"cover"},".object-fill":{"object-fit":"fill"},".object-none":{"object-fit":"none"},".object-scale-down":{"object-fit":"scale-down"}})},objectPosition:L("objectPosition",[["object",["object-position"]]]),padding:L("padding",[["p",["padding"]],[["px",["padding-left","padding-right"]],["py",["padding-top","padding-bottom"]]],[["ps",["padding-inline-start"]],["pe",["padding-inline-end"]],["pt",["padding-top"]],["pr",["padding-right"]],["pb",["padding-bottom"]],["pl",["padding-left"]]]]),textAlign:({addUtilities:r})=>{r({".text-left":{"text-align":"left"},".text-center":{"text-align":"center"},".text-right":{"text-align":"right"},".text-justify":{"text-align":"justify"},".text-start":{"text-align":"start"},".text-end":{"text-align":"end"}})},textIndent:L("textIndent",[["indent",["text-indent"]]],{supportsNegativeValues:!0}),verticalAlign:({addUtilities:r,matchUtilities:e})=>{r({".align-baseline":{"vertical-align":"baseline"},".align-top":{"vertical-align":"top"},".align-middle":{"vertical-align":"middle"},".align-bottom":{"vertical-align":"bottom"},".align-text-top":{"vertical-align":"text-top"},".align-text-bottom":{"vertical-align":"text-bottom"},".align-sub":{"vertical-align":"sub"},".align-super":{"vertical-align":"super"}}),e({align:t=>({"vertical-align":t})})},fontFamily:({matchUtilities:r,theme:e})=>{r({font:t=>{let[i,n={}]=Array.isArray(t)&&ke(t[1])?t:[t],{fontFeatureSettings:s,fontVariationSettings:a}=n;return{"font-family":Array.isArray(i)?i.join(", "):i,...s===void 0?{}:{"font-feature-settings":s},...a===void 0?{}:{"font-variation-settings":a}}}},{values:e("fontFamily"),type:["lookup","generic-name","family-name"]})},fontSize:({matchUtilities:r,theme:e})=>{r({text:(t,{modifier:i})=>{let[n,s]=Array.isArray(t)?t:[t];if(i)return{"font-size":n,"line-height":i};let{lineHeight:a,letterSpacing:o,fontWeight:l}=ke(s)?s:{lineHeight:s};return{"font-size":n,...a===void 0?{}:{"line-height":a},...o===void 0?{}:{"letter-spacing":o},...l===void 0?{}:{"font-weight":l}}}},{values:e("fontSize"),modifiers:e("lineHeight"),type:["absolute-size","relative-size","length","percentage"]})},fontWeight:L("fontWeight",[["font",["fontWeight"]]],{type:["lookup","number","any"]}),textTransform:({addUtilities:r})=>{r({".uppercase":{"text-transform":"uppercase"},".lowercase":{"text-transform":"lowercase"},".capitalize":{"text-transform":"capitalize"},".normal-case":{"text-transform":"none"}})},fontStyle:({addUtilities:r})=>{r({".italic":{"font-style":"italic"},".not-italic":{"font-style":"normal"}})},fontVariantNumeric:({addDefaults:r,addUtilities:e})=>{let t="var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)";r("font-variant-numeric",{"--tw-ordinal":" ","--tw-slashed-zero":" ","--tw-numeric-figure":" ","--tw-numeric-spacing":" ","--tw-numeric-fraction":" "}),e({".normal-nums":{"font-variant-numeric":"normal"},".ordinal":{"@defaults font-variant-numeric":{},"--tw-ordinal":"ordinal","font-variant-numeric":t},".slashed-zero":{"@defaults font-variant-numeric":{},"--tw-slashed-zero":"slashed-zero","font-variant-numeric":t},".lining-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-figure":"lining-nums","font-variant-numeric":t},".oldstyle-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-figure":"oldstyle-nums","font-variant-numeric":t},".proportional-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-spacing":"proportional-nums","font-variant-numeric":t},".tabular-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-spacing":"tabular-nums","font-variant-numeric":t},".diagonal-fractions":{"@defaults font-variant-numeric":{},"--tw-numeric-fraction":"diagonal-fractions","font-variant-numeric":t},".stacked-fractions":{"@defaults font-variant-numeric":{},"--tw-numeric-fraction":"stacked-fractions","font-variant-numeric":t}})},lineHeight:L("lineHeight",[["leading",["lineHeight"]]]),letterSpacing:L("letterSpacing",[["tracking",["letterSpacing"]]],{supportsNegativeValues:!0}),textColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({text:i=>t("textOpacity")?Ae({color:i,property:"color",variable:"--tw-text-opacity"}):{color:X(i)}},{values:xe(e("textColor")),type:["color","any"]})},textOpacity:L("textOpacity",[["text-opacity",["--tw-text-opacity"]]]),textDecoration:({addUtilities:r})=>{r({".underline":{"text-decoration-line":"underline"},".overline":{"text-decoration-line":"overline"},".line-through":{"text-decoration-line":"line-through"},".no-underline":{"text-decoration-line":"none"}})},textDecorationColor:({matchUtilities:r,theme:e})=>{r({decoration:t=>({"text-decoration-color":X(t)})},{values:xe(e("textDecorationColor")),type:["color","any"]})},textDecorationStyle:({addUtilities:r})=>{r({".decoration-solid":{"text-decoration-style":"solid"},".decoration-double":{"text-decoration-style":"double"},".decoration-dotted":{"text-decoration-style":"dotted"},".decoration-dashed":{"text-decoration-style":"dashed"},".decoration-wavy":{"text-decoration-style":"wavy"}})},textDecorationThickness:L("textDecorationThickness",[["decoration",["text-decoration-thickness"]]],{type:["length","percentage"]}),textUnderlineOffset:L("textUnderlineOffset",[["underline-offset",["text-underline-offset"]]],{type:["length","percentage","any"]}),fontSmoothing:({addUtilities:r})=>{r({".antialiased":{"-webkit-font-smoothing":"antialiased","-moz-osx-font-smoothing":"grayscale"},".subpixel-antialiased":{"-webkit-font-smoothing":"auto","-moz-osx-font-smoothing":"auto"}})},placeholderColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({placeholder:i=>t("placeholderOpacity")?{"&::placeholder":Ae({color:i,property:"color",variable:"--tw-placeholder-opacity"})}:{"&::placeholder":{color:X(i)}}},{values:xe(e("placeholderColor")),type:["color","any"]})},placeholderOpacity:({matchUtilities:r,theme:e})=>{r({"placeholder-opacity":t=>({["&::placeholder"]:{"--tw-placeholder-opacity":t}})},{values:e("placeholderOpacity")})},caretColor:({matchUtilities:r,theme:e})=>{r({caret:t=>({"caret-color":X(t)})},{values:xe(e("caretColor")),type:["color","any"]})},accentColor:({matchUtilities:r,theme:e})=>{r({accent:t=>({"accent-color":X(t)})},{values:xe(e("accentColor")),type:["color","any"]})},opacity:L("opacity",[["opacity",["opacity"]]]),backgroundBlendMode:({addUtilities:r})=>{r({".bg-blend-normal":{"background-blend-mode":"normal"},".bg-blend-multiply":{"background-blend-mode":"multiply"},".bg-blend-screen":{"background-blend-mode":"screen"},".bg-blend-overlay":{"background-blend-mode":"overlay"},".bg-blend-darken":{"background-blend-mode":"darken"},".bg-blend-lighten":{"background-blend-mode":"lighten"},".bg-blend-color-dodge":{"background-blend-mode":"color-dodge"},".bg-blend-color-burn":{"background-blend-mode":"color-burn"},".bg-blend-hard-light":{"background-blend-mode":"hard-light"},".bg-blend-soft-light":{"background-blend-mode":"soft-light"},".bg-blend-difference":{"background-blend-mode":"difference"},".bg-blend-exclusion":{"background-blend-mode":"exclusion"},".bg-blend-hue":{"background-blend-mode":"hue"},".bg-blend-saturation":{"background-blend-mode":"saturation"},".bg-blend-color":{"background-blend-mode":"color"},".bg-blend-luminosity":{"background-blend-mode":"luminosity"}})},mixBlendMode:({addUtilities:r})=>{r({".mix-blend-normal":{"mix-blend-mode":"normal"},".mix-blend-multiply":{"mix-blend-mode":"multiply"},".mix-blend-screen":{"mix-blend-mode":"screen"},".mix-blend-overlay":{"mix-blend-mode":"overlay"},".mix-blend-darken":{"mix-blend-mode":"darken"},".mix-blend-lighten":{"mix-blend-mode":"lighten"},".mix-blend-color-dodge":{"mix-blend-mode":"color-dodge"},".mix-blend-color-burn":{"mix-blend-mode":"color-burn"},".mix-blend-hard-light":{"mix-blend-mode":"hard-light"},".mix-blend-soft-light":{"mix-blend-mode":"soft-light"},".mix-blend-difference":{"mix-blend-mode":"difference"},".mix-blend-exclusion":{"mix-blend-mode":"exclusion"},".mix-blend-hue":{"mix-blend-mode":"hue"},".mix-blend-saturation":{"mix-blend-mode":"saturation"},".mix-blend-color":{"mix-blend-mode":"color"},".mix-blend-luminosity":{"mix-blend-mode":"luminosity"},".mix-blend-plus-darker":{"mix-blend-mode":"plus-darker"},".mix-blend-plus-lighter":{"mix-blend-mode":"plus-lighter"}})},boxShadow:(()=>{let r=mt("boxShadow"),e=["var(--tw-ring-offset-shadow, 0 0 #0000)","var(--tw-ring-shadow, 0 0 #0000)","var(--tw-shadow)"].join(", ");return function({matchUtilities:t,addDefaults:i,theme:n}){i("box-shadow",{"--tw-ring-offset-shadow":"0 0 #0000","--tw-ring-shadow":"0 0 #0000","--tw-shadow":"0 0 #0000","--tw-shadow-colored":"0 0 #0000"}),t({shadow:s=>{s=r(s);let a=en(s);for(let o of a)!o.valid||(o.color="var(--tw-shadow-color)");return{"@defaults box-shadow":{},"--tw-shadow":s==="none"?"0 0 #0000":s,"--tw-shadow-colored":s==="none"?"0 0 #0000":Lf(a),"box-shadow":e}}},{values:n("boxShadow"),type:["shadow"]})}})(),boxShadowColor:({matchUtilities:r,theme:e})=>{r({shadow:t=>({"--tw-shadow-color":X(t),"--tw-shadow":"var(--tw-shadow-colored)"})},{values:xe(e("boxShadowColor")),type:["color","any"]})},outlineStyle:({addUtilities:r})=>{r({".outline-none":{outline:"2px solid transparent","outline-offset":"2px"},".outline":{"outline-style":"solid"},".outline-dashed":{"outline-style":"dashed"},".outline-dotted":{"outline-style":"dotted"},".outline-double":{"outline-style":"double"}})},outlineWidth:L("outlineWidth",[["outline",["outline-width"]]],{type:["length","number","percentage"]}),outlineOffset:L("outlineOffset",[["outline-offset",["outline-offset"]]],{type:["length","number","percentage","any"],supportsNegativeValues:!0}),outlineColor:({matchUtilities:r,theme:e})=>{r({outline:t=>({"outline-color":X(t)})},{values:xe(e("outlineColor")),type:["color","any"]})},ringWidth:({matchUtilities:r,addDefaults:e,addUtilities:t,theme:i,config:n})=>{let s=(()=>{if(we(n(),"respectDefaultRingColorOpacity"))return i("ringColor.DEFAULT");let a=i("ringOpacity.DEFAULT","0.5");return i("ringColor")?.DEFAULT?Je(i("ringColor")?.DEFAULT,a,`rgb(147 197 253 / ${a})`):`rgb(147 197 253 / ${a})`})();e("ring-width",{"--tw-ring-inset":" ","--tw-ring-offset-width":i("ringOffsetWidth.DEFAULT","0px"),"--tw-ring-offset-color":i("ringOffsetColor.DEFAULT","#fff"),"--tw-ring-color":s,"--tw-ring-offset-shadow":"0 0 #0000","--tw-ring-shadow":"0 0 #0000","--tw-shadow":"0 0 #0000","--tw-shadow-colored":"0 0 #0000"}),r({ring:a=>({"@defaults ring-width":{},"--tw-ring-offset-shadow":"var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)","--tw-ring-shadow":`var(--tw-ring-inset) 0 0 0 calc(${a} + var(--tw-ring-offset-width)) var(--tw-ring-color)`,"box-shadow":["var(--tw-ring-offset-shadow)","var(--tw-ring-shadow)","var(--tw-shadow, 0 0 #0000)"].join(", ")})},{values:i("ringWidth"),type:"length"}),t({".ring-inset":{"@defaults ring-width":{},"--tw-ring-inset":"inset"}})},ringColor:({matchUtilities:r,theme:e,corePlugins:t})=>{r({ring:i=>t("ringOpacity")?Ae({color:i,property:"--tw-ring-color",variable:"--tw-ring-opacity"}):{"--tw-ring-color":X(i)}},{values:Object.fromEntries(Object.entries(xe(e("ringColor"))).filter(([i])=>i!=="DEFAULT")),type:["color","any"]})},ringOpacity:r=>{let{config:e}=r;return L("ringOpacity",[["ring-opacity",["--tw-ring-opacity"]]],{filterDefault:!we(e(),"respectDefaultRingColorOpacity")})(r)},ringOffsetWidth:L("ringOffsetWidth",[["ring-offset",["--tw-ring-offset-width"]]],{type:"length"}),ringOffsetColor:({matchUtilities:r,theme:e})=>{r({"ring-offset":t=>({"--tw-ring-offset-color":X(t)})},{values:xe(e("ringOffsetColor")),type:["color","any"]})},blur:({matchUtilities:r,theme:e})=>{r({blur:t=>({"--tw-blur":t.trim()===""?" ":`blur(${t})`,"@defaults filter":{},filter:nt})},{values:e("blur")})},brightness:({matchUtilities:r,theme:e})=>{r({brightness:t=>({"--tw-brightness":`brightness(${t})`,"@defaults filter":{},filter:nt})},{values:e("brightness")})},contrast:({matchUtilities:r,theme:e})=>{r({contrast:t=>({"--tw-contrast":`contrast(${t})`,"@defaults filter":{},filter:nt})},{values:e("contrast")})},dropShadow:({matchUtilities:r,theme:e})=>{r({"drop-shadow":t=>({"--tw-drop-shadow":Array.isArray(t)?t.map(i=>`drop-shadow(${i})`).join(" "):`drop-shadow(${t})`,"@defaults filter":{},filter:nt})},{values:e("dropShadow")})},grayscale:({matchUtilities:r,theme:e})=>{r({grayscale:t=>({"--tw-grayscale":`grayscale(${t})`,"@defaults filter":{},filter:nt})},{values:e("grayscale")})},hueRotate:({matchUtilities:r,theme:e})=>{r({"hue-rotate":t=>({"--tw-hue-rotate":`hue-rotate(${t})`,"@defaults filter":{},filter:nt})},{values:e("hueRotate"),supportsNegativeValues:!0})},invert:({matchUtilities:r,theme:e})=>{r({invert:t=>({"--tw-invert":`invert(${t})`,"@defaults filter":{},filter:nt})},{values:e("invert")})},saturate:({matchUtilities:r,theme:e})=>{r({saturate:t=>({"--tw-saturate":`saturate(${t})`,"@defaults filter":{},filter:nt})},{values:e("saturate")})},sepia:({matchUtilities:r,theme:e})=>{r({sepia:t=>({"--tw-sepia":`sepia(${t})`,"@defaults filter":{},filter:nt})},{values:e("sepia")})},filter:({addDefaults:r,addUtilities:e})=>{r("filter",{"--tw-blur":" ","--tw-brightness":" ","--tw-contrast":" ","--tw-grayscale":" ","--tw-hue-rotate":" ","--tw-invert":" ","--tw-saturate":" ","--tw-sepia":" ","--tw-drop-shadow":" "}),e({".filter":{"@defaults filter":{},filter:nt},".filter-none":{filter:"none"}})},backdropBlur:({matchUtilities:r,theme:e})=>{r({"backdrop-blur":t=>({"--tw-backdrop-blur":t.trim()===""?" ":`blur(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropBlur")})},backdropBrightness:({matchUtilities:r,theme:e})=>{r({"backdrop-brightness":t=>({"--tw-backdrop-brightness":`brightness(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropBrightness")})},backdropContrast:({matchUtilities:r,theme:e})=>{r({"backdrop-contrast":t=>({"--tw-backdrop-contrast":`contrast(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropContrast")})},backdropGrayscale:({matchUtilities:r,theme:e})=>{r({"backdrop-grayscale":t=>({"--tw-backdrop-grayscale":`grayscale(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropGrayscale")})},backdropHueRotate:({matchUtilities:r,theme:e})=>{r({"backdrop-hue-rotate":t=>({"--tw-backdrop-hue-rotate":`hue-rotate(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropHueRotate"),supportsNegativeValues:!0})},backdropInvert:({matchUtilities:r,theme:e})=>{r({"backdrop-invert":t=>({"--tw-backdrop-invert":`invert(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropInvert")})},backdropOpacity:({matchUtilities:r,theme:e})=>{r({"backdrop-opacity":t=>({"--tw-backdrop-opacity":`opacity(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropOpacity")})},backdropSaturate:({matchUtilities:r,theme:e})=>{r({"backdrop-saturate":t=>({"--tw-backdrop-saturate":`saturate(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropSaturate")})},backdropSepia:({matchUtilities:r,theme:e})=>{r({"backdrop-sepia":t=>({"--tw-backdrop-sepia":`sepia(${t})`,"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge})},{values:e("backdropSepia")})},backdropFilter:({addDefaults:r,addUtilities:e})=>{r("backdrop-filter",{"--tw-backdrop-blur":" ","--tw-backdrop-brightness":" ","--tw-backdrop-contrast":" ","--tw-backdrop-grayscale":" ","--tw-backdrop-hue-rotate":" ","--tw-backdrop-invert":" ","--tw-backdrop-opacity":" ","--tw-backdrop-saturate":" ","--tw-backdrop-sepia":" "}),e({".backdrop-filter":{"@defaults backdrop-filter":{},"-webkit-backdrop-filter":ge,"backdrop-filter":ge},".backdrop-filter-none":{"-webkit-backdrop-filter":"none","backdrop-filter":"none"}})},transitionProperty:({matchUtilities:r,theme:e})=>{let t=e("transitionTimingFunction.DEFAULT"),i=e("transitionDuration.DEFAULT");r({transition:n=>({"transition-property":n,...n==="none"?{}:{"transition-timing-function":t,"transition-duration":i}})},{values:e("transitionProperty")})},transitionDelay:L("transitionDelay",[["delay",["transitionDelay"]]]),transitionDuration:L("transitionDuration",[["duration",["transitionDuration"]]],{filterDefault:!0}),transitionTimingFunction:L("transitionTimingFunction",[["ease",["transitionTimingFunction"]]],{filterDefault:!0}),willChange:L("willChange",[["will-change",["will-change"]]]),contain:({addDefaults:r,addUtilities:e})=>{let t="var(--tw-contain-size) var(--tw-contain-layout) var(--tw-contain-paint) var(--tw-contain-style)";r("contain",{"--tw-contain-size":" ","--tw-contain-layout":" ","--tw-contain-paint":" ","--tw-contain-style":" "}),e({".contain-none":{contain:"none"},".contain-content":{contain:"content"},".contain-strict":{contain:"strict"},".contain-size":{"@defaults contain":{},"--tw-contain-size":"size",contain:t},".contain-inline-size":{"@defaults contain":{},"--tw-contain-size":"inline-size",contain:t},".contain-layout":{"@defaults contain":{},"--tw-contain-layout":"layout",contain:t},".contain-paint":{"@defaults contain":{},"--tw-contain-paint":"paint",contain:t},".contain-style":{"@defaults contain":{},"--tw-contain-style":"style",contain:t}})},content:L("content",[["content",["--tw-content",["content","var(--tw-content)"]]]]),forcedColorAdjust:({addUtilities:r})=>{r({".forced-color-adjust-auto":{"forced-color-adjust":"auto"},".forced-color-adjust-none":{"forced-color-adjust":"none"}})}}});function h_(r){if(r===void 0)return!1;if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;if(r==="*")return!0;let e=r.split(",").map(t=>t.split(":")[0]);return e.includes("-tailwindcss")?!1:!!e.includes("tailwindcss")}var Ze,wh,vh,es,No,gt,Ti,It=P(()=>{u();Ze=typeof m!="undefined"?{NODE_ENV:"production",DEBUG:h_(m.env.DEBUG)}:{NODE_ENV:"production",DEBUG:!1},wh=new Map,vh=new Map,es=new Map,No=new Map,gt=new String("*"),Ti=Symbol("__NONE__")});function cr(r){let e=[],t=!1;for(let i=0;i0)}var xh,kh,m_,Bo=P(()=>{u();xh=new Map([["{","}"],["[","]"],["(",")"]]),kh=new Map(Array.from(xh.entries()).map(([r,e])=>[e,r])),m_=new Set(['"',"'","`"])});function pr(r){let[e]=Sh(r);return e.forEach(([t,i])=>t.removeChild(i)),r.nodes.push(...e.map(([,t])=>t)),r}function Sh(r){let e=[],t=null;for(let i of r.nodes)if(i.type==="combinator")e=e.filter(([,n])=>jo(n).includes("jumpable")),t=null;else if(i.type==="pseudo"){g_(i)?(t=i,e.push([r,i,null])):t&&y_(i,t)?e.push([r,i,t]):t=null;for(let n of i.nodes??[]){let[s,a]=Sh(n);t=a||t,e.push(...s)}}return[e,t]}function Ah(r){return r.value.startsWith("::")||Fo[r.value]!==void 0}function g_(r){return Ah(r)&&jo(r).includes("terminal")}function y_(r,e){return r.type!=="pseudo"||Ah(r)?!1:jo(e).includes("actionable")}function jo(r){return Fo[r.value]??Fo.__default__}var Fo,ts=P(()=>{u();Fo={"::after":["terminal","jumpable"],"::backdrop":["terminal","jumpable"],"::before":["terminal","jumpable"],"::cue":["terminal"],"::cue-region":["terminal"],"::first-letter":["terminal","jumpable"],"::first-line":["terminal","jumpable"],"::grammar-error":["terminal"],"::marker":["terminal","jumpable"],"::part":["terminal","actionable"],"::placeholder":["terminal","jumpable"],"::selection":["terminal","jumpable"],"::slotted":["terminal"],"::spelling-error":["terminal"],"::target-text":["terminal"],"::file-selector-button":["terminal","actionable"],"::deep":["actionable"],"::v-deep":["actionable"],"::ng-deep":["actionable"],":after":["terminal","jumpable"],":before":["terminal","jumpable"],":first-letter":["terminal","jumpable"],":first-line":["terminal","jumpable"],":where":[],":is":[],":has":[],__default__:["terminal","actionable"]}});function dr(r,{context:e,candidate:t}){let i=e?.tailwindConfig.prefix??"",n=r.map(a=>{let o=(0,st.default)().astSync(a.format);return{...a,ast:a.respectPrefix?ur(i,o):o}}),s=st.default.root({nodes:[st.default.selector({nodes:[st.default.className({value:Te(t)})]})]});for(let{ast:a}of n)[s,a]=w_(s,a),a.walkNesting(o=>o.replaceWith(...s.nodes[0].nodes)),s=a;return s}function _h(r){let e=[];for(;r.prev()&&r.prev().type!=="combinator";)r=r.prev();for(;r&&r.type!=="combinator";)e.push(r),r=r.next();return e}function b_(r){return r.sort((e,t)=>e.type==="tag"&&t.type==="class"?-1:e.type==="class"&&t.type==="tag"?1:e.type==="class"&&t.type==="pseudo"&&t.value.startsWith("::")?-1:e.type==="pseudo"&&e.value.startsWith("::")&&t.type==="class"?1:r.index(e)-r.index(t)),r}function Uo(r,e){let t=!1;r.walk(i=>{if(i.type==="class"&&i.value===e)return t=!0,!1}),t||r.remove()}function rs(r,e,{context:t,candidate:i,base:n}){let s=t?.tailwindConfig?.separator??":";n=n??ve(i,s).pop();let a=(0,st.default)().astSync(r);if(a.walkClasses(f=>{f.raws&&f.value.includes(n)&&(f.raws.value=Te((0,Ch.default)(f.raws.value)))}),a.each(f=>Uo(f,n)),a.length===0)return null;let o=Array.isArray(e)?dr(e,{context:t,candidate:i}):e;if(o===null)return a.toString();let l=st.default.comment({value:"/*__simple__*/"}),c=st.default.comment({value:"/*__simple__*/"});return a.walkClasses(f=>{if(f.value!==n)return;let d=f.parent,p=o.nodes[0].nodes;if(d.nodes.length===1){f.replaceWith(...p);return}let h=_h(f);d.insertBefore(h[0],l),d.insertAfter(h[h.length-1],c);for(let v of p)d.insertBefore(h[0],v.clone());f.remove(),h=_h(l);let b=d.index(l);d.nodes.splice(b,h.length,...b_(st.default.selector({nodes:h})).nodes),l.remove(),c.remove()}),a.walkPseudos(f=>{f.value===zo&&f.replaceWith(f.nodes)}),a.each(f=>pr(f)),a.toString()}function w_(r,e){let t=[];return r.walkPseudos(i=>{i.value===zo&&t.push({pseudo:i,value:i.nodes[0].toString()})}),e.walkPseudos(i=>{if(i.value!==zo)return;let n=i.nodes[0].toString(),s=t.find(c=>c.value===n);if(!s)return;let a=[],o=i.next();for(;o&&o.type!=="combinator";)a.push(o),o=o.next();let l=o;s.pseudo.parent.insertAfter(s.pseudo,st.default.selector({nodes:a.map(c=>c.clone())})),i.remove(),a.forEach(c=>c.remove()),l&&l.type==="combinator"&&l.remove()}),[r,e]}var st,Ch,zo,Vo=P(()=>{u();st=pe(it()),Ch=pe(Pn());fr();Gn();ts();zt();zo=":merge"});function is(r,e){let t=(0,Ho.default)().astSync(r);return t.each(i=>{i.nodes.some(s=>s.type==="combinator")&&(i.nodes=[Ho.default.pseudo({value:":is",nodes:[i.clone()]})]),pr(i)}),`${e} ${t.toString()}`}var Ho,Wo=P(()=>{u();Ho=pe(it());ts()});function Go(r){return v_.transformSync(r)}function*x_(r){let e=1/0;for(;e>=0;){let t,i=!1;if(e===1/0&&r.endsWith("]")){let a=r.indexOf("[");r[a-1]==="-"?t=a-1:r[a-1]==="/"?(t=a-1,i=!0):t=-1}else e===1/0&&r.includes("/")?(t=r.lastIndexOf("/"),i=!0):t=r.lastIndexOf("-",e);if(t<0)break;let n=r.slice(0,t),s=r.slice(i?t:t+1);e=t-1,!(n===""||s==="/")&&(yield[n,s])}}function k_(r,e){if(r.length===0||e.tailwindConfig.prefix==="")return r;for(let t of r){let[i]=t;if(i.options.respectPrefix){let n=ee.root({nodes:[t[1].clone()]}),s=t[1].raws.tailwind.classCandidate;n.walkRules(a=>{let o=s.startsWith("-");a.selector=ur(e.tailwindConfig.prefix,a.selector,o)}),t[1]=n.nodes[0]}}return r}function S_(r,e){if(r.length===0)return r;let t=[];function i(n){return n.parent&&n.parent.type==="atrule"&&n.parent.name==="keyframes"}for(let[n,s]of r){let a=ee.root({nodes:[s.clone()]});a.walkRules(o=>{if(i(o))return;let l=(0,ns.default)().astSync(o.selector);l.each(c=>Uo(c,e)),Qf(l,c=>c===e?`!${c}`:c),o.selector=l.toString(),o.walkDecls(c=>c.important=!0)}),t.push([{...n,important:!0},a.nodes[0]])}return t}function A_(r,e,t){if(e.length===0)return e;let i={modifier:null,value:Ti};{let[n,...s]=ve(r,"/");if(s.length>1&&(n=n+"/"+s.slice(0,-1).join("/"),s=s.slice(-1)),s.length&&!t.variantMap.has(r)&&(r=n,i.modifier=s[0],!we(t.tailwindConfig,"generalizedModifiers")))return[]}if(r.endsWith("]")&&!r.startsWith("[")){let n=/(.)(-?)\[(.*)\]/g.exec(r);if(n){let[,s,a,o]=n;if(s==="@"&&a==="-")return[];if(s!=="@"&&a==="")return[];r=r.replace(`${a}[${o}]`,""),i.value=o}}if(Ko(r)&&!t.variantMap.has(r)){let n=t.offsets.recordVariant(r),s=K(r.slice(1,-1)),a=ve(s,",");if(a.length>1)return[];if(!a.every(ls))return[];let o=a.map((l,c)=>[t.offsets.applyParallelOffset(n,c),Ri(l.trim())]);t.variantMap.set(r,o)}if(t.variantMap.has(r)){let n=Ko(r),s=t.variantOptions.get(r)?.[Pt]??{},a=t.variantMap.get(r).slice(),o=[],l=(()=>!(n||s.respectPrefix===!1))();for(let[c,f]of e){if(c.layer==="user")continue;let d=ee.root({nodes:[f.clone()]});for(let[p,h,b]of a){let w=function(){v.raws.neededBackup||(v.raws.neededBackup=!0,v.walkRules(T=>T.raws.originalSelector=T.selector))},k=function(T){return w(),v.each(B=>{B.type==="rule"&&(B.selectors=B.selectors.map(N=>T({get className(){return Go(N)},selector:N})))}),v},v=(b??d).clone(),y=[],S=h({get container(){return w(),v},separator:t.tailwindConfig.separator,modifySelectors:k,wrap(T){let B=v.nodes;v.removeAll(),T.append(B),v.append(T)},format(T){y.push({format:T,respectPrefix:l})},args:i});if(Array.isArray(S)){for(let[T,B]of S.entries())a.push([t.offsets.applyParallelOffset(p,T),B,v.clone()]);continue}if(typeof S=="string"&&y.push({format:S,respectPrefix:l}),S===null)continue;v.raws.neededBackup&&(delete v.raws.neededBackup,v.walkRules(T=>{let B=T.raws.originalSelector;if(!B||(delete T.raws.originalSelector,B===T.selector))return;let N=T.selector,R=(0,ns.default)(F=>{F.walkClasses(Y=>{Y.value=`${r}${t.tailwindConfig.separator}${Y.value}`})}).processSync(B);y.push({format:N.replace(R,"&"),respectPrefix:l}),T.selector=B})),v.nodes[0].raws.tailwind={...v.nodes[0].raws.tailwind,parentLayer:c.layer};let E=[{...c,sort:t.offsets.applyVariantOffset(c.sort,p,Object.assign(i,t.variantOptions.get(r))),collectedFormats:(c.collectedFormats??[]).concat(y)},v.nodes[0]];o.push(E)}}return o}return[]}function Qo(r,e,t={}){return!ke(r)&&!Array.isArray(r)?[[r],t]:Array.isArray(r)?Qo(r[0],e,r[1]):(e.has(r)||e.set(r,lr(r)),[e.get(r),t])}function __(r){return C_.test(r)}function E_(r){if(!r.includes("://"))return!1;try{let e=new URL(r);return e.scheme!==""&&e.host!==""}catch(e){return!1}}function Eh(r){let e=!0;return r.walkDecls(t=>{if(!Oh(t.prop,t.value))return e=!1,!1}),e}function Oh(r,e){if(E_(`${r}:${e}`))return!1;try{return ee.parse(`a{${r}:${e}}`).toResult(),!0}catch(t){return!1}}function O_(r,e){let[,t,i]=r.match(/^\[([a-zA-Z0-9-_]+):(\S+)\]$/)??[];if(i===void 0||!__(t)||!cr(i))return null;let n=K(i,{property:t});return Oh(t,n)?[[{sort:e.offsets.arbitraryProperty(r),layer:"utilities",options:{respectImportant:!0}},()=>({[$o(r)]:{[t]:n}})]]:null}function*T_(r,e){e.candidateRuleMap.has(r)&&(yield[e.candidateRuleMap.get(r),"DEFAULT"]),yield*function*(o){o!==null&&(yield[o,"DEFAULT"])}(O_(r,e));let t=r,i=!1,n=e.tailwindConfig.prefix,s=n.length,a=t.startsWith(n)||t.startsWith(`-${n}`);t[s]==="-"&&a&&(i=!0,t=n+t.slice(s+1)),i&&e.candidateRuleMap.has(t)&&(yield[e.candidateRuleMap.get(t),"-DEFAULT"]);for(let[o,l]of x_(t))e.candidateRuleMap.has(o)&&(yield[e.candidateRuleMap.get(o),i?`-${l}`:l])}function R_(r,e){return r===gt?[gt]:ve(r,e)}function*P_(r,e){for(let t of r)t[1].raws.tailwind={...t[1].raws.tailwind,classCandidate:e,preserveSource:t[0].options?.preserveSource??!1},yield t}function*Yo(r,e){let t=e.tailwindConfig.separator,[i,...n]=R_(r,t).reverse(),s=!1;i.startsWith("!")&&(s=!0,i=i.slice(1));for(let a of T_(i,e)){let o=[],l=new Map,[c,f]=a,d=c.length===1;for(let[p,h]of c){let b=[];if(typeof h=="function")for(let v of[].concat(h(f,{isOnlyPlugin:d}))){let[y,w]=Qo(v,e.postCssNodeCache);for(let k of y)b.push([{...p,options:{...p.options,...w}},k])}else if(f==="DEFAULT"||f==="-DEFAULT"){let v=h,[y,w]=Qo(v,e.postCssNodeCache);for(let k of y)b.push([{...p,options:{...p.options,...w}},k])}if(b.length>0){let v=Array.from(ta(p.options?.types??[],f,p.options??{},e.tailwindConfig)).map(([y,w])=>w);v.length>0&&l.set(b,v),o.push(b)}}if(Ko(f)){if(o.length>1){let b=function(y){return y.length===1?y[0]:y.find(w=>{let k=l.get(w);return w.some(([{options:S},E])=>Eh(E)?S.types.some(({type:T,preferOnConflict:B})=>k.includes(T)&&B):!1)})},[p,h]=o.reduce((y,w)=>(w.some(([{options:S}])=>S.types.some(({type:E})=>E==="any"))?y[0].push(w):y[1].push(w),y),[[],[]]),v=b(h)??b(p);if(v)o=[v];else{let y=o.map(k=>new Set([...l.get(k)??[]]));for(let k of y)for(let S of k){let E=!1;for(let T of y)k!==T&&T.has(S)&&(T.delete(S),E=!0);E&&k.delete(S)}let w=[];for(let[k,S]of y.entries())for(let E of S){let T=o[k].map(([,B])=>B).flat().map(B=>B.toString().split(` +`).slice(1,-1).map(N=>N.trim()).map(N=>` ${N}`).join(` +`)).join(` + +`);w.push(` Use \`${r.replace("[",`[${E}:`)}\` for \`${T.trim()}\``);break}G.warn([`The class \`${r}\` is ambiguous and matches multiple utilities.`,...w,`If this is content and not a class, replace it with \`${r.replace("[","[").replace("]","]")}\` to silence this warning.`]);continue}}o=o.map(p=>p.filter(h=>Eh(h[1])))}o=o.flat(),o=Array.from(P_(o,i)),o=k_(o,e),s&&(o=S_(o,i));for(let p of n)o=A_(p,o,e);for(let p of o)p[1].raws.tailwind={...p[1].raws.tailwind,candidate:r},p=I_(p,{context:e,candidate:r}),p!==null&&(yield p)}}function I_(r,{context:e,candidate:t}){if(!r[0].collectedFormats)return r;let i=!0,n;try{n=dr(r[0].collectedFormats,{context:e,candidate:t})}catch{return null}let s=ee.root({nodes:[r[1].clone()]});return s.walkRules(a=>{if(!ss(a))try{let o=rs(a.selector,n,{candidate:t,context:e});if(o===null){a.remove();return}a.selector=o}catch{return i=!1,!1}}),!i||s.nodes.length===0?null:(r[1]=s.nodes[0],r)}function ss(r){return r.parent&&r.parent.type==="atrule"&&r.parent.name==="keyframes"}function D_(r){if(r===!0)return e=>{ss(e)||e.walkDecls(t=>{t.parent.type==="rule"&&!ss(t.parent)&&(t.important=!0)})};if(typeof r=="string")return e=>{ss(e)||(e.selectors=e.selectors.map(t=>is(t,r)))}}function as(r,e,t=!1){let i=[],n=D_(e.tailwindConfig.important);for(let s of r){if(e.notClassCache.has(s))continue;if(e.candidateRuleCache.has(s)){i=i.concat(Array.from(e.candidateRuleCache.get(s)));continue}let a=Array.from(Yo(s,e));if(a.length===0){e.notClassCache.add(s);continue}e.classCache.set(s,a);let o=e.candidateRuleCache.get(s)??new Set;e.candidateRuleCache.set(s,o);for(let l of a){let[{sort:c,options:f},d]=l;if(f.respectImportant&&n){let h=ee.root({nodes:[d.clone()]});h.walkRules(n),d=h.nodes[0]}let p=[c,t?d.clone():d];o.add(p),e.ruleCache.add(p),i.push(p)}}return i}function Ko(r){return r.startsWith("[")&&r.endsWith("]")}var ns,v_,C_,os=P(()=>{u();Ot();ns=pe(it());qo();Kt();Gn();Fr();Be();It();Vo();Lo();Br();Oi();Bo();zt();ct();Wo();v_=(0,ns.default)(r=>r.first.filter(({type:e})=>e==="class").pop().value);C_=/^[a-z_-]/});var Th,Rh=P(()=>{u();Th={}});function q_(r){try{return Th.createHash("md5").update(r,"utf-8").digest("binary")}catch(e){return""}}function Ph(r,e){let t=e.toString();if(!t.includes("@tailwind"))return!1;let i=No.get(r),n=q_(t),s=i!==n;return No.set(r,n),s}var Ih=P(()=>{u();Rh();It()});function us(r){return(r>0n)-(r<0n)}var Dh=P(()=>{u()});function qh(r,e){let t=0n,i=0n;for(let[n,s]of e)r&n&&(t=t|n,i=i|s);return r&~t|i}var $h=P(()=>{u()});function Lh(r){let e=null;for(let t of r)e=e??t,e=e>t?e:t;return e}function $_(r,e){let t=r.length,i=e.length,n=t{u();Dh();$h();Xo=class{constructor(){this.offsets={defaults:0n,base:0n,components:0n,utilities:0n,variants:0n,user:0n},this.layerPositions={defaults:0n,base:1n,components:2n,utilities:3n,user:4n,variants:5n},this.reservedVariantBits=0n,this.variantOffsets=new Map}create(e){return{layer:e,parentLayer:e,arbitrary:0n,variants:0n,parallelIndex:0n,index:this.offsets[e]++,propertyOffset:0n,property:"",options:[]}}arbitraryProperty(e){return{...this.create("utilities"),arbitrary:1n,property:e}}forVariant(e,t=0){let i=this.variantOffsets.get(e);if(i===void 0)throw new Error(`Cannot find offset for unknown variant ${e}`);return{...this.create("variants"),variants:i<n.startsWith("[")).sort(([n],[s])=>$_(n,s)),t=e.map(([,n])=>n).sort((n,s)=>us(n-s));return e.map(([,n],s)=>[n,t[s]]).filter(([n,s])=>n!==s)}remapArbitraryVariantOffsets(e){let t=this.recalculateVariantOffsets();return t.length===0?e:e.map(i=>{let[n,s]=i;return n={...n,variants:qh(n.variants,t)},[n,s]})}sortArbitraryProperties(e){let t=new Set;for(let[a]of e)a.arbitrary===1n&&t.add(a.property);if(t.size===0)return e;let i=Array.from(t).sort(),n=new Map,s=1n;for(let a of i)n.set(a,s++);return e.map(a=>{let[o,l]=a;return o={...o,propertyOffset:n.get(o.property)??0n},[o,l]})}sort(e){return e=this.remapArbitraryVariantOffsets(e),e=this.sortArbitraryProperties(e),e.sort(([t],[i])=>us(this.compare(t,i)))}}});function tl(r,e){let t=r.tailwindConfig.prefix;return typeof t=="function"?t(e):t+e}function Bh({type:r="any",...e}){let t=[].concat(r);return{...e,types:t.map(i=>Array.isArray(i)?{type:i[0],...i[1]}:{type:i,preferOnConflict:!1})}}function L_(r){let e=[],t="",i=0;for(let n=0;n0&&e.push(t.trim()),e=e.filter(n=>n!==""),e}function M_(r,e,{before:t=[]}={}){if(t=[].concat(t),t.length<=0){r.push(e);return}let i=r.length-1;for(let n of t){let s=r.indexOf(n);s!==-1&&(i=Math.min(i,s))}r.splice(i,0,e)}function Fh(r){return Array.isArray(r)?r.flatMap(e=>!Array.isArray(e)&&!ke(e)?e:lr(e)):Fh([r])}function N_(r,e){return(0,Zo.default)(i=>{let n=[];return e&&e(i),i.walkClasses(s=>{n.push(s.value)}),n}).transformSync(r)}function B_(r){r.walkPseudos(e=>{e.value===":not"&&e.remove()})}function F_(r,e={containsNonOnDemandable:!1},t=0){let i=[],n=[];r.type==="rule"?n.push(...r.selectors):r.type==="atrule"&&r.walkRules(s=>n.push(...s.selectors));for(let s of n){let a=N_(s,B_);a.length===0&&(e.containsNonOnDemandable=!0);for(let o of a)i.push(o)}return t===0?[e.containsNonOnDemandable||i.length===0,i]:i}function fs(r){return Fh(r).flatMap(e=>{let t=new Map,[i,n]=F_(e);return i&&n.unshift(gt),n.map(s=>(t.has(e)||t.set(e,e),[s,t.get(e)]))})}function ls(r){return r.startsWith("@")||r.includes("&")}function Ri(r){r=r.replace(/\n+/g,"").replace(/\s{1,}/g," ").trim();let e=L_(r).map(t=>{if(!t.startsWith("@"))return({format:s})=>s(t);let[,i,n]=/@(\S*)( .+|[({].*)?/g.exec(t);return({wrap:s})=>s(ee.atRule({name:i,params:n?.trim()??""}))}).reverse();return t=>{for(let i of e)i(t)}}function j_(r,e,{variantList:t,variantMap:i,offsets:n,classList:s}){function a(p,h){return p?(0,Nh.default)(r,p,h):r}function o(p){return ur(r.prefix,p)}function l(p,h){return p===gt?gt:h.respectPrefix?e.tailwindConfig.prefix+p:p}function c(p,h,b={}){let v=kt(p),y=a(["theme",...v],h);return mt(v[0])(y,b)}let f=0,d={postcss:ee,prefix:o,e:Te,config:a,theme:c,corePlugins:p=>Array.isArray(r.corePlugins)?r.corePlugins.includes(p):a(["corePlugins",p],!0),variants:()=>[],addBase(p){for(let[h,b]of fs(p)){let v=l(h,{}),y=n.create("base");e.candidateRuleMap.has(v)||e.candidateRuleMap.set(v,[]),e.candidateRuleMap.get(v).push([{sort:y,layer:"base"},b])}},addDefaults(p,h){let b={[`@defaults ${p}`]:h};for(let[v,y]of fs(b)){let w=l(v,{});e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("defaults"),layer:"defaults"},y])}},addComponents(p,h){h=Object.assign({},{preserveSource:!1,respectPrefix:!0,respectImportant:!1},Array.isArray(h)?{}:h);for(let[v,y]of fs(p)){let w=l(v,h);s.add(w),e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("components"),layer:"components",options:h},y])}},addUtilities(p,h){h=Object.assign({},{preserveSource:!1,respectPrefix:!0,respectImportant:!0},Array.isArray(h)?{}:h);for(let[v,y]of fs(p)){let w=l(v,h);s.add(w),e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("utilities"),layer:"utilities",options:h},y])}},matchUtilities:function(p,h){h=Bh({...{respectPrefix:!0,respectImportant:!0,modifiers:!1},...h});let v=n.create("utilities");for(let y in p){let S=function(T,{isOnlyPlugin:B}){let[N,R,F]=ea(h.types,T,h,r);if(N===void 0)return[];if(!h.types.some(({type:U})=>U===R))if(B)G.warn([`Unnecessary typehint \`${R}\` in \`${y}-${T}\`.`,`You can safely update it to \`${y}-${T.replace(R+":","")}\`.`]);else return[];if(!cr(N))return[];let Y={get modifier(){return h.modifiers||G.warn(`modifier-used-without-options-for-${y}`,["Your plugin must set `modifiers: true` in its options to support modifiers."]),F}},_=we(r,"generalizedModifiers");return[].concat(_?k(N,Y):k(N)).filter(Boolean).map(U=>({[Qn(y,T)]:U}))},w=l(y,h),k=p[y];s.add([w,h]);let E=[{sort:v,layer:"utilities",options:h},S];e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push(E)}},matchComponents:function(p,h){h=Bh({...{respectPrefix:!0,respectImportant:!1,modifiers:!1},...h});let v=n.create("components");for(let y in p){let S=function(T,{isOnlyPlugin:B}){let[N,R,F]=ea(h.types,T,h,r);if(N===void 0)return[];if(!h.types.some(({type:U})=>U===R))if(B)G.warn([`Unnecessary typehint \`${R}\` in \`${y}-${T}\`.`,`You can safely update it to \`${y}-${T.replace(R+":","")}\`.`]);else return[];if(!cr(N))return[];let Y={get modifier(){return h.modifiers||G.warn(`modifier-used-without-options-for-${y}`,["Your plugin must set `modifiers: true` in its options to support modifiers."]),F}},_=we(r,"generalizedModifiers");return[].concat(_?k(N,Y):k(N)).filter(Boolean).map(U=>({[Qn(y,T)]:U}))},w=l(y,h),k=p[y];s.add([w,h]);let E=[{sort:v,layer:"components",options:h},S];e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push(E)}},addVariant(p,h,b={}){h=[].concat(h).map(v=>{if(typeof v!="string")return(y={})=>{let{args:w,modifySelectors:k,container:S,separator:E,wrap:T,format:B}=y,N=v(Object.assign({modifySelectors:k,container:S,separator:E},b.type===Jo.MatchVariant&&{args:w,wrap:T,format:B}));if(typeof N=="string"&&!ls(N))throw new Error(`Your custom variant \`${p}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`);return Array.isArray(N)?N.filter(R=>typeof R=="string").map(R=>Ri(R)):N&&typeof N=="string"&&Ri(N)(y)};if(!ls(v))throw new Error(`Your custom variant \`${p}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`);return Ri(v)}),M_(t,p,b),i.set(p,h),e.variantOptions.set(p,b)},matchVariant(p,h,b){let v=b?.id??++f,y=p==="@",w=we(r,"generalizedModifiers");for(let[S,E]of Object.entries(b?.values??{}))S!=="DEFAULT"&&d.addVariant(y?`${p}${S}`:`${p}-${S}`,({args:T,container:B})=>h(E,w?{modifier:T?.modifier,container:B}:{container:B}),{...b,value:E,id:v,type:Jo.MatchVariant,variantInfo:el.Base});let k="DEFAULT"in(b?.values??{});d.addVariant(p,({args:S,container:E})=>S?.value===Ti&&!k?null:h(S?.value===Ti?b.values.DEFAULT:S?.value??(typeof S=="string"?S:""),w?{modifier:S?.modifier,container:E}:{container:E}),{...b,id:v,type:Jo.MatchVariant,variantInfo:el.Dynamic})}};return d}function cs(r){return rl.has(r)||rl.set(r,new Map),rl.get(r)}function jh(r,e){let t=!1,i=new Map;for(let n of r){if(!n)continue;let s=oa.parse(n),a=s.hash?s.href.replace(s.hash,""):s.href;a=s.search?a.replace(s.search,""):a;let o=be.statSync(decodeURIComponent(a),{throwIfNoEntry:!1})?.mtimeMs;!o||((!e.has(n)||o>e.get(n))&&(t=!0),i.set(n,o))}return[t,i]}function zh(r){r.walkAtRules(e=>{["responsive","variants"].includes(e.name)&&(zh(e),e.before(e.nodes),e.remove())})}function z_(r){let e=[];return r.each(t=>{t.type==="atrule"&&["responsive","variants"].includes(t.name)&&(t.name="layer",t.params="utilities")}),r.walkAtRules("layer",t=>{if(zh(t),t.params==="base"){for(let i of t.nodes)e.push(function({addBase:n}){n(i,{respectPrefix:!1})});t.remove()}else if(t.params==="components"){for(let i of t.nodes)e.push(function({addComponents:n}){n(i,{respectPrefix:!1,preserveSource:!0})});t.remove()}else if(t.params==="utilities"){for(let i of t.nodes)e.push(function({addUtilities:n}){n(i,{respectPrefix:!1,preserveSource:!0})});t.remove()}}),e}function U_(r,e){let t=Object.entries({...se,...yh}).map(([l,c])=>r.tailwindConfig.corePlugins.includes(l)?c:null).filter(Boolean),i=r.tailwindConfig.plugins.map(l=>(l.__isOptionsFunction&&(l=l()),typeof l=="function"?l:l.handler)),n=z_(e),s=[se.childVariant,se.pseudoElementVariants,se.pseudoClassVariants,se.hasVariants,se.ariaVariants,se.dataVariants],a=[se.supportsVariants,se.reducedMotionVariants,se.prefersContrastVariants,se.screenVariants,se.orientationVariants,se.directionVariants,se.darkVariants,se.forcedColorsVariants,se.printVariant];return(r.tailwindConfig.darkMode==="class"||Array.isArray(r.tailwindConfig.darkMode)&&r.tailwindConfig.darkMode[0]==="class")&&(a=[se.supportsVariants,se.reducedMotionVariants,se.prefersContrastVariants,se.darkVariants,se.screenVariants,se.orientationVariants,se.directionVariants,se.forcedColorsVariants,se.printVariant]),[...t,...s,...i,...a,...n]}function V_(r,e){let t=[],i=new Map;e.variantMap=i;let n=new Xo;e.offsets=n;let s=new Set,a=j_(e.tailwindConfig,e,{variantList:t,variantMap:i,offsets:n,classList:s});for(let f of r)if(Array.isArray(f))for(let d of f)d(a);else f?.(a);n.recordVariants(t,f=>i.get(f).length);for(let[f,d]of i.entries())e.variantMap.set(f,d.map((p,h)=>[n.forVariant(f,h),p]));let o=(e.tailwindConfig.safelist??[]).filter(Boolean);if(o.length>0){let f=[];for(let d of o){if(typeof d=="string"){e.changedContent.push({content:d,extension:"html"});continue}if(d instanceof RegExp){G.warn("root-regex",["Regular expressions in `safelist` work differently in Tailwind CSS v3.0.","Update your `safelist` configuration to eliminate this warning.","https://tailwindcss.com/docs/content-configuration#safelisting-classes"]);continue}f.push(d)}if(f.length>0){let d=new Map,p=e.tailwindConfig.prefix.length,h=f.some(b=>b.pattern.source.includes("!"));for(let b of s){let v=Array.isArray(b)?(()=>{let[y,w]=b,S=Object.keys(w?.values??{}).map(E=>Ei(y,E));return w?.supportsNegativeValues&&(S=[...S,...S.map(E=>"-"+E)],S=[...S,...S.map(E=>E.slice(0,p)+"-"+E.slice(p))]),w.types.some(({type:E})=>E==="color")&&(S=[...S,...S.flatMap(E=>Object.keys(e.tailwindConfig.theme.opacity).map(T=>`${E}/${T}`))]),h&&w?.respectImportant&&(S=[...S,...S.map(E=>"!"+E)]),S})():[b];for(let y of v)for(let{pattern:w,variants:k=[]}of f)if(w.lastIndex=0,d.has(w)||d.set(w,0),!!w.test(y)){d.set(w,d.get(w)+1),e.changedContent.push({content:y,extension:"html"});for(let S of k)e.changedContent.push({content:S+e.tailwindConfig.separator+y,extension:"html"})}}for(let[b,v]of d.entries())v===0&&G.warn([`The safelist pattern \`${b}\` doesn't match any Tailwind CSS classes.`,"Fix this pattern or remove it from your `safelist` configuration.","https://tailwindcss.com/docs/content-configuration#safelisting-classes"])}}let l=[].concat(e.tailwindConfig.darkMode??"media")[1]??"dark",c=[tl(e,l),tl(e,"group"),tl(e,"peer")];e.getClassOrder=function(d){let p=[...d].sort((y,w)=>y===w?0:y[y,null])),b=as(new Set(p),e,!0);b=e.offsets.sort(b);let v=BigInt(c.length);for(let[,y]of b){let w=y.raws.tailwind.candidate;h.set(w,h.get(w)??v++)}return d.map(y=>{let w=h.get(y)??null,k=c.indexOf(y);return w===null&&k!==-1&&(w=BigInt(k)),[y,w]})},e.getClassList=function(d={}){let p=[];for(let h of s)if(Array.isArray(h)){let[b,v]=h,y=[],w=Object.keys(v?.modifiers??{});v?.types?.some(({type:E})=>E==="color")&&w.push(...Object.keys(e.tailwindConfig.theme.opacity??{}));let k={modifiers:w},S=d.includeMetadata&&w.length>0;for(let[E,T]of Object.entries(v?.values??{})){if(T==null)continue;let B=Ei(b,E);if(p.push(S?[B,k]:B),v?.supportsNegativeValues&&xt(T)){let N=Ei(b,`-${E}`);y.push(S?[N,k]:N)}}p.push(...y)}else p.push(h);return p},e.getVariants=function(){let d=Math.random().toString(36).substring(7).toUpperCase(),p=[];for(let[h,b]of e.variantOptions.entries())b.variantInfo!==el.Base&&p.push({name:h,isArbitrary:b.type===Symbol.for("MATCH_VARIANT"),values:Object.keys(b.values??{}),hasDash:h!=="@",selectors({modifier:v,value:y}={}){let w=`TAILWINDPLACEHOLDER${d}`,k=ee.rule({selector:`.${w}`}),S=ee.root({nodes:[k.clone()]}),E=S.toString(),T=(e.variantMap.get(h)??[]).flatMap(([le,A])=>A),B=[];for(let le of T){let A=[],C={args:{modifier:v,value:b.values?.[y]??y},separator:e.tailwindConfig.separator,modifySelectors(V){return S.each(Ee=>{Ee.type==="rule"&&(Ee.selectors=Ee.selectors.map(Ie=>V({get className(){return Go(Ie)},selector:Ie})))}),S},format(V){A.push(V)},wrap(V){A.push(`@${V.name} ${V.params} { & }`)},container:S},he=le(C);if(A.length>0&&B.push(A),Array.isArray(he))for(let V of he)A=[],V(C),B.push(A)}let N=[],R=S.toString();E!==R&&(S.walkRules(le=>{let A=le.selector,C=(0,Zo.default)(he=>{he.walkClasses(V=>{V.value=`${h}${e.tailwindConfig.separator}${V.value}`})}).processSync(A);N.push(A.replace(C,"&").replace(w,"&"))}),S.walkAtRules(le=>{N.push(`@${le.name} (${le.params}) { & }`)}));let F=!(y in(b.values??{})),Y=b[Pt]??{},_=(()=>!(F||Y.respectPrefix===!1))();B=B.map(le=>le.map(A=>({format:A,respectPrefix:_}))),N=N.map(le=>({format:le,respectPrefix:_}));let Q={candidate:w,context:e},U=B.map(le=>rs(`.${w}`,dr(le,Q),Q).replace(`.${w}`,"&").replace("{ & }","").trim());return N.length>0&&U.push(dr(N,Q).toString().replace(`.${w}`,"&")),U}});return p}}function Uh(r,e){!r.classCache.has(e)||(r.notClassCache.add(e),r.classCache.delete(e),r.applyClassCache.delete(e),r.candidateRuleMap.delete(e),r.candidateRuleCache.delete(e),r.stylesheetCache=null)}function H_(r,e){let t=e.raws.tailwind.candidate;if(!!t){for(let i of r.ruleCache)i[1].raws.tailwind.candidate===t&&r.ruleCache.delete(i);Uh(r,t)}}function il(r,e=[],t=ee.root()){let i={disposables:[],ruleCache:new Set,candidateRuleCache:new Map,classCache:new Map,applyClassCache:new Map,notClassCache:new Set(r.blocklist??[]),postCssNodeCache:new Map,candidateRuleMap:new Map,tailwindConfig:r,changedContent:e,variantMap:new Map,stylesheetCache:null,variantOptions:new Map,markInvalidUtilityCandidate:s=>Uh(i,s),markInvalidUtilityNode:s=>H_(i,s)},n=U_(i,t);return V_(n,i),i}function Vh(r,e,t,i,n,s){let a=e.opts.from,o=i!==null;Ze.DEBUG&&console.log("Source path:",a);let l;if(o&&hr.has(a))l=hr.get(a);else if(Pi.has(n)){let p=Pi.get(n);Dt.get(p).add(a),hr.set(a,p),l=p}let c=Ph(a,r);if(l){let[p,h]=jh([...s],cs(l));if(!p&&!c)return[l,!1,h]}if(hr.has(a)){let p=hr.get(a);if(Dt.has(p)&&(Dt.get(p).delete(a),Dt.get(p).size===0)){Dt.delete(p);for(let[h,b]of Pi)b===p&&Pi.delete(h);for(let h of p.disposables.splice(0))h(p)}}Ze.DEBUG&&console.log("Setting up new context...");let f=il(t,[],r);Object.assign(f,{userConfigPath:i});let[,d]=jh([...s],cs(f));return Pi.set(n,f),hr.set(a,f),Dt.has(f)||Dt.set(f,new Set),Dt.get(f).add(a),[f,!0,d]}var Nh,Zo,Pt,Jo,el,rl,hr,Pi,Dt,Oi=P(()=>{u();ft();la();Ot();Nh=pe(Ra()),Zo=pe(it());Ci();qo();Gn();Kt();fr();Lo();Fr();bh();It();It();Yi();Be();Gi();Bo();os();Ih();Mh();ct();Vo();Pt=Symbol(),Jo={AddVariant:Symbol.for("ADD_VARIANT"),MatchVariant:Symbol.for("MATCH_VARIANT")},el={Base:1<<0,Dynamic:1<<1};rl=new WeakMap;hr=wh,Pi=vh,Dt=es});function nl(r){return r.ignore?[]:r.glob?m.env.ROLLUP_WATCH==="true"?[{type:"dependency",file:r.base}]:[{type:"dir-dependency",dir:r.base,glob:r.glob}]:[{type:"dependency",file:r.base}]}var Hh=P(()=>{u()});function Wh(r,e){return{handler:r,config:e}}var Gh,Qh=P(()=>{u();Wh.withOptions=function(r,e=()=>({})){let t=function(i){return{__options:i,handler:r(i),config:e(i)}};return t.__isOptionsFunction=!0,t.__pluginFunction=r,t.__configFunction=e,t};Gh=Wh});var sl={};Ge(sl,{default:()=>W_});var W_,al=P(()=>{u();Qh();W_=Gh});var Kh=x((z4,Yh)=>{u();var G_=(al(),sl).default,Q_={overflow:"hidden",display:"-webkit-box","-webkit-box-orient":"vertical"},Y_=G_(function({matchUtilities:r,addUtilities:e,theme:t,variants:i}){let n=t("lineClamp");r({"line-clamp":s=>({...Q_,"-webkit-line-clamp":`${s}`})},{values:n}),e([{".line-clamp-none":{"-webkit-line-clamp":"unset"}}],i("lineClamp"))},{theme:{lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"}},variants:{lineClamp:["responsive"]}});Yh.exports=Y_});function ol(r){r.content.files.length===0&&G.warn("content-problems",["The `content` option in your Tailwind CSS configuration is missing or empty.","Configure your content sources or your generated CSS will be missing styles.","https://tailwindcss.com/docs/content-configuration"]);try{let e=Kh();r.plugins.includes(e)&&(G.warn("line-clamp-in-core",["As of Tailwind CSS v3.3, the `@tailwindcss/line-clamp` plugin is now included by default.","Remove it from the `plugins` array in your configuration to eliminate this warning."]),r.plugins=r.plugins.filter(t=>t!==e))}catch{}return r}var Xh=P(()=>{u();Be()});var Zh,Jh=P(()=>{u();Zh=()=>!1});var ps,em=P(()=>{u();ps={sync:r=>[].concat(r),generateTasks:r=>[{dynamic:!1,base:".",negative:[],positive:[].concat(r),patterns:[].concat(r)}],escapePath:r=>r}});var ll,tm=P(()=>{u();ll=r=>r});var rm,im=P(()=>{u();rm=()=>""});function nm(r){let e=r,t=rm(r);return t!=="."&&(e=r.substr(t.length),e.charAt(0)==="/"&&(e=e.substr(1))),e.substr(0,2)==="./"?e=e.substr(2):e.charAt(0)==="/"&&(e=e.substr(1)),{base:t,glob:e}}var sm=P(()=>{u();im()});var ds=x(Ve=>{u();"use strict";Ve.isInteger=r=>typeof r=="number"?Number.isInteger(r):typeof r=="string"&&r.trim()!==""?Number.isInteger(Number(r)):!1;Ve.find=(r,e)=>r.nodes.find(t=>t.type===e);Ve.exceedsLimit=(r,e,t=1,i)=>i===!1||!Ve.isInteger(r)||!Ve.isInteger(e)?!1:(Number(e)-Number(r))/Number(t)>=i;Ve.escapeNode=(r,e=0,t)=>{let i=r.nodes[e];!i||(t&&i.type===t||i.type==="open"||i.type==="close")&&i.escaped!==!0&&(i.value="\\"+i.value,i.escaped=!0)};Ve.encloseBrace=r=>r.type!=="brace"?!1:r.commas>>0+r.ranges>>0==0?(r.invalid=!0,!0):!1;Ve.isInvalidBrace=r=>r.type!=="brace"?!1:r.invalid===!0||r.dollar?!0:r.commas>>0+r.ranges>>0==0||r.open!==!0||r.close!==!0?(r.invalid=!0,!0):!1;Ve.isOpenOrClose=r=>r.type==="open"||r.type==="close"?!0:r.open===!0||r.close===!0;Ve.reduce=r=>r.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Ve.flatten=(...r)=>{let e=[],t=i=>{for(let n=0;n{u();"use strict";var am=ds();om.exports=(r,e={})=>{let t=(i,n={})=>{let s=e.escapeInvalid&&am.isInvalidBrace(n),a=i.invalid===!0&&e.escapeInvalid===!0,o="";if(i.value)return(s||a)&&am.isOpenOrClose(i)?"\\"+i.value:i.value;if(i.value)return i.value;if(i.nodes)for(let l of i.nodes)o+=t(l);return o};return t(r)}});var um=x((J4,lm)=>{u();"use strict";lm.exports=function(r){return typeof r=="number"?r-r==0:typeof r=="string"&&r.trim()!==""?Number.isFinite?Number.isFinite(+r):isFinite(+r):!1}});var bm=x((e6,ym)=>{u();"use strict";var fm=um(),Wt=(r,e,t)=>{if(fm(r)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||r===e)return String(r);if(fm(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let i={relaxZeros:!0,...t};typeof i.strictZeros=="boolean"&&(i.relaxZeros=i.strictZeros===!1);let n=String(i.relaxZeros),s=String(i.shorthand),a=String(i.capture),o=String(i.wrap),l=r+":"+e+"="+n+s+a+o;if(Wt.cache.hasOwnProperty(l))return Wt.cache[l].result;let c=Math.min(r,e),f=Math.max(r,e);if(Math.abs(c-f)===1){let v=r+"|"+e;return i.capture?`(${v})`:i.wrap===!1?v:`(?:${v})`}let d=gm(r)||gm(e),p={min:r,max:e,a:c,b:f},h=[],b=[];if(d&&(p.isPadded=d,p.maxLen=String(p.max).length),c<0){let v=f<0?Math.abs(f):1;b=cm(v,Math.abs(c),p,i),c=p.a=0}return f>=0&&(h=cm(c,f,p,i)),p.negatives=b,p.positives=h,p.result=K_(b,h,i),i.capture===!0?p.result=`(${p.result})`:i.wrap!==!1&&h.length+b.length>1&&(p.result=`(?:${p.result})`),Wt.cache[l]=p,p.result};function K_(r,e,t){let i=ul(r,e,"-",!1,t)||[],n=ul(e,r,"",!1,t)||[],s=ul(r,e,"-?",!0,t)||[];return i.concat(s).concat(n).join("|")}function X_(r,e){let t=1,i=1,n=dm(r,t),s=new Set([e]);for(;r<=n&&n<=e;)s.add(n),t+=1,n=dm(r,t);for(n=hm(e+1,i)-1;r1&&o.count.pop(),o.count.push(f.count[0]),o.string=o.pattern+mm(o.count),a=c+1;continue}t.isPadded&&(d=rE(c,t,i)),f.string=d+f.pattern+mm(f.count),s.push(f),a=c+1,o=f}return s}function ul(r,e,t,i,n){let s=[];for(let a of r){let{string:o}=a;!i&&!pm(e,"string",o)&&s.push(t+o),i&&pm(e,"string",o)&&s.push(t+o)}return s}function J_(r,e){let t=[];for(let i=0;ie?1:e>r?-1:0}function pm(r,e,t){return r.some(i=>i[e]===t)}function dm(r,e){return Number(String(r).slice(0,-e)+"9".repeat(e))}function hm(r,e){return r-r%Math.pow(10,e)}function mm(r){let[e=0,t=""]=r;return t||e>1?`{${e+(t?","+t:"")}}`:""}function tE(r,e,t){return`[${r}${e-r==1?"":"-"}${e}]`}function gm(r){return/^-?(0+)\d/.test(r)}function rE(r,e,t){if(!e.isPadded)return r;let i=Math.abs(e.maxLen-String(r).length),n=t.relaxZeros!==!1;switch(i){case 0:return"";case 1:return n?"0?":"0";case 2:return n?"0{0,2}":"00";default:return n?`0{0,${i}}`:`0{${i}}`}}Wt.cache={};Wt.clearCache=()=>Wt.cache={};ym.exports=Wt});var pl=x((t6,Cm)=>{u();"use strict";var iE=(Fn(),Bn),wm=bm(),vm=r=>r!==null&&typeof r=="object"&&!Array.isArray(r),nE=r=>e=>r===!0?Number(e):String(e),fl=r=>typeof r=="number"||typeof r=="string"&&r!=="",Ii=r=>Number.isInteger(+r),cl=r=>{let e=`${r}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},sE=(r,e,t)=>typeof r=="string"||typeof e=="string"?!0:t.stringify===!0,aE=(r,e,t)=>{if(e>0){let i=r[0]==="-"?"-":"";i&&(r=r.slice(1)),r=i+r.padStart(i?e-1:e,"0")}return t===!1?String(r):r},ms=(r,e)=>{let t=r[0]==="-"?"-":"";for(t&&(r=r.slice(1),e--);r.length{r.negatives.sort((o,l)=>ol?1:0),r.positives.sort((o,l)=>ol?1:0);let i=e.capture?"":"?:",n="",s="",a;return r.positives.length&&(n=r.positives.map(o=>ms(String(o),t)).join("|")),r.negatives.length&&(s=`-(${i}${r.negatives.map(o=>ms(String(o),t)).join("|")})`),n&&s?a=`${n}|${s}`:a=n||s,e.wrap?`(${i}${a})`:a},xm=(r,e,t,i)=>{if(t)return wm(r,e,{wrap:!1,...i});let n=String.fromCharCode(r);if(r===e)return n;let s=String.fromCharCode(e);return`[${n}-${s}]`},km=(r,e,t)=>{if(Array.isArray(r)){let i=t.wrap===!0,n=t.capture?"":"?:";return i?`(${n}${r.join("|")})`:r.join("|")}return wm(r,e,t)},Sm=(...r)=>new RangeError("Invalid range arguments: "+iE.inspect(...r)),Am=(r,e,t)=>{if(t.strictRanges===!0)throw Sm([r,e]);return[]},lE=(r,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${r}" to be a number`);return[]},uE=(r,e,t=1,i={})=>{let n=Number(r),s=Number(e);if(!Number.isInteger(n)||!Number.isInteger(s)){if(i.strictRanges===!0)throw Sm([r,e]);return[]}n===0&&(n=0),s===0&&(s=0);let a=n>s,o=String(r),l=String(e),c=String(t);t=Math.max(Math.abs(t),1);let f=cl(o)||cl(l)||cl(c),d=f?Math.max(o.length,l.length,c.length):0,p=f===!1&&sE(r,e,i)===!1,h=i.transform||nE(p);if(i.toRegex&&t===1)return xm(ms(r,d),ms(e,d),!0,i);let b={negatives:[],positives:[]},v=k=>b[k<0?"negatives":"positives"].push(Math.abs(k)),y=[],w=0;for(;a?n>=s:n<=s;)i.toRegex===!0&&t>1?v(n):y.push(aE(h(n,w),d,p)),n=a?n-t:n+t,w++;return i.toRegex===!0?t>1?oE(b,i,d):km(y,null,{wrap:!1,...i}):y},fE=(r,e,t=1,i={})=>{if(!Ii(r)&&r.length>1||!Ii(e)&&e.length>1)return Am(r,e,i);let n=i.transform||(p=>String.fromCharCode(p)),s=`${r}`.charCodeAt(0),a=`${e}`.charCodeAt(0),o=s>a,l=Math.min(s,a),c=Math.max(s,a);if(i.toRegex&&t===1)return xm(l,c,!1,i);let f=[],d=0;for(;o?s>=a:s<=a;)f.push(n(s,d)),s=o?s-t:s+t,d++;return i.toRegex===!0?km(f,null,{wrap:!1,options:i}):f},gs=(r,e,t,i={})=>{if(e==null&&fl(r))return[r];if(!fl(r)||!fl(e))return Am(r,e,i);if(typeof t=="function")return gs(r,e,1,{transform:t});if(vm(t))return gs(r,e,0,t);let n={...i};return n.capture===!0&&(n.wrap=!0),t=t||n.step||1,Ii(t)?Ii(r)&&Ii(e)?uE(r,e,t,n):fE(r,e,Math.max(Math.abs(t),1),n):t!=null&&!vm(t)?lE(t,n):gs(r,e,1,t)};Cm.exports=gs});var Om=x((r6,Em)=>{u();"use strict";var cE=pl(),_m=ds(),pE=(r,e={})=>{let t=(i,n={})=>{let s=_m.isInvalidBrace(n),a=i.invalid===!0&&e.escapeInvalid===!0,o=s===!0||a===!0,l=e.escapeInvalid===!0?"\\":"",c="";if(i.isOpen===!0)return l+i.value;if(i.isClose===!0)return console.log("node.isClose",l,i.value),l+i.value;if(i.type==="open")return o?l+i.value:"(";if(i.type==="close")return o?l+i.value:")";if(i.type==="comma")return i.prev.type==="comma"?"":o?i.value:"|";if(i.value)return i.value;if(i.nodes&&i.ranges>0){let f=_m.reduce(i.nodes),d=cE(...f,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return f.length>1&&d.length>1?`(${d})`:d}if(i.nodes)for(let f of i.nodes)c+=t(f,i);return c};return t(r)};Em.exports=pE});var Pm=x((i6,Rm)=>{u();"use strict";var dE=pl(),Tm=hs(),mr=ds(),Gt=(r="",e="",t=!1)=>{let i=[];if(r=[].concat(r),e=[].concat(e),!e.length)return r;if(!r.length)return t?mr.flatten(e).map(n=>`{${n}}`):e;for(let n of r)if(Array.isArray(n))for(let s of n)i.push(Gt(s,e,t));else for(let s of e)t===!0&&typeof s=="string"&&(s=`{${s}}`),i.push(Array.isArray(s)?Gt(n,s,t):n+s);return mr.flatten(i)},hE=(r,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,i=(n,s={})=>{n.queue=[];let a=s,o=s.queue;for(;a.type!=="brace"&&a.type!=="root"&&a.parent;)a=a.parent,o=a.queue;if(n.invalid||n.dollar){o.push(Gt(o.pop(),Tm(n,e)));return}if(n.type==="brace"&&n.invalid!==!0&&n.nodes.length===2){o.push(Gt(o.pop(),["{}"]));return}if(n.nodes&&n.ranges>0){let d=mr.reduce(n.nodes);if(mr.exceedsLimit(...d,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=dE(...d,e);p.length===0&&(p=Tm(n,e)),o.push(Gt(o.pop(),p)),n.nodes=[];return}let l=mr.encloseBrace(n),c=n.queue,f=n;for(;f.type!=="brace"&&f.type!=="root"&&f.parent;)f=f.parent,c=f.queue;for(let d=0;d{u();"use strict";Im.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:` +`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nm=x((s6,Mm)=>{u();"use strict";var mE=hs(),{MAX_LENGTH:qm,CHAR_BACKSLASH:dl,CHAR_BACKTICK:gE,CHAR_COMMA:yE,CHAR_DOT:bE,CHAR_LEFT_PARENTHESES:wE,CHAR_RIGHT_PARENTHESES:vE,CHAR_LEFT_CURLY_BRACE:xE,CHAR_RIGHT_CURLY_BRACE:kE,CHAR_LEFT_SQUARE_BRACKET:$m,CHAR_RIGHT_SQUARE_BRACKET:Lm,CHAR_DOUBLE_QUOTE:SE,CHAR_SINGLE_QUOTE:AE,CHAR_NO_BREAK_SPACE:CE,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_E}=Dm(),EE=(r,e={})=>{if(typeof r!="string")throw new TypeError("Expected a string");let t=e||{},i=typeof t.maxLength=="number"?Math.min(qm,t.maxLength):qm;if(r.length>i)throw new SyntaxError(`Input length (${r.length}), exceeds max characters (${i})`);let n={type:"root",input:r,nodes:[]},s=[n],a=n,o=n,l=0,c=r.length,f=0,d=0,p,h=()=>r[f++],b=v=>{if(v.type==="text"&&o.type==="dot"&&(o.type="text"),o&&o.type==="text"&&v.type==="text"){o.value+=v.value;return}return a.nodes.push(v),v.parent=a,v.prev=o,o=v,v};for(b({type:"bos"});f0){if(a.ranges>0){a.ranges=0;let v=a.nodes.shift();a.nodes=[v,{type:"text",value:mE(a)}]}b({type:"comma",value:p}),a.commas++;continue}if(p===bE&&d>0&&a.commas===0){let v=a.nodes;if(d===0||v.length===0){b({type:"text",value:p});continue}if(o.type==="dot"){if(a.range=[],o.value+=p,o.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,o.type="text";continue}a.ranges++,a.args=[];continue}if(o.type==="range"){v.pop();let y=v[v.length-1];y.value+=o.value+p,o=y,a.ranges--;continue}b({type:"dot",value:p});continue}b({type:"text",value:p})}do if(a=s.pop(),a.type!=="root"){a.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let v=s[s.length-1],y=v.nodes.indexOf(a);v.nodes.splice(y,1,...a.nodes)}while(s.length>0);return b({type:"eos"}),n};Mm.exports=EE});var jm=x((a6,Fm)=>{u();"use strict";var Bm=hs(),OE=Om(),TE=Pm(),RE=Nm(),Le=(r,e={})=>{let t=[];if(Array.isArray(r))for(let i of r){let n=Le.create(i,e);Array.isArray(n)?t.push(...n):t.push(n)}else t=[].concat(Le.create(r,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Le.parse=(r,e={})=>RE(r,e);Le.stringify=(r,e={})=>typeof r=="string"?Bm(Le.parse(r,e),e):Bm(r,e);Le.compile=(r,e={})=>(typeof r=="string"&&(r=Le.parse(r,e)),OE(r,e));Le.expand=(r,e={})=>{typeof r=="string"&&(r=Le.parse(r,e));let t=TE(r,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Le.create=(r,e={})=>r===""||r.length<3?[r]:e.expand!==!0?Le.compile(r,e):Le.expand(r,e);Fm.exports=Le});var Di=x((o6,Wm)=>{u();"use strict";var PE=(et(),Ur),at="\\\\/",zm=`[^${at}]`,yt="\\.",IE="\\+",DE="\\?",ys="\\/",qE="(?=.)",Um="[^/]",hl=`(?:${ys}|$)`,Vm=`(?:^|${ys})`,ml=`${yt}{1,2}${hl}`,$E=`(?!${yt})`,LE=`(?!${Vm}${ml})`,ME=`(?!${yt}{0,1}${hl})`,NE=`(?!${ml})`,BE=`[^.${ys}]`,FE=`${Um}*?`,Hm={DOT_LITERAL:yt,PLUS_LITERAL:IE,QMARK_LITERAL:DE,SLASH_LITERAL:ys,ONE_CHAR:qE,QMARK:Um,END_ANCHOR:hl,DOTS_SLASH:ml,NO_DOT:$E,NO_DOTS:LE,NO_DOT_SLASH:ME,NO_DOTS_SLASH:NE,QMARK_NO_DOT:BE,STAR:FE,START_ANCHOR:Vm},jE={...Hm,SLASH_LITERAL:`[${at}]`,QMARK:zm,STAR:`${zm}*?`,DOTS_SLASH:`${yt}{1,2}(?:[${at}]|$)`,NO_DOT:`(?!${yt})`,NO_DOTS:`(?!(?:^|[${at}])${yt}{1,2}(?:[${at}]|$))`,NO_DOT_SLASH:`(?!${yt}{0,1}(?:[${at}]|$))`,NO_DOTS_SLASH:`(?!${yt}{1,2}(?:[${at}]|$))`,QMARK_NO_DOT:`[^.${at}]`,START_ANCHOR:`(?:^|[${at}])`,END_ANCHOR:`(?:[${at}]|$)`},zE={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Wm.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:zE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:PE.sep,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?jE:Hm}}});var qi=x(Re=>{u();"use strict";var UE=(et(),Ur),VE=m.platform==="win32",{REGEX_BACKSLASH:HE,REGEX_REMOVE_BACKSLASH:WE,REGEX_SPECIAL_CHARS:GE,REGEX_SPECIAL_CHARS_GLOBAL:QE}=Di();Re.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);Re.hasRegexChars=r=>GE.test(r);Re.isRegexChar=r=>r.length===1&&Re.hasRegexChars(r);Re.escapeRegex=r=>r.replace(QE,"\\$1");Re.toPosixSlashes=r=>r.replace(HE,"/");Re.removeBackslashes=r=>r.replace(WE,e=>e==="\\"?"":e);Re.supportsLookbehinds=()=>{let r=m.version.slice(1).split(".").map(Number);return r.length===3&&r[0]>=9||r[0]===8&&r[1]>=10};Re.isWindows=r=>r&&typeof r.windows=="boolean"?r.windows:VE===!0||UE.sep==="\\";Re.escapeLast=(r,e,t)=>{let i=r.lastIndexOf(e,t);return i===-1?r:r[i-1]==="\\"?Re.escapeLast(r,e,i-1):`${r.slice(0,i)}\\${r.slice(i)}`};Re.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Re.wrapOutput=(r,e={},t={})=>{let i=t.contains?"":"^",n=t.contains?"":"$",s=`${i}(?:${r})${n}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var eg=x((u6,Jm)=>{u();"use strict";var Gm=qi(),{CHAR_ASTERISK:gl,CHAR_AT:YE,CHAR_BACKWARD_SLASH:$i,CHAR_COMMA:KE,CHAR_DOT:yl,CHAR_EXCLAMATION_MARK:bl,CHAR_FORWARD_SLASH:Qm,CHAR_LEFT_CURLY_BRACE:wl,CHAR_LEFT_PARENTHESES:vl,CHAR_LEFT_SQUARE_BRACKET:XE,CHAR_PLUS:ZE,CHAR_QUESTION_MARK:Ym,CHAR_RIGHT_CURLY_BRACE:JE,CHAR_RIGHT_PARENTHESES:Km,CHAR_RIGHT_SQUARE_BRACKET:e2}=Di(),Xm=r=>r===Qm||r===$i,Zm=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},t2=(r,e)=>{let t=e||{},i=r.length-1,n=t.parts===!0||t.scanToEnd===!0,s=[],a=[],o=[],l=r,c=-1,f=0,d=0,p=!1,h=!1,b=!1,v=!1,y=!1,w=!1,k=!1,S=!1,E=!1,T=!1,B=0,N,R,F={value:"",depth:0,isGlob:!1},Y=()=>c>=i,_=()=>l.charCodeAt(c+1),Q=()=>(N=R,l.charCodeAt(++c));for(;c0&&(le=l.slice(0,f),l=l.slice(f),d-=f),U&&b===!0&&d>0?(U=l.slice(0,d),A=l.slice(d)):b===!0?(U="",A=l):U=l,U&&U!==""&&U!=="/"&&U!==l&&Xm(U.charCodeAt(U.length-1))&&(U=U.slice(0,-1)),t.unescape===!0&&(A&&(A=Gm.removeBackslashes(A)),U&&k===!0&&(U=Gm.removeBackslashes(U)));let C={prefix:le,input:r,start:f,base:U,glob:A,isBrace:p,isBracket:h,isGlob:b,isExtglob:v,isGlobstar:y,negated:S,negatedExtglob:E};if(t.tokens===!0&&(C.maxDepth=0,Xm(R)||a.push(F),C.tokens=a),t.parts===!0||t.tokens===!0){let he;for(let V=0;V{u();"use strict";var bs=Di(),Me=qi(),{MAX_LENGTH:ws,POSIX_REGEX_SOURCE:r2,REGEX_NON_SPECIAL_CHARS:i2,REGEX_SPECIAL_CHARS_BACKREF:n2,REPLACEMENTS:tg}=bs,s2=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(i){return r.map(n=>Me.escapeRegex(n)).join("..")}return t},gr=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,xl=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=tg[r]||r;let t={...e},i=typeof t.maxLength=="number"?Math.min(ws,t.maxLength):ws,n=r.length;if(n>i)throw new SyntaxError(`Input length: ${n}, exceeds maximum allowed length: ${i}`);let s={type:"bos",value:"",output:t.prepend||""},a=[s],o=t.capture?"":"?:",l=Me.isWindows(e),c=bs.globChars(l),f=bs.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:h,ONE_CHAR:b,DOTS_SLASH:v,NO_DOT:y,NO_DOT_SLASH:w,NO_DOTS_SLASH:k,QMARK:S,QMARK_NO_DOT:E,STAR:T,START_ANCHOR:B}=c,N=$=>`(${o}(?:(?!${B}${$.dot?v:d}).)*?)`,R=t.dot?"":y,F=t.dot?S:E,Y=t.bash===!0?N(t):T;t.capture&&(Y=`(${Y})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let _={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:a};r=Me.removePrefix(r,_),n=r.length;let Q=[],U=[],le=[],A=s,C,he=()=>_.index===n-1,V=_.peek=($=1)=>r[_.index+$],Ee=_.advance=()=>r[++_.index]||"",Ie=()=>r.slice(_.index+1),De=($="",ae=0)=>{_.consumed+=$,_.index+=ae},ji=$=>{_.output+=$.output!=null?$.output:$.value,De($.value)},Iv=()=>{let $=1;for(;V()==="!"&&(V(2)!=="("||V(3)==="?");)Ee(),_.start++,$++;return $%2==0?!1:(_.negated=!0,_.start++,!0)},zi=$=>{_[$]++,le.push($)},Ft=$=>{_[$]--,le.pop()},W=$=>{if(A.type==="globstar"){let ae=_.braces>0&&($.type==="comma"||$.type==="brace"),I=$.extglob===!0||Q.length&&($.type==="pipe"||$.type==="paren");$.type!=="slash"&&$.type!=="paren"&&!ae&&!I&&(_.output=_.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=Y,_.output+=A.output)}if(Q.length&&$.type!=="paren"&&(Q[Q.length-1].inner+=$.value),($.value||$.output)&&ji($),A&&A.type==="text"&&$.type==="text"){A.value+=$.value,A.output=(A.output||"")+$.value;return}$.prev=A,a.push($),A=$},Ui=($,ae)=>{let I={...f[ae],conditions:1,inner:""};I.prev=A,I.parens=_.parens,I.output=_.output;let H=(t.capture?"(":"")+I.open;zi("parens"),W({type:$,value:ae,output:_.output?"":b}),W({type:"paren",extglob:!0,value:Ee(),output:H}),Q.push(I)},Dv=$=>{let ae=$.close+(t.capture?")":""),I;if($.type==="negate"){let H=Y;if($.inner&&$.inner.length>1&&$.inner.includes("/")&&(H=N(t)),(H!==Y||he()||/^\)+$/.test(Ie()))&&(ae=$.close=`)$))${H}`),$.inner.includes("*")&&(I=Ie())&&/^\.[^\\/.]+$/.test(I)){let ce=xl(I,{...e,fastpaths:!1}).output;ae=$.close=`)${ce})${H})`}$.prev.type==="bos"&&(_.negatedExtglob=!0)}W({type:"paren",extglob:!0,value:C,output:ae}),Ft("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let $=!1,ae=r.replace(n2,(I,H,ce,Ce,ye,Bs)=>Ce==="\\"?($=!0,I):Ce==="?"?H?H+Ce+(ye?S.repeat(ye.length):""):Bs===0?F+(ye?S.repeat(ye.length):""):S.repeat(ce.length):Ce==="."?d.repeat(ce.length):Ce==="*"?H?H+Ce+(ye?Y:""):Y:H?I:`\\${I}`);return $===!0&&(t.unescape===!0?ae=ae.replace(/\\/g,""):ae=ae.replace(/\\+/g,I=>I.length%2==0?"\\\\":I?"\\":"")),ae===r&&t.contains===!0?(_.output=r,_):(_.output=Me.wrapOutput(ae,_,e),_)}for(;!he();){if(C=Ee(),C==="\0")continue;if(C==="\\"){let I=V();if(I==="/"&&t.bash!==!0||I==="."||I===";")continue;if(!I){C+="\\",W({type:"text",value:C});continue}let H=/^\\+/.exec(Ie()),ce=0;if(H&&H[0].length>2&&(ce=H[0].length,_.index+=ce,ce%2!=0&&(C+="\\")),t.unescape===!0?C=Ee():C+=Ee(),_.brackets===0){W({type:"text",value:C});continue}}if(_.brackets>0&&(C!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==!1&&C===":"){let I=A.value.slice(1);if(I.includes("[")&&(A.posix=!0,I.includes(":"))){let H=A.value.lastIndexOf("["),ce=A.value.slice(0,H),Ce=A.value.slice(H+2),ye=r2[Ce];if(ye){A.value=ce+ye,_.backtrack=!0,Ee(),!s.output&&a.indexOf(A)===1&&(s.output=b);continue}}}(C==="["&&V()!==":"||C==="-"&&V()==="]")&&(C=`\\${C}`),C==="]"&&(A.value==="["||A.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&A.value==="["&&(C="^"),A.value+=C,ji({value:C});continue}if(_.quotes===1&&C!=='"'){C=Me.escapeRegex(C),A.value+=C,ji({value:C});continue}if(C==='"'){_.quotes=_.quotes===1?0:1,t.keepQuotes===!0&&W({type:"text",value:C});continue}if(C==="("){zi("parens"),W({type:"paren",value:C});continue}if(C===")"){if(_.parens===0&&t.strictBrackets===!0)throw new SyntaxError(gr("opening","("));let I=Q[Q.length-1];if(I&&_.parens===I.parens+1){Dv(Q.pop());continue}W({type:"paren",value:C,output:_.parens?")":"\\)"}),Ft("parens");continue}if(C==="["){if(t.nobracket===!0||!Ie().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(gr("closing","]"));C=`\\${C}`}else zi("brackets");W({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||A&&A.type==="bracket"&&A.value.length===1){W({type:"text",value:C,output:`\\${C}`});continue}if(_.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(gr("opening","["));W({type:"text",value:C,output:`\\${C}`});continue}Ft("brackets");let I=A.value.slice(1);if(A.posix!==!0&&I[0]==="^"&&!I.includes("/")&&(C=`/${C}`),A.value+=C,ji({value:C}),t.literalBrackets===!1||Me.hasRegexChars(I))continue;let H=Me.escapeRegex(A.value);if(_.output=_.output.slice(0,-A.value.length),t.literalBrackets===!0){_.output+=H,A.value=H;continue}A.value=`(${o}${H}|${A.value})`,_.output+=A.value;continue}if(C==="{"&&t.nobrace!==!0){zi("braces");let I={type:"brace",value:C,output:"(",outputIndex:_.output.length,tokensIndex:_.tokens.length};U.push(I),W(I);continue}if(C==="}"){let I=U[U.length-1];if(t.nobrace===!0||!I){W({type:"text",value:C,output:C});continue}let H=")";if(I.dots===!0){let ce=a.slice(),Ce=[];for(let ye=ce.length-1;ye>=0&&(a.pop(),ce[ye].type!=="brace");ye--)ce[ye].type!=="dots"&&Ce.unshift(ce[ye].value);H=s2(Ce,t),_.backtrack=!0}if(I.comma!==!0&&I.dots!==!0){let ce=_.output.slice(0,I.outputIndex),Ce=_.tokens.slice(I.tokensIndex);I.value=I.output="\\{",C=H="\\}",_.output=ce;for(let ye of Ce)_.output+=ye.output||ye.value}W({type:"brace",value:C,output:H}),Ft("braces"),U.pop();continue}if(C==="|"){Q.length>0&&Q[Q.length-1].conditions++,W({type:"text",value:C});continue}if(C===","){let I=C,H=U[U.length-1];H&&le[le.length-1]==="braces"&&(H.comma=!0,I="|"),W({type:"comma",value:C,output:I});continue}if(C==="/"){if(A.type==="dot"&&_.index===_.start+1){_.start=_.index+1,_.consumed="",_.output="",a.pop(),A=s;continue}W({type:"slash",value:C,output:h});continue}if(C==="."){if(_.braces>0&&A.type==="dot"){A.value==="."&&(A.output=d);let I=U[U.length-1];A.type="dots",A.output+=C,A.value+=C,I.dots=!0;continue}if(_.braces+_.parens===0&&A.type!=="bos"&&A.type!=="slash"){W({type:"text",value:C,output:d});continue}W({type:"dot",value:C,output:d});continue}if(C==="?"){if(!(A&&A.value==="(")&&t.noextglob!==!0&&V()==="("&&V(2)!=="?"){Ui("qmark",C);continue}if(A&&A.type==="paren"){let H=V(),ce=C;if(H==="<"&&!Me.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(A.value==="("&&!/[!=<:]/.test(H)||H==="<"&&!/<([!=]|\w+>)/.test(Ie()))&&(ce=`\\${C}`),W({type:"text",value:C,output:ce});continue}if(t.dot!==!0&&(A.type==="slash"||A.type==="bos")){W({type:"qmark",value:C,output:E});continue}W({type:"qmark",value:C,output:S});continue}if(C==="!"){if(t.noextglob!==!0&&V()==="("&&(V(2)!=="?"||!/[!=<:]/.test(V(3)))){Ui("negate",C);continue}if(t.nonegate!==!0&&_.index===0){Iv();continue}}if(C==="+"){if(t.noextglob!==!0&&V()==="("&&V(2)!=="?"){Ui("plus",C);continue}if(A&&A.value==="("||t.regex===!1){W({type:"plus",value:C,output:p});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||_.parens>0){W({type:"plus",value:C});continue}W({type:"plus",value:p});continue}if(C==="@"){if(t.noextglob!==!0&&V()==="("&&V(2)!=="?"){W({type:"at",extglob:!0,value:C,output:""});continue}W({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let I=i2.exec(Ie());I&&(C+=I[0],_.index+=I[0].length),W({type:"text",value:C});continue}if(A&&(A.type==="globstar"||A.star===!0)){A.type="star",A.star=!0,A.value+=C,A.output=Y,_.backtrack=!0,_.globstar=!0,De(C);continue}let $=Ie();if(t.noextglob!==!0&&/^\([^?]/.test($)){Ui("star",C);continue}if(A.type==="star"){if(t.noglobstar===!0){De(C);continue}let I=A.prev,H=I.prev,ce=I.type==="slash"||I.type==="bos",Ce=H&&(H.type==="star"||H.type==="globstar");if(t.bash===!0&&(!ce||$[0]&&$[0]!=="/")){W({type:"star",value:C,output:""});continue}let ye=_.braces>0&&(I.type==="comma"||I.type==="brace"),Bs=Q.length&&(I.type==="pipe"||I.type==="paren");if(!ce&&I.type!=="paren"&&!ye&&!Bs){W({type:"star",value:C,output:""});continue}for(;$.slice(0,3)==="/**";){let Vi=r[_.index+4];if(Vi&&Vi!=="/")break;$=$.slice(3),De("/**",3)}if(I.type==="bos"&&he()){A.type="globstar",A.value+=C,A.output=N(t),_.output=A.output,_.globstar=!0,De(C);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&!Ce&&he()){_.output=_.output.slice(0,-(I.output+A.output).length),I.output=`(?:${I.output}`,A.type="globstar",A.output=N(t)+(t.strictSlashes?")":"|$)"),A.value+=C,_.globstar=!0,_.output+=I.output+A.output,De(C);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&$[0]==="/"){let Vi=$[1]!==void 0?"|$":"";_.output=_.output.slice(0,-(I.output+A.output).length),I.output=`(?:${I.output}`,A.type="globstar",A.output=`${N(t)}${h}|${h}${Vi})`,A.value+=C,_.output+=I.output+A.output,_.globstar=!0,De(C+Ee()),W({type:"slash",value:"/",output:""});continue}if(I.type==="bos"&&$[0]==="/"){A.type="globstar",A.value+=C,A.output=`(?:^|${h}|${N(t)}${h})`,_.output=A.output,_.globstar=!0,De(C+Ee()),W({type:"slash",value:"/",output:""});continue}_.output=_.output.slice(0,-A.output.length),A.type="globstar",A.output=N(t),A.value+=C,_.output+=A.output,_.globstar=!0,De(C);continue}let ae={type:"star",value:C,output:Y};if(t.bash===!0){ae.output=".*?",(A.type==="bos"||A.type==="slash")&&(ae.output=R+ae.output),W(ae);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===!0){ae.output=C,W(ae);continue}(_.index===_.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(_.output+=w,A.output+=w):t.dot===!0?(_.output+=k,A.output+=k):(_.output+=R,A.output+=R),V()!=="*"&&(_.output+=b,A.output+=b)),W(ae)}for(;_.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(gr("closing","]"));_.output=Me.escapeLast(_.output,"["),Ft("brackets")}for(;_.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(gr("closing",")"));_.output=Me.escapeLast(_.output,"("),Ft("parens")}for(;_.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(gr("closing","}"));_.output=Me.escapeLast(_.output,"{"),Ft("braces")}if(t.strictSlashes!==!0&&(A.type==="star"||A.type==="bracket")&&W({type:"maybe_slash",value:"",output:`${h}?`}),_.backtrack===!0){_.output="";for(let $ of _.tokens)_.output+=$.output!=null?$.output:$.value,$.suffix&&(_.output+=$.suffix)}return _};xl.fastpaths=(r,e)=>{let t={...e},i=typeof t.maxLength=="number"?Math.min(ws,t.maxLength):ws,n=r.length;if(n>i)throw new SyntaxError(`Input length: ${n}, exceeds maximum allowed length: ${i}`);r=tg[r]||r;let s=Me.isWindows(e),{DOT_LITERAL:a,SLASH_LITERAL:o,ONE_CHAR:l,DOTS_SLASH:c,NO_DOT:f,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:h,START_ANCHOR:b}=bs.globChars(s),v=t.dot?d:f,y=t.dot?p:f,w=t.capture?"":"?:",k={negated:!1,prefix:""},S=t.bash===!0?".*?":h;t.capture&&(S=`(${S})`);let E=R=>R.noglobstar===!0?S:`(${w}(?:(?!${b}${R.dot?c:a}).)*?)`,T=R=>{switch(R){case"*":return`${v}${l}${S}`;case".*":return`${a}${l}${S}`;case"*.*":return`${v}${S}${a}${l}${S}`;case"*/*":return`${v}${S}${o}${l}${y}${S}`;case"**":return v+E(t);case"**/*":return`(?:${v}${E(t)}${o})?${y}${l}${S}`;case"**/*.*":return`(?:${v}${E(t)}${o})?${y}${S}${a}${l}${S}`;case"**/.*":return`(?:${v}${E(t)}${o})?${a}${l}${S}`;default:{let F=/^(.*?)\.(\w+)$/.exec(R);if(!F)return;let Y=T(F[1]);return Y?Y+a+F[2]:void 0}}},B=Me.removePrefix(r,k),N=T(B);return N&&t.strictSlashes!==!0&&(N+=`${o}?`),N};rg.exports=xl});var sg=x((c6,ng)=>{u();"use strict";var a2=(et(),Ur),o2=eg(),kl=ig(),Sl=qi(),l2=Di(),u2=r=>r&&typeof r=="object"&&!Array.isArray(r),de=(r,e,t=!1)=>{if(Array.isArray(r)){let f=r.map(p=>de(p,e,t));return p=>{for(let h of f){let b=h(p);if(b)return b}return!1}}let i=u2(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let n=e||{},s=Sl.isWindows(e),a=i?de.compileRe(r,e):de.makeRe(r,e,!1,!0),o=a.state;delete a.state;let l=()=>!1;if(n.ignore){let f={...e,ignore:null,onMatch:null,onResult:null};l=de(n.ignore,f,t)}let c=(f,d=!1)=>{let{isMatch:p,match:h,output:b}=de.test(f,a,e,{glob:r,posix:s}),v={glob:r,state:o,regex:a,posix:s,input:f,output:b,match:h,isMatch:p};return typeof n.onResult=="function"&&n.onResult(v),p===!1?(v.isMatch=!1,d?v:!1):l(f)?(typeof n.onIgnore=="function"&&n.onIgnore(v),v.isMatch=!1,d?v:!1):(typeof n.onMatch=="function"&&n.onMatch(v),d?v:!0)};return t&&(c.state=o),c};de.test=(r,e,t,{glob:i,posix:n}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},a=s.format||(n?Sl.toPosixSlashes:null),o=r===i,l=o&&a?a(r):r;return o===!1&&(l=a?a(r):r,o=l===i),(o===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?o=de.matchBase(r,e,t,n):o=e.exec(l)),{isMatch:Boolean(o),match:o,output:l}};de.matchBase=(r,e,t,i=Sl.isWindows(t))=>(e instanceof RegExp?e:de.makeRe(e,t)).test(a2.basename(r));de.isMatch=(r,e,t)=>de(e,t)(r);de.parse=(r,e)=>Array.isArray(r)?r.map(t=>de.parse(t,e)):kl(r,{...e,fastpaths:!1});de.scan=(r,e)=>o2(r,e);de.compileRe=(r,e,t=!1,i=!1)=>{if(t===!0)return r.output;let n=e||{},s=n.contains?"":"^",a=n.contains?"":"$",o=`${s}(?:${r.output})${a}`;r&&r.negated===!0&&(o=`^(?!${o}).*$`);let l=de.toRegex(o,e);return i===!0&&(l.state=r),l};de.makeRe=(r,e={},t=!1,i=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let n={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(n.output=kl.fastpaths(r,e)),n.output||(n=kl(r,e)),de.compileRe(n,e,t,i)};de.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};de.constants=l2;ng.exports=de});var og=x((p6,ag)=>{u();"use strict";ag.exports=sg()});var dg=x((d6,pg)=>{u();"use strict";var lg=(Fn(),Bn),ug=jm(),ot=og(),Al=qi(),fg=r=>r===""||r==="./",cg=r=>{let e=r.indexOf("{");return e>-1&&r.indexOf("}",e)>-1},oe=(r,e,t)=>{e=[].concat(e),r=[].concat(r);let i=new Set,n=new Set,s=new Set,a=0,o=f=>{s.add(f.output),t&&t.onResult&&t.onResult(f)};for(let f=0;f!i.has(f));if(t&&c.length===0){if(t.failglob===!0)throw new Error(`No matches found for "${e.join(", ")}"`);if(t.nonull===!0||t.nullglob===!0)return t.unescape?e.map(f=>f.replace(/\\/g,"")):e}return c};oe.match=oe;oe.matcher=(r,e)=>ot(r,e);oe.isMatch=(r,e,t)=>ot(e,t)(r);oe.any=oe.isMatch;oe.not=(r,e,t={})=>{e=[].concat(e).map(String);let i=new Set,n=[],s=o=>{t.onResult&&t.onResult(o),n.push(o.output)},a=new Set(oe(r,e,{...t,onResult:s}));for(let o of n)a.has(o)||i.add(o);return[...i]};oe.contains=(r,e,t)=>{if(typeof r!="string")throw new TypeError(`Expected a string: "${lg.inspect(r)}"`);if(Array.isArray(e))return e.some(i=>oe.contains(r,i,t));if(typeof e=="string"){if(fg(r)||fg(e))return!1;if(r.includes(e)||r.startsWith("./")&&r.slice(2).includes(e))return!0}return oe.isMatch(r,e,{...t,contains:!0})};oe.matchKeys=(r,e,t)=>{if(!Al.isObject(r))throw new TypeError("Expected the first argument to be an object");let i=oe(Object.keys(r),e,t),n={};for(let s of i)n[s]=r[s];return n};oe.some=(r,e,t)=>{let i=[].concat(r);for(let n of[].concat(e)){let s=ot(String(n),t);if(i.some(a=>s(a)))return!0}return!1};oe.every=(r,e,t)=>{let i=[].concat(r);for(let n of[].concat(e)){let s=ot(String(n),t);if(!i.every(a=>s(a)))return!1}return!0};oe.all=(r,e,t)=>{if(typeof r!="string")throw new TypeError(`Expected a string: "${lg.inspect(r)}"`);return[].concat(e).every(i=>ot(i,t)(r))};oe.capture=(r,e,t)=>{let i=Al.isWindows(t),s=ot.makeRe(String(r),{...t,capture:!0}).exec(i?Al.toPosixSlashes(e):e);if(s)return s.slice(1).map(a=>a===void 0?"":a)};oe.makeRe=(...r)=>ot.makeRe(...r);oe.scan=(...r)=>ot.scan(...r);oe.parse=(r,e)=>{let t=[];for(let i of[].concat(r||[]))for(let n of ug(String(i),e))t.push(ot.parse(n,e));return t};oe.braces=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!cg(r)?[r]:ug(r,e)};oe.braceExpand=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");return oe.braces(r,{...e,expand:!0})};oe.hasBraces=cg;pg.exports=oe});function mg(r,e){let t=e.content.files;t=t.filter(o=>typeof o=="string"),t=t.map(ll);let i=ps.generateTasks(t),n=[],s=[];for(let o of i)n.push(...o.positive.map(l=>gg(l,!1))),s.push(...o.negative.map(l=>gg(l,!0)));let a=[...n,...s];return a=c2(r,a),a=a.flatMap(p2),a=a.map(f2),a}function gg(r,e){let t={original:r,base:r,ignore:e,pattern:r,glob:null};return Zh(r)&&Object.assign(t,nm(r)),t}function f2(r){let e=ll(r.base);return e=ps.escapePath(e),r.pattern=r.glob?`${e}/${r.glob}`:e,r.pattern=r.ignore?`!${r.pattern}`:r.pattern,r}function c2(r,e){let t=[];return r.userConfigPath&&r.tailwindConfig.content.relative&&(t=[me.dirname(r.userConfigPath)]),e.map(i=>(i.base=me.resolve(...t,i.base),i))}function p2(r){let e=[r];try{let t=be.realpathSync(r.base);t!==r.base&&e.push({...r,base:t})}catch{}return e}function yg(r,e,t){let i=r.tailwindConfig.content.files.filter(a=>typeof a.raw=="string").map(({raw:a,extension:o="html"})=>({content:a,extension:o})),[n,s]=h2(e,t);for(let a of n){let o=me.extname(a).slice(1);i.push({file:a,extension:o})}return[i,s]}function d2(r){if(!r.some(s=>s.includes("**")&&!wg.test(s)))return()=>{};let t=[],i=[];for(let s of r){let a=hg.default.matcher(s);wg.test(s)&&i.push(a),t.push(a)}let n=!1;return s=>{if(n||i.some(f=>f(s)))return;let a=t.findIndex(f=>f(s));if(a===-1)return;let o=r[a],l=me.relative(m.cwd(),o);l[0]!=="."&&(l=`./${l}`);let c=bg.find(f=>s.includes(f));c&&(n=!0,G.warn("broad-content-glob-pattern",[`Your \`content\` configuration includes a pattern which looks like it's accidentally matching all of \`${c}\` and can cause serious performance issues.`,`Pattern: \`${l}\``,"See our documentation for recommendations:","https://tailwindcss.com/docs/content-configuration#pattern-recommendations"]))}}function h2(r,e){let t=r.map(o=>o.pattern),i=new Map,n=d2(t),s=new Set;Ze.DEBUG&&console.time("Finding changed files");let a=ps.sync(t,{absolute:!0});for(let o of a){n(o);let l=e.get(o)||-1/0,c=be.statSync(o).mtimeMs;c>l&&(s.add(o),i.set(o,c))}return Ze.DEBUG&&console.timeEnd("Finding changed files"),[s,i]}var hg,bg,wg,vg=P(()=>{u();ft();et();Jh();em();tm();sm();It();Be();hg=pe(dg());bg=["node_modules"],wg=new RegExp(`(${bg.map(r=>String.raw`\b${r}\b`).join("|")})`)});function xg(){}var kg=P(()=>{u()});function b2(r,e){for(let t of e){let i=`${r}${t}`;if(be.existsSync(i)&&be.statSync(i).isFile())return i}for(let t of e){let i=`${r}/index${t}`;if(be.existsSync(i))return i}return null}function*Sg(r,e,t,i=me.extname(r)){let n=b2(me.resolve(e,r),m2.includes(i)?g2:y2);if(n===null||t.has(n))return;t.add(n),yield n,e=me.dirname(n),i=me.extname(n);let s=be.readFileSync(n,"utf-8");for(let a of[...s.matchAll(/import[\s\S]*?['"](.{3,}?)['"]/gi),...s.matchAll(/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi),...s.matchAll(/require\(['"`](.+)['"`]\)/gi)])!a[1].startsWith(".")||(yield*Sg(a[1],e,t,i))}function Cl(r){return r===null?new Set:new Set(Sg(r,me.dirname(r),new Set))}var m2,g2,y2,Ag=P(()=>{u();ft();et();m2=[".js",".cjs",".mjs"],g2=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],y2=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"]});function w2(r,e){if(_l.has(r))return _l.get(r);let t=mg(r,e);return _l.set(r,t).get(r)}function v2(r){let e=aa(r);if(e!==null){let[i,n,s,a]=_g.get(e)||[],o=Cl(e),l=!1,c=new Map;for(let p of o){let h=be.statSync(p).mtimeMs;c.set(p,h),(!a||!a.has(p)||h>a.get(p))&&(l=!0)}if(!l)return[i,e,n,s];for(let p of o)delete hf.cache[p];let f=ol(zr(xg(e))),d=Wi(f);return _g.set(e,[f,d,o,c]),[f,e,d,o]}let t=zr(r?.config??r??{});return t=ol(t),[t,null,Wi(t),[]]}function El(r){return({tailwindDirectives:e,registerDependency:t})=>(i,n)=>{let[s,a,o,l]=v2(r),c=new Set(l);if(e.size>0){c.add(n.opts.from);for(let b of n.messages)b.type==="dependency"&&c.add(b.file)}let[f,,d]=Vh(i,n,s,a,o,c),p=cs(f),h=w2(f,s);if(e.size>0){for(let y of h)for(let w of nl(y))t(w);let[b,v]=yg(f,h,p);for(let y of b)f.changedContent.push(y);for(let[y,w]of v.entries())d.set(y,w)}for(let b of l)t({type:"dependency",file:b});for(let[b,v]of d.entries())p.set(b,v);return f}}var Cg,_g,_l,Eg=P(()=>{u();ft();Cg=pe(Fs());wf();sa();oc();Oi();Hh();Xh();vg();kg();Ag();_g=new Cg.default({maxSize:100}),_l=new WeakMap});function Ol(r){let e=new Set,t=new Set,i=new Set;if(r.walkAtRules(n=>{n.name==="apply"&&i.add(n),n.name==="import"&&(n.params==='"tailwindcss/base"'||n.params==="'tailwindcss/base'"?(n.name="tailwind",n.params="base"):n.params==='"tailwindcss/components"'||n.params==="'tailwindcss/components'"?(n.name="tailwind",n.params="components"):n.params==='"tailwindcss/utilities"'||n.params==="'tailwindcss/utilities'"?(n.name="tailwind",n.params="utilities"):(n.params==='"tailwindcss/screens"'||n.params==="'tailwindcss/screens'"||n.params==='"tailwindcss/variants"'||n.params==="'tailwindcss/variants'")&&(n.name="tailwind",n.params="variants")),n.name==="tailwind"&&(n.params==="screens"&&(n.params="variants"),e.add(n.params)),["layer","responsive","variants"].includes(n.name)&&(["responsive","variants"].includes(n.name)&&G.warn(`${n.name}-at-rule-deprecated`,[`The \`@${n.name}\` directive has been deprecated in Tailwind CSS v3.0.`,"Use `@layer utilities` or `@layer components` instead.","https://tailwindcss.com/docs/upgrade-guide#replace-variants-with-layer"]),t.add(n))}),!e.has("base")||!e.has("components")||!e.has("utilities")){for(let n of t)if(n.name==="layer"&&["base","components","utilities"].includes(n.params)){if(!e.has(n.params))throw n.error(`\`@layer ${n.params}\` is used but no matching \`@tailwind ${n.params}\` directive is present.`)}else if(n.name==="responsive"){if(!e.has("utilities"))throw n.error("`@responsive` is used but `@tailwind utilities` is missing.")}else if(n.name==="variants"&&!e.has("utilities"))throw n.error("`@variants` is used but `@tailwind utilities` is missing.")}return{tailwindDirectives:e,applyDirectives:i}}var Og=P(()=>{u();Be()});function Qt(r,e=void 0,t=void 0){return r.map(i=>{let n=i.clone();return t!==void 0&&(n.raws.tailwind={...n.raws.tailwind,...t}),e!==void 0&&Tg(n,s=>{if(s.raws.tailwind?.preserveSource===!0&&s.source)return!1;s.source=e}),n})}function Tg(r,e){e(r)!==!1&&r.each?.(t=>Tg(t,e))}var Rg=P(()=>{u()});function Tl(r){return r=Array.isArray(r)?r:[r],r=r.map(e=>e instanceof RegExp?e.source:e),r.join("")}function Ne(r){return new RegExp(Tl(r),"g")}function qt(r){return`(?:${r.map(Tl).join("|")})`}function Rl(r){return`(?:${Tl(r)})?`}function Ig(r){return r&&x2.test(r)?r.replace(Pg,"\\$&"):r||""}var Pg,x2,Dg=P(()=>{u();Pg=/[\\^$.*+?()[\]{}|]/g,x2=RegExp(Pg.source)});function qg(r){let e=Array.from(k2(r));return t=>{let i=[];for(let n of e)for(let s of t.match(n)??[])i.push(C2(s));for(let n of i.slice()){let s=ve(n,".");for(let a=0;a=s.length-1){i.push(o);continue}let l=Number(s[a+1]);isNaN(l)?i.push(o):a++}}return i}}function*k2(r){let e=r.tailwindConfig.separator,t=r.tailwindConfig.prefix!==""?Rl(Ne([/-?/,Ig(r.tailwindConfig.prefix)])):"",i=qt([/\[[^\s:'"`]+:[^\s\[\]]+\]/,/\[[^\s:'"`\]]+:[^\s]+?\[[^\s]+\][^\s]+?\]/,Ne([qt([/-?(?:\w+)/,/@(?:\w+)/]),Rl(qt([Ne([qt([/-(?:\w+-)*\['[^\s]+'\]/,/-(?:\w+-)*\["[^\s]+"\]/,/-(?:\w+-)*\[`[^\s]+`\]/,/-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s:\[\]]+\]/]),/(?![{([]])/,/(?:\/[^\s'"`\\><$]*)?/]),Ne([qt([/-(?:\w+-)*\['[^\s]+'\]/,/-(?:\w+-)*\["[^\s]+"\]/,/-(?:\w+-)*\[`[^\s]+`\]/,/-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s\[\]]+\]/]),/(?![{([]])/,/(?:\/[^\s'"`\\$]*)?/]),/[-\/][^\s'"`\\$={><]*/]))])]),n=[qt([Ne([/@\[[^\s"'`]+\](\/[^\s"'`]+)?/,e]),Ne([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]\/[\w_-]+/,e]),Ne([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/,e]),Ne([/[^\s"'`\[\\]+/,e])]),qt([Ne([/([^\s"'`\[\\]+-)?\[[^\s`]+\]\/[\w_-]+/,e]),Ne([/([^\s"'`\[\\]+-)?\[[^\s`]+\]/,e]),Ne([/[^\s`\[\\]+/,e])])];for(let s of n)yield Ne(["((?=((",s,")+))\\2)?",/!?/,t,i]);yield/[^<>"'`\s.(){}[\]#=%$][^<>"'`\s(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g}function C2(r){if(!r.includes("-["))return r;let e=0,t=[],i=r.matchAll(S2);i=Array.from(i).flatMap(n=>{let[,...s]=n;return s.map((a,o)=>Object.assign([],n,{index:n.index+o,0:a}))});for(let n of i){let s=n[0],a=t[t.length-1];if(s===a?t.pop():(s==="'"||s==='"'||s==="`")&&t.push(s),!a){if(s==="["){e++;continue}else if(s==="]"){e--;continue}if(e<0)return r.substring(0,n.index-1);if(e===0&&!A2.test(s))return r.substring(0,n.index)}}return r}var S2,A2,$g=P(()=>{u();Dg();zt();S2=/([\[\]'"`])([^\[\]'"`])?/g,A2=/[^"'`\s<>\]]+/});function _2(r,e){let t=r.tailwindConfig.content.extract;return t[e]||t.DEFAULT||Mg[e]||Mg.DEFAULT(r)}function E2(r,e){let t=r.content.transform;return t[e]||t.DEFAULT||Ng[e]||Ng.DEFAULT}function O2(r,e,t,i){Li.has(e)||Li.set(e,new Lg.default({maxSize:25e3}));for(let n of r.split(` +`))if(n=n.trim(),!i.has(n))if(i.add(n),Li.get(e).has(n))for(let s of Li.get(e).get(n))t.add(s);else{let s=e(n).filter(o=>o!=="!*"),a=new Set(s);for(let o of a)t.add(o);Li.get(e).set(n,a)}}function T2(r,e){let t=e.offsets.sort(r),i={base:new Set,defaults:new Set,components:new Set,utilities:new Set,variants:new Set};for(let[n,s]of t)i[n.layer].add(s);return i}function Pl(r){return async e=>{let t={base:null,components:null,utilities:null,variants:null};if(e.walkAtRules(y=>{y.name==="tailwind"&&Object.keys(t).includes(y.params)&&(t[y.params]=y)}),Object.values(t).every(y=>y===null))return e;let i=new Set([...r.candidates??[],gt]),n=new Set;bt.DEBUG&&console.time("Reading changed files");let s=[];for(let y of r.changedContent){let w=E2(r.tailwindConfig,y.extension),k=_2(r,y.extension);s.push([y,{transformer:w,extractor:k}])}let a=500;for(let y=0;y{S=k?await be.promises.readFile(k,"utf8"):S,O2(E(S),T,i,n)}))}bt.DEBUG&&console.timeEnd("Reading changed files");let o=r.classCache.size;bt.DEBUG&&console.time("Generate rules"),bt.DEBUG&&console.time("Sorting candidates");let l=new Set([...i].sort((y,w)=>y===w?0:y{let w=y.raws.tailwind?.parentLayer;return w==="components"?t.components!==null:w==="utilities"?t.utilities!==null:!0});t.variants?(t.variants.before(Qt(b,t.variants.source,{layer:"variants"})),t.variants.remove()):b.length>0&&e.append(Qt(b,e.source,{layer:"variants"})),e.source.end=e.source.end??e.source.start;let v=b.some(y=>y.raws.tailwind?.parentLayer==="utilities");t.utilities&&p.size===0&&!v&&G.warn("content-problems",["No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.","https://tailwindcss.com/docs/content-configuration"]),bt.DEBUG&&(console.log("Potential classes: ",i.size),console.log("Active contexts: ",es.size)),r.changedContent=[],e.walkAtRules("layer",y=>{Object.keys(t).includes(y.params)&&y.remove()})}}var Lg,bt,Mg,Ng,Li,Bg=P(()=>{u();ft();Lg=pe(Fs());It();os();Be();Rg();$g();bt=Ze,Mg={DEFAULT:qg},Ng={DEFAULT:r=>r,svelte:r=>r.replace(/(?:^|\s)class:/g," ")};Li=new WeakMap});function xs(r){let e=new Map;ee.root({nodes:[r.clone()]}).walkRules(s=>{(0,vs.default)(a=>{a.walkClasses(o=>{let l=o.parent.toString(),c=e.get(l);c||e.set(l,c=new Set),c.add(o.value)})}).processSync(s.selector)});let i=Array.from(e.values(),s=>Array.from(s)),n=i.flat();return Object.assign(n,{groups:i})}function Il(r){return R2.astSync(r)}function Fg(r,e){let t=new Set;for(let i of r)t.add(i.split(e).pop());return Array.from(t)}function jg(r,e){let t=r.tailwindConfig.prefix;return typeof t=="function"?t(e):t+e}function*zg(r){for(yield r;r.parent;)yield r.parent,r=r.parent}function P2(r,e={}){let t=r.nodes;r.nodes=[];let i=r.clone(e);return r.nodes=t,i}function I2(r){for(let e of zg(r))if(r!==e){if(e.type==="root")break;r=P2(e,{nodes:[r]})}return r}function D2(r,e){let t=new Map;return r.walkRules(i=>{for(let a of zg(i))if(a.raws.tailwind?.layer!==void 0)return;let n=I2(i),s=e.offsets.create("user");for(let a of xs(i)){let o=t.get(a)||[];t.set(a,o),o.push([{layer:"user",sort:s,important:!1},n])}}),t}function q2(r,e){for(let t of r){if(e.notClassCache.has(t)||e.applyClassCache.has(t))continue;if(e.classCache.has(t)){e.applyClassCache.set(t,e.classCache.get(t).map(([n,s])=>[n,s.clone()]));continue}let i=Array.from(Yo(t,e));if(i.length===0){e.notClassCache.add(t);continue}e.applyClassCache.set(t,i)}return e.applyClassCache}function $2(r){let e=null;return{get:t=>(e=e||r(),e.get(t)),has:t=>(e=e||r(),e.has(t))}}function L2(r){return{get:e=>r.flatMap(t=>t.get(e)||[]),has:e=>r.some(t=>t.has(e))}}function Ug(r){let e=r.split(/[\s\t\n]+/g);return e[e.length-1]==="!important"?[e.slice(0,-1),!0]:[e,!1]}function Vg(r,e,t){let i=new Set,n=[];if(r.walkAtRules("apply",l=>{let[c]=Ug(l.params);for(let f of c)i.add(f);n.push(l)}),n.length===0)return;let s=L2([t,q2(i,e)]);function a(l,c,f){let d=Il(l),p=Il(c),b=Il(`.${Te(f)}`).nodes[0].nodes[0];return d.each(v=>{let y=new Set;p.each(w=>{let k=!1;w=w.clone(),w.walkClasses(S=>{S.value===b.value&&(k||(S.replaceWith(...v.nodes.map(E=>E.clone())),y.add(w),k=!0))})});for(let w of y){let k=[[]];for(let S of w.nodes)S.type==="combinator"?(k.push(S),k.push([])):k[k.length-1].push(S);w.nodes=[];for(let S of k)Array.isArray(S)&&S.sort((E,T)=>E.type==="tag"&&T.type==="class"?-1:E.type==="class"&&T.type==="tag"?1:E.type==="class"&&T.type==="pseudo"&&T.value.startsWith("::")?-1:E.type==="pseudo"&&E.value.startsWith("::")&&T.type==="class"?1:0),w.nodes=w.nodes.concat(S)}v.replaceWith(...y)}),d.toString()}let o=new Map;for(let l of n){let[c]=o.get(l.parent)||[[],l.source];o.set(l.parent,[c,l.source]);let[f,d]=Ug(l.params);if(l.parent.type==="atrule"){if(l.parent.name==="screen"){let p=l.parent.params;throw l.error(`@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${f.map(h=>`${p}:${h}`).join(" ")} instead.`)}throw l.error(`@apply is not supported within nested at-rules like @${l.parent.name}. You can fix this by un-nesting @${l.parent.name}.`)}for(let p of f){if([jg(e,"group"),jg(e,"peer")].includes(p))throw l.error(`@apply should not be used with the '${p}' utility`);if(!s.has(p))throw l.error(`The \`${p}\` class does not exist. If \`${p}\` is a custom class, make sure it is defined within a \`@layer\` directive.`);let h=s.get(p);for(let[,b]of h)b.type!=="atrule"&&b.walkRules(()=>{throw l.error([`The \`${p}\` class cannot be used with \`@apply\` because \`@apply\` does not currently support nested CSS.`,"Rewrite the selector without nesting or configure the `tailwindcss/nesting` plugin:","https://tailwindcss.com/docs/using-with-preprocessors#nesting"].join(` +`))});c.push([p,d,h])}}for(let[l,[c,f]]of o){let d=[];for(let[h,b,v]of c){let y=[h,...Fg([h],e.tailwindConfig.separator)];for(let[w,k]of v){let S=xs(l),E=xs(k);if(E=E.groups.filter(R=>R.some(F=>y.includes(F))).flat(),E=E.concat(Fg(E,e.tailwindConfig.separator)),S.some(R=>E.includes(R)))throw k.error(`You cannot \`@apply\` the \`${h}\` utility here because it creates a circular dependency.`);let B=ee.root({nodes:[k.clone()]});B.walk(R=>{R.source=f}),(k.type!=="atrule"||k.type==="atrule"&&k.name!=="keyframes")&&B.walkRules(R=>{if(!xs(R).some(U=>U===h)){R.remove();return}let F=typeof e.tailwindConfig.important=="string"?e.tailwindConfig.important:null,_=l.raws.tailwind!==void 0&&F&&l.selector.indexOf(F)===0?l.selector.slice(F.length):l.selector;_===""&&(_=l.selector),R.selector=a(_,R.selector,h),F&&_!==l.selector&&(R.selector=is(R.selector,F)),R.walkDecls(U=>{U.important=w.important||b});let Q=(0,vs.default)().astSync(R.selector);Q.each(U=>pr(U)),R.selector=Q.toString()}),!!B.nodes[0]&&d.push([w.sort,B.nodes[0]])}}let p=e.offsets.sort(d).map(h=>h[1]);l.after(p)}for(let l of n)l.parent.nodes.length>1?l.remove():l.parent.remove();Vg(r,e,t)}function Dl(r){return e=>{let t=$2(()=>D2(e,r));Vg(e,r,t)}}var vs,R2,Hg=P(()=>{u();Ot();vs=pe(it());os();fr();Wo();ts();R2=(0,vs.default)()});var Wg=x((nq,ks)=>{u();(function(){"use strict";function r(i,n,s){if(!i)return null;r.caseSensitive||(i=i.toLowerCase());var a=r.threshold===null?null:r.threshold*i.length,o=r.thresholdAbsolute,l;a!==null&&o!==null?l=Math.min(a,o):a!==null?l=a:o!==null?l=o:l=null;var c,f,d,p,h,b=n.length;for(h=0;hs)return s+1;var l=[],c,f,d,p,h;for(c=0;c<=o;c++)l[c]=[c];for(f=0;f<=a;f++)l[0][f]=f;for(c=1;c<=o;c++){for(d=e,p=1,c>s&&(p=c-s),h=o+1,h>s+c&&(h=s+c),f=1;f<=a;f++)fh?l[c][f]=s+1:n.charAt(c-1)===i.charAt(f-1)?l[c][f]=l[c-1][f-1]:l[c][f]=Math.min(l[c-1][f-1]+1,Math.min(l[c][f-1]+1,l[c-1][f]+1)),l[c][f]s)return s+1}return l[o][a]}})()});var Qg=x((sq,Gg)=>{u();var ql="(".charCodeAt(0),$l=")".charCodeAt(0),Ss="'".charCodeAt(0),Ll='"'.charCodeAt(0),Ml="\\".charCodeAt(0),yr="/".charCodeAt(0),Nl=",".charCodeAt(0),Bl=":".charCodeAt(0),As="*".charCodeAt(0),M2="u".charCodeAt(0),N2="U".charCodeAt(0),B2="+".charCodeAt(0),F2=/^[a-f0-9?-]+$/i;Gg.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d{u();Yg.exports=function r(e,t,i){var n,s,a,o;for(n=0,s=e.length;n{u();function Xg(r,e){var t=r.type,i=r.value,n,s;return e&&(s=e(r))!==void 0?s:t==="word"||t==="space"?i:t==="string"?(n=r.quote||"",n+i+(r.unclosed?"":n)):t==="comment"?"/*"+i+(r.unclosed?"":"*/"):t==="div"?(r.before||"")+i+(r.after||""):Array.isArray(r.nodes)?(n=Zg(r.nodes,e),t!=="function"?n:i+"("+(r.before||"")+n+(r.after||"")+(r.unclosed?"":")")):i}function Zg(r,e){var t,i;if(Array.isArray(r)){for(t="",i=r.length-1;~i;i-=1)t=Xg(r[i],e)+t;return t}return Xg(r,e)}Jg.exports=Zg});var ry=x((lq,ty)=>{u();var Cs="-".charCodeAt(0),_s="+".charCodeAt(0),Fl=".".charCodeAt(0),j2="e".charCodeAt(0),z2="E".charCodeAt(0);function U2(r){var e=r.charCodeAt(0),t;if(e===_s||e===Cs){if(t=r.charCodeAt(1),t>=48&&t<=57)return!0;var i=r.charCodeAt(2);return t===Fl&&i>=48&&i<=57}return e===Fl?(t=r.charCodeAt(1),t>=48&&t<=57):e>=48&&e<=57}ty.exports=function(r){var e=0,t=r.length,i,n,s;if(t===0||!U2(r))return!1;for(i=r.charCodeAt(e),(i===_s||i===Cs)&&e++;e57));)e+=1;if(i=r.charCodeAt(e),n=r.charCodeAt(e+1),i===Fl&&n>=48&&n<=57)for(e+=2;e57));)e+=1;if(i=r.charCodeAt(e),n=r.charCodeAt(e+1),s=r.charCodeAt(e+2),(i===j2||i===z2)&&(n>=48&&n<=57||(n===_s||n===Cs)&&s>=48&&s<=57))for(e+=n===_s||n===Cs?3:2;e57));)e+=1;return{number:r.slice(0,e),unit:r.slice(e)}}});var ay=x((uq,sy)=>{u();var V2=Qg(),iy=Kg(),ny=ey();function $t(r){return this instanceof $t?(this.nodes=V2(r),this):new $t(r)}$t.prototype.toString=function(){return Array.isArray(this.nodes)?ny(this.nodes):""};$t.prototype.walk=function(r,e){return iy(this.nodes,r,e),this};$t.unit=ry();$t.walk=iy;$t.stringify=ny;sy.exports=$t});function zl(r){return typeof r=="object"&&r!==null}function H2(r,e){let t=kt(e);do if(t.pop(),(0,Mi.default)(r,t)!==void 0)break;while(t.length);return t.length?t:void 0}function br(r){return typeof r=="string"?r:r.reduce((e,t,i)=>t.includes(".")?`${e}[${t}]`:i===0?t:`${e}.${t}`,"")}function ly(r){return r.map(e=>`'${e}'`).join(", ")}function uy(r){return ly(Object.keys(r))}function Ul(r,e,t,i={}){let n=Array.isArray(e)?br(e):e.replace(/^['"]+|['"]+$/g,""),s=Array.isArray(e)?e:kt(n),a=(0,Mi.default)(r.theme,s,t);if(a===void 0){let l=`'${n}' does not exist in your theme config.`,c=s.slice(0,-1),f=(0,Mi.default)(r.theme,c);if(zl(f)){let d=Object.keys(f).filter(h=>Ul(r,[...c,h]).isValid),p=(0,oy.default)(s[s.length-1],d);p?l+=` Did you mean '${br([...c,p])}'?`:d.length>0&&(l+=` '${br(c)}' has the following valid keys: ${ly(d)}`)}else{let d=H2(r.theme,n);if(d){let p=(0,Mi.default)(r.theme,d);zl(p)?l+=` '${br(d)}' has the following keys: ${uy(p)}`:l+=` '${br(d)}' is not an object.`}else l+=` Your theme has the following top-level keys: ${uy(r.theme)}`}return{isValid:!1,error:l}}if(!(typeof a=="string"||typeof a=="number"||typeof a=="function"||a instanceof String||a instanceof Number||Array.isArray(a))){let l=`'${n}' was found but does not resolve to a string.`;if(zl(a)){let c=Object.keys(a).filter(f=>Ul(r,[...s,f]).isValid);c.length&&(l+=` Did you mean something like '${br([...s,c[0]])}'?`)}return{isValid:!1,error:l}}let[o]=s;return{isValid:!0,value:mt(o)(a,i)}}function W2(r,e,t){e=e.map(n=>fy(r,n,t));let i=[""];for(let n of e)n.type==="div"&&n.value===","?i.push(""):i[i.length-1]+=jl.default.stringify(n);return i}function fy(r,e,t){if(e.type==="function"&&t[e.value]!==void 0){let i=W2(r,e.nodes,t);e.type="word",e.value=t[e.value](r,...i)}return e}function G2(r,e,t){return Object.keys(t).some(n=>e.includes(`${n}(`))?(0,jl.default)(e).walk(n=>{fy(r,n,t)}).toString():e}function*Y2(r){r=r.replace(/^['"]+|['"]+$/g,"");let e=r.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/),t;yield[r,void 0],e&&(r=e[1],t=e[2],yield[r,t])}function K2(r,e,t){let i=Array.from(Y2(e)).map(([n,s])=>Object.assign(Ul(r,n,t,{opacityValue:s}),{resolvedPath:n,alpha:s}));return i.find(n=>n.isValid)??i[0]}function cy(r){let e=r.tailwindConfig,t={theme:(i,n,...s)=>{let{isValid:a,value:o,error:l,alpha:c}=K2(e,n,s.length?s:void 0);if(!a){let p=i.parent,h=p?.raws.tailwind?.candidate;if(p&&h!==void 0){r.markInvalidUtilityNode(p),p.remove(),G.warn("invalid-theme-key-in-class",[`The utility \`${h}\` contains an invalid theme value and was not generated.`]);return}throw i.error(l)}let f=Xt(o),d=f!==void 0&&typeof f=="function";return(c!==void 0||d)&&(c===void 0&&(c=1),o=Je(f,c,f)),o},screen:(i,n)=>{n=n.replace(/^['"]+/g,"").replace(/['"]+$/g,"");let a=Rt(e.theme.screens).find(({name:o})=>o===n);if(!a)throw i.error(`The '${n}' screen does not exist in your theme.`);return Tt(a)}};return i=>{i.walk(n=>{let s=Q2[n.type];s!==void 0&&(n[s]=G2(n,n[s],t))})}}var Mi,oy,jl,Q2,py=P(()=>{u();Mi=pe(Ra()),oy=pe(Wg());Ci();jl=pe(ay());Zn();Yn();Yi();Lr();Fr();Be();Q2={atrule:"params",decl:"value"}});function dy({tailwindConfig:{theme:r}}){return function(e){e.walkAtRules("screen",t=>{let i=t.params,s=Rt(r.screens).find(({name:a})=>a===i);if(!s)throw t.error(`No \`${i}\` screen found.`);t.name="media",t.params=Tt(s)})}}var hy=P(()=>{u();Zn();Yn()});function X2(r){let e=r.filter(o=>o.type!=="pseudo"||o.nodes.length>0?!0:o.value.startsWith("::")||[":before",":after",":first-line",":first-letter"].includes(o.value)).reverse(),t=new Set(["tag","class","id","attribute"]),i=e.findIndex(o=>t.has(o.type));if(i===-1)return e.reverse().join("").trim();let n=e[i],s=my[n.type]?my[n.type](n):n;e=e.slice(0,i);let a=e.findIndex(o=>o.type==="combinator"&&o.value===">");return a!==-1&&(e.splice(0,a),e.unshift(Es.default.universal())),[s,...e.reverse()].join("").trim()}function J2(r){return Vl.has(r)||Vl.set(r,Z2.transformSync(r)),Vl.get(r)}function Hl({tailwindConfig:r}){return e=>{let t=new Map,i=new Set;if(e.walkAtRules("defaults",n=>{if(n.nodes&&n.nodes.length>0){i.add(n);return}let s=n.params;t.has(s)||t.set(s,new Set),t.get(s).add(n.parent),n.remove()}),we(r,"optimizeUniversalDefaults"))for(let n of i){let s=new Map,a=t.get(n.params)??[];for(let o of a)for(let l of J2(o.selector)){let c=l.includes(":-")||l.includes("::-")||l.includes(":has")?l:"__DEFAULT__",f=s.get(c)??new Set;s.set(c,f),f.add(l)}if(s.size===0){n.remove();continue}for(let[,o]of s){let l=ee.rule({source:n.source});l.selectors=[...o],l.append(n.nodes.map(c=>c.clone())),n.before(l)}n.remove()}else if(i.size){let n=ee.rule({selectors:["*","::before","::after"]});for(let a of i)n.append(a.nodes),n.parent||a.before(n),n.source||(n.source=a.source),a.remove();let s=n.clone({selectors:["::backdrop"]});n.after(s)}}}var Es,my,Z2,Vl,gy=P(()=>{u();Ot();Es=pe(it());ct();my={id(r){return Es.default.attribute({attribute:"id",operator:"=",value:r.value,quoteMark:'"'})}};Z2=(0,Es.default)(r=>r.map(e=>{let t=e.split(i=>i.type==="combinator"&&i.value===" ").pop();return X2(t)})),Vl=new Map});function Wl(){function r(e){let t=null;e.each(i=>{if(!eO.has(i.type)){t=null;return}if(t===null){t=i;return}let n=yy[i.type];i.type==="atrule"&&i.name==="font-face"?t=i:n.every(s=>(i[s]??"").replace(/\s+/g," ")===(t[s]??"").replace(/\s+/g," "))?(i.nodes&&t.append(i.nodes),i.remove()):t=i}),e.each(i=>{i.type==="atrule"&&r(i)})}return e=>{r(e)}}var yy,eO,by=P(()=>{u();yy={atrule:["name","params"],rule:["selector"]},eO=new Set(Object.keys(yy))});function Gl(){return r=>{r.walkRules(e=>{let t=new Map,i=new Set([]),n=new Map;e.walkDecls(s=>{if(s.parent===e){if(t.has(s.prop)){if(t.get(s.prop).value===s.value){i.add(t.get(s.prop)),t.set(s.prop,s);return}n.has(s.prop)||n.set(s.prop,new Set),n.get(s.prop).add(t.get(s.prop)),n.get(s.prop).add(s)}t.set(s.prop,s)}});for(let s of i)s.remove();for(let s of n.values()){let a=new Map;for(let o of s){let l=rO(o.value);l!==null&&(a.has(l)||a.set(l,new Set),a.get(l).add(o))}for(let o of a.values()){let l=Array.from(o).slice(0,-1);for(let c of l)c.remove()}}})}}function rO(r){let e=/^-?\d*.?\d+([\w%]+)?$/g.exec(r);return e?e[1]??tO:null}var tO,wy=P(()=>{u();tO=Symbol("unitless-number")});function iO(r){if(!r.walkAtRules)return;let e=new Set;if(r.walkAtRules("apply",t=>{e.add(t.parent)}),e.size!==0)for(let t of e){let i=[],n=[];for(let s of t.nodes)s.type==="atrule"&&s.name==="apply"?(n.length>0&&(i.push(n),n=[]),i.push([s])):n.push(s);if(n.length>0&&i.push(n),i.length!==1){for(let s of[...i].reverse()){let a=t.clone({nodes:[]});a.append(s),t.after(a)}t.remove()}}}function Os(){return r=>{iO(r)}}var vy=P(()=>{u()});function Ts(r){return async function(e,t){let{tailwindDirectives:i,applyDirectives:n}=Ol(e);Os()(e,t);let s=r({tailwindDirectives:i,applyDirectives:n,registerDependency(a){t.messages.push({plugin:"tailwindcss",parent:t.opts.from,...a})},createContext(a,o){return il(a,o,e)}})(e,t);if(s.tailwindConfig.separator==="-")throw new Error("The '-' character cannot be used as a custom separator in JIT mode due to parsing ambiguity. Please use another character like '_' instead.");Rf(s.tailwindConfig),await Pl(s)(e,t),Os()(e,t),Dl(s)(e,t),cy(s)(e,t),dy(s)(e,t),Hl(s)(e,t),Wl(s)(e,t),Gl(s)(e,t)}}var xy=P(()=>{u();Og();Bg();Hg();py();hy();gy();by();wy();vy();Oi();ct()});function ky(r,e){let t=null,i=null;return r.walkAtRules("config",n=>{if(i=n.source?.input.file??e.opts.from??null,i===null)throw n.error("The `@config` directive cannot be used without setting `from` in your PostCSS config.");if(t)throw n.error("Only one `@config` directive is allowed per file.");let s=n.params.match(/(['"])(.*?)\1/);if(!s)throw n.error("A path is required when using the `@config` directive.");let a=s[2];if(me.isAbsolute(a))throw n.error("The `@config` directive cannot be used with an absolute path.");if(t=me.resolve(me.dirname(i),a),!be.existsSync(t))throw n.error(`The config file at "${a}" does not exist. Make sure the path is correct and the file exists.`);n.remove()}),t||null}var Sy=P(()=>{u();ft();et()});var Ay=x((Wq,Ql)=>{u();Eg();xy();It();Sy();Ql.exports=function(e){return{postcssPlugin:"tailwindcss",plugins:[Ze.DEBUG&&function(t){return console.log(` +`),console.time("JIT TOTAL"),t},async function(t,i){e=ky(t,i)??e;let n=El(e);if(t.type==="document"){let s=t.nodes.filter(a=>a.type==="root");for(let a of s)a.type==="root"&&await Ts(n)(a,i);return}await Ts(n)(t,i)},Ze.DEBUG&&function(t){return console.timeEnd("JIT TOTAL"),console.log(` +`),t}].filter(Boolean)}};Ql.exports.postcss=!0});var _y=x((Gq,Cy)=>{u();Cy.exports=Ay()});var Yl=x((Qq,Ey)=>{u();Ey.exports=()=>["and_chr 114","and_uc 15.5","chrome 114","chrome 113","chrome 109","edge 114","firefox 114","ios_saf 16.5","ios_saf 16.4","ios_saf 16.3","ios_saf 16.1","opera 99","safari 16.5","samsung 21"]});var Rs={};Ge(Rs,{agents:()=>nO,feature:()=>sO});function sO(){return{status:"cr",title:"CSS Feature Queries",stats:{ie:{"6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","5.5":"n"},edge:{"12":"y","13":"y","14":"y","15":"y","16":"y","17":"y","18":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y"},firefox:{"2":"n","3":"n","4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y","3.5":"n","3.6":"n"},chrome:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"n","23":"n","24":"n","25":"n","26":"n","27":"n","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y"},safari:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"y","10":"y","11":"y","12":"y","13":"y","14":"y","15":"y","17":"y","9.1":"y","10.1":"y","11.1":"y","12.1":"y","13.1":"y","14.1":"y","15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y",TP:"y","3.1":"n","3.2":"n","5.1":"n","6.1":"n","7.1":"n"},opera:{"9":"n","11":"n","12":"n","15":"y","16":"y","17":"y","18":"y","19":"y","20":"y","21":"y","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","60":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","12.1":"y","9.5-9.6":"n","10.0-10.1":"n","10.5":"n","10.6":"n","11.1":"n","11.5":"n","11.6":"n"},ios_saf:{"8":"n","17":"y","9.0-9.2":"y","9.3":"y","10.0-10.2":"y","10.3":"y","11.0-11.2":"y","11.3-11.4":"y","12.0-12.1":"y","12.2-12.5":"y","13.0-13.1":"y","13.2":"y","13.3":"y","13.4-13.7":"y","14.0-14.4":"y","14.5-14.8":"y","15.0-15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y","3.2":"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0-7.1":"n","8.1-8.4":"n"},op_mini:{all:"y"},android:{"3":"n","4":"n","114":"y","4.4":"y","4.4.3-4.4.4":"y","2.1":"n","2.2":"n","2.3":"n","4.1":"n","4.2-4.3":"n"},bb:{"7":"n","10":"n"},op_mob:{"10":"n","11":"n","12":"n","73":"y","11.1":"n","11.5":"n","12.1":"n"},and_chr:{"114":"y"},and_ff:{"115":"y"},ie_mob:{"10":"n","11":"n"},and_uc:{"15.5":"y"},samsung:{"4":"y","20":"y","21":"y","5.0-5.4":"y","6.2-6.4":"y","7.2-7.4":"y","8.2":"y","9.2":"y","10.1":"y","11.1-11.2":"y","12.0":"y","13.0":"y","14.0":"y","15.0":"y","16.0":"y","17.0":"y","18.0":"y","19.0":"y"},and_qq:{"13.1":"y"},baidu:{"13.18":"y"},kaios:{"2.5":"y","3.0-3.1":"y"}}}}var nO,Ps=P(()=>{u();nO={ie:{prefix:"ms"},edge:{prefix:"webkit",prefix_exceptions:{"12":"ms","13":"ms","14":"ms","15":"ms","16":"ms","17":"ms","18":"ms"}},firefox:{prefix:"moz"},chrome:{prefix:"webkit"},safari:{prefix:"webkit"},opera:{prefix:"webkit",prefix_exceptions:{"9":"o","11":"o","12":"o","9.5-9.6":"o","10.0-10.1":"o","10.5":"o","10.6":"o","11.1":"o","11.5":"o","11.6":"o","12.1":"o"}},ios_saf:{prefix:"webkit"},op_mini:{prefix:"o"},android:{prefix:"webkit"},bb:{prefix:"webkit"},op_mob:{prefix:"o",prefix_exceptions:{"73":"webkit"}},and_chr:{prefix:"webkit"},and_ff:{prefix:"moz"},ie_mob:{prefix:"ms"},and_uc:{prefix:"webkit",prefix_exceptions:{"15.5":"webkit"}},samsung:{prefix:"webkit"},and_qq:{prefix:"webkit"},baidu:{prefix:"webkit"},kaios:{prefix:"moz"}}});var Oy=x(()=>{u()});var _e=x((Xq,Lt)=>{u();var{list:Kl}=$e();Lt.exports.error=function(r){let e=new Error(r);throw e.autoprefixer=!0,e};Lt.exports.uniq=function(r){return[...new Set(r)]};Lt.exports.removeNote=function(r){return r.includes(" ")?r.split(" ")[0]:r};Lt.exports.escapeRegexp=function(r){return r.replace(/[$()*+-.?[\\\]^{|}]/g,"\\$&")};Lt.exports.regexp=function(r,e=!0){return e&&(r=this.escapeRegexp(r)),new RegExp(`(^|[\\s,(])(${r}($|[\\s(,]))`,"gi")};Lt.exports.editList=function(r,e){let t=Kl.comma(r),i=e(t,[]);if(t===i)return r;let n=r.match(/,\s*/);return n=n?n[0]:", ",i.join(n)};Lt.exports.splitSelector=function(r){return Kl.comma(r).map(e=>Kl.space(e).map(t=>t.split(/(?=\.|#)/g)))}});var Mt=x((Zq,Py)=>{u();var aO=Yl(),Ty=(Ps(),Rs).agents,oO=_e(),Ry=class{static prefixes(){if(this.prefixesCache)return this.prefixesCache;this.prefixesCache=[];for(let e in Ty)this.prefixesCache.push(`-${Ty[e].prefix}-`);return this.prefixesCache=oO.uniq(this.prefixesCache).sort((e,t)=>t.length-e.length),this.prefixesCache}static withPrefix(e){return this.prefixesRegexp||(this.prefixesRegexp=new RegExp(this.prefixes().join("|"))),this.prefixesRegexp.test(e)}constructor(e,t,i,n){this.data=e,this.options=i||{},this.browserslistOpts=n||{},this.selected=this.parse(t)}parse(e){let t={};for(let i in this.browserslistOpts)t[i]=this.browserslistOpts[i];return t.path=this.options.from,aO(e,t)}prefix(e){let[t,i]=e.split(" "),n=this.data[t],s=n.prefix_exceptions&&n.prefix_exceptions[i];return s||(s=n.prefix),`-${s}-`}isSelected(e){return this.selected.includes(e)}};Py.exports=Ry});var Ni=x((Jq,Iy)=>{u();Iy.exports={prefix(r){let e=r.match(/^(-\w+-)/);return e?e[0]:""},unprefixed(r){return r.replace(/^-\w+-/,"")}}});var wr=x((e$,qy)=>{u();var lO=Mt(),Dy=Ni(),uO=_e();function Xl(r,e){let t=new r.constructor;for(let i of Object.keys(r||{})){let n=r[i];i==="parent"&&typeof n=="object"?e&&(t[i]=e):i==="source"||i===null?t[i]=n:Array.isArray(n)?t[i]=n.map(s=>Xl(s,t)):i!=="_autoprefixerPrefix"&&i!=="_autoprefixerValues"&&i!=="proxyCache"&&(typeof n=="object"&&n!==null&&(n=Xl(n,t)),t[i]=n)}return t}var Is=class{static hack(e){return this.hacks||(this.hacks={}),e.names.map(t=>(this.hacks[t]=e,this.hacks[t]))}static load(e,t,i){let n=this.hacks&&this.hacks[e];return n?new n(e,t,i):new this(e,t,i)}static clone(e,t){let i=Xl(e);for(let n in t)i[n]=t[n];return i}constructor(e,t,i){this.prefixes=t,this.name=e,this.all=i}parentPrefix(e){let t;return typeof e._autoprefixerPrefix!="undefined"?t=e._autoprefixerPrefix:e.type==="decl"&&e.prop[0]==="-"?t=Dy.prefix(e.prop):e.type==="root"?t=!1:e.type==="rule"&&e.selector.includes(":-")&&/:(-\w+-)/.test(e.selector)?t=e.selector.match(/:(-\w+-)/)[1]:e.type==="atrule"&&e.name[0]==="-"?t=Dy.prefix(e.name):t=this.parentPrefix(e.parent),lO.prefixes().includes(t)||(t=!1),e._autoprefixerPrefix=t,e._autoprefixerPrefix}process(e,t){if(!this.check(e))return;let i=this.parentPrefix(e),n=this.prefixes.filter(a=>!i||i===uO.removeNote(a)),s=[];for(let a of n)this.add(e,a,s.concat([a]),t)&&s.push(a);return s}clone(e,t){return Is.clone(e,t)}};qy.exports=Is});var j=x((t$,My)=>{u();var fO=wr(),cO=Mt(),$y=_e(),Ly=class extends fO{check(){return!0}prefixed(e,t){return t+e}normalize(e){return e}otherPrefixes(e,t){for(let i of cO.prefixes())if(i!==t&&e.includes(i))return!0;return!1}set(e,t){return e.prop=this.prefixed(e.prop,t),e}needCascade(e){return e._autoprefixerCascade||(e._autoprefixerCascade=this.all.options.cascade!==!1&&e.raw("before").includes(` +`)),e._autoprefixerCascade}maxPrefixed(e,t){if(t._autoprefixerMax)return t._autoprefixerMax;let i=0;for(let n of e)n=$y.removeNote(n),n.length>i&&(i=n.length);return t._autoprefixerMax=i,t._autoprefixerMax}calcBefore(e,t,i=""){let s=this.maxPrefixed(e,t)-$y.removeNote(i).length,a=t.raw("before");return s>0&&(a+=Array(s).fill(" ").join("")),a}restoreBefore(e){let t=e.raw("before").split(` +`),i=t[t.length-1];this.all.group(e).up(n=>{let s=n.raw("before").split(` +`),a=s[s.length-1];a.lengtha.prop===n.prop&&a.value===n.value)))return this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,n)}isAlready(e,t){let i=this.all.group(e).up(n=>n.prop===t);return i||(i=this.all.group(e).down(n=>n.prop===t)),i}add(e,t,i,n){let s=this.prefixed(e.prop,t);if(!(this.isAlready(e,s)||this.otherPrefixes(e.value,t)))return this.insert(e,t,i,n)}process(e,t){if(!this.needCascade(e)){super.process(e,t);return}let i=super.process(e,t);!i||!i.length||(this.restoreBefore(e),e.raws.before=this.calcBefore(i,e))}old(e,t){return[this.prefixed(e,t)]}};My.exports=Ly});var By=x((r$,Ny)=>{u();Ny.exports=function r(e){return{mul:t=>new r(e*t),div:t=>new r(e/t),simplify:()=>new r(e),toString:()=>e.toString()}}});var zy=x((i$,jy)=>{u();var pO=By(),dO=wr(),Zl=_e(),hO=/(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpcm|dpi|x)/gi,mO=/(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpcm|dpi|x)/i,Fy=class extends dO{prefixName(e,t){return e==="-moz-"?t+"--moz-device-pixel-ratio":e+t+"-device-pixel-ratio"}prefixQuery(e,t,i,n,s){return n=new pO(n),s==="dpi"?n=n.div(96):s==="dpcm"&&(n=n.mul(2.54).div(96)),n=n.simplify(),e==="-o-"&&(n=n.n+"/"+n.d),this.prefixName(e,t)+i+n}clean(e){if(!this.bad){this.bad=[];for(let t of this.prefixes)this.bad.push(this.prefixName(t,"min")),this.bad.push(this.prefixName(t,"max"))}e.params=Zl.editList(e.params,t=>t.filter(i=>this.bad.every(n=>!i.includes(n))))}process(e){let t=this.parentPrefix(e),i=t?[t]:this.prefixes;e.params=Zl.editList(e.params,(n,s)=>{for(let a of n){if(!a.includes("min-resolution")&&!a.includes("max-resolution")){s.push(a);continue}for(let o of i){let l=a.replace(hO,c=>{let f=c.match(mO);return this.prefixQuery(o,f[1],f[2],f[3],f[4])});s.push(l)}s.push(a)}return Zl.uniq(s)})}};jy.exports=Fy});var Vy=x((n$,Uy)=>{u();var Jl="(".charCodeAt(0),eu=")".charCodeAt(0),Ds="'".charCodeAt(0),tu='"'.charCodeAt(0),ru="\\".charCodeAt(0),vr="/".charCodeAt(0),iu=",".charCodeAt(0),nu=":".charCodeAt(0),qs="*".charCodeAt(0),gO="u".charCodeAt(0),yO="U".charCodeAt(0),bO="+".charCodeAt(0),wO=/^[a-f0-9?-]+$/i;Uy.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d{u();Hy.exports=function r(e,t,i){var n,s,a,o;for(n=0,s=e.length;n{u();function Gy(r,e){var t=r.type,i=r.value,n,s;return e&&(s=e(r))!==void 0?s:t==="word"||t==="space"?i:t==="string"?(n=r.quote||"",n+i+(r.unclosed?"":n)):t==="comment"?"/*"+i+(r.unclosed?"":"*/"):t==="div"?(r.before||"")+i+(r.after||""):Array.isArray(r.nodes)?(n=Qy(r.nodes,e),t!=="function"?n:i+"("+(r.before||"")+n+(r.after||"")+(r.unclosed?"":")")):i}function Qy(r,e){var t,i;if(Array.isArray(r)){for(t="",i=r.length-1;~i;i-=1)t=Gy(r[i],e)+t;return t}return Gy(r,e)}Yy.exports=Qy});var Zy=x((o$,Xy)=>{u();var $s="-".charCodeAt(0),Ls="+".charCodeAt(0),su=".".charCodeAt(0),vO="e".charCodeAt(0),xO="E".charCodeAt(0);function kO(r){var e=r.charCodeAt(0),t;if(e===Ls||e===$s){if(t=r.charCodeAt(1),t>=48&&t<=57)return!0;var i=r.charCodeAt(2);return t===su&&i>=48&&i<=57}return e===su?(t=r.charCodeAt(1),t>=48&&t<=57):e>=48&&e<=57}Xy.exports=function(r){var e=0,t=r.length,i,n,s;if(t===0||!kO(r))return!1;for(i=r.charCodeAt(e),(i===Ls||i===$s)&&e++;e57));)e+=1;if(i=r.charCodeAt(e),n=r.charCodeAt(e+1),i===su&&n>=48&&n<=57)for(e+=2;e57));)e+=1;if(i=r.charCodeAt(e),n=r.charCodeAt(e+1),s=r.charCodeAt(e+2),(i===vO||i===xO)&&(n>=48&&n<=57||(n===Ls||n===$s)&&s>=48&&s<=57))for(e+=n===Ls||n===$s?3:2;e57));)e+=1;return{number:r.slice(0,e),unit:r.slice(e)}}});var Ms=x((l$,tb)=>{u();var SO=Vy(),Jy=Wy(),eb=Ky();function Nt(r){return this instanceof Nt?(this.nodes=SO(r),this):new Nt(r)}Nt.prototype.toString=function(){return Array.isArray(this.nodes)?eb(this.nodes):""};Nt.prototype.walk=function(r,e){return Jy(this.nodes,r,e),this};Nt.unit=Zy();Nt.walk=Jy;Nt.stringify=eb;tb.exports=Nt});var ab=x((u$,sb)=>{u();var{list:AO}=$e(),rb=Ms(),CO=Mt(),ib=Ni(),nb=class{constructor(e){this.props=["transition","transition-property"],this.prefixes=e}add(e,t){let i,n,s=this.prefixes.add[e.prop],a=this.ruleVendorPrefixes(e),o=a||s&&s.prefixes||[],l=this.parse(e.value),c=l.map(h=>this.findProp(h)),f=[];if(c.some(h=>h[0]==="-"))return;for(let h of l){if(n=this.findProp(h),n[0]==="-")continue;let b=this.prefixes.add[n];if(!(!b||!b.prefixes))for(i of b.prefixes){if(a&&!a.some(y=>i.includes(y)))continue;let v=this.prefixes.prefixed(n,i);v!=="-ms-transform"&&!c.includes(v)&&(this.disabled(n,i)||f.push(this.clone(n,v,h)))}}l=l.concat(f);let d=this.stringify(l),p=this.stringify(this.cleanFromUnprefixed(l,"-webkit-"));if(o.includes("-webkit-")&&this.cloneBefore(e,`-webkit-${e.prop}`,p),this.cloneBefore(e,e.prop,p),o.includes("-o-")){let h=this.stringify(this.cleanFromUnprefixed(l,"-o-"));this.cloneBefore(e,`-o-${e.prop}`,h)}for(i of o)if(i!=="-webkit-"&&i!=="-o-"){let h=this.stringify(this.cleanOtherPrefixes(l,i));this.cloneBefore(e,i+e.prop,h)}d!==e.value&&!this.already(e,e.prop,d)&&(this.checkForWarning(t,e),e.cloneBefore(),e.value=d)}findProp(e){let t=e[0].value;if(/^\d/.test(t)){for(let[i,n]of e.entries())if(i!==0&&n.type==="word")return n.value}return t}already(e,t,i){return e.parent.some(n=>n.prop===t&&n.value===i)}cloneBefore(e,t,i){this.already(e,t,i)||e.cloneBefore({prop:t,value:i})}checkForWarning(e,t){if(t.prop!=="transition-property")return;let i=!1,n=!1;t.parent.each(s=>{if(s.type!=="decl"||s.prop.indexOf("transition-")!==0)return;let a=AO.comma(s.value);if(s.prop==="transition-property"){a.forEach(o=>{let l=this.prefixes.add[o];l&&l.prefixes&&l.prefixes.length>0&&(i=!0)});return}return n=n||a.length>1,!1}),i&&n&&t.warn(e,"Replace transition-property to transition, because Autoprefixer could not support any cases of transition-property and other transition-*")}remove(e){let t=this.parse(e.value);t=t.filter(a=>{let o=this.prefixes.remove[this.findProp(a)];return!o||!o.remove});let i=this.stringify(t);if(e.value===i)return;if(t.length===0){e.remove();return}let n=e.parent.some(a=>a.prop===e.prop&&a.value===i),s=e.parent.some(a=>a!==e&&a.prop===e.prop&&a.value.length>i.length);if(n||s){e.remove();return}e.value=i}parse(e){let t=rb(e),i=[],n=[];for(let s of t.nodes)n.push(s),s.type==="div"&&s.value===","&&(i.push(n),n=[]);return i.push(n),i.filter(s=>s.length>0)}stringify(e){if(e.length===0)return"";let t=[];for(let i of e)i[i.length-1].type!=="div"&&i.push(this.div(e)),t=t.concat(i);return t[0].type==="div"&&(t=t.slice(1)),t[t.length-1].type==="div"&&(t=t.slice(0,-2+1||void 0)),rb.stringify({nodes:t})}clone(e,t,i){let n=[],s=!1;for(let a of i)!s&&a.type==="word"&&a.value===e?(n.push({type:"word",value:t}),s=!0):n.push(a);return n}div(e){for(let t of e)for(let i of t)if(i.type==="div"&&i.value===",")return i;return{type:"div",value:",",after:" "}}cleanOtherPrefixes(e,t){return e.filter(i=>{let n=ib.prefix(this.findProp(i));return n===""||n===t})}cleanFromUnprefixed(e,t){let i=e.map(s=>this.findProp(s)).filter(s=>s.slice(0,t.length)===t).map(s=>this.prefixes.unprefixed(s)),n=[];for(let s of e){let a=this.findProp(s),o=ib.prefix(a);!i.includes(a)&&(o===t||o==="")&&n.push(s)}return n}disabled(e,t){let i=["order","justify-content","align-self","align-content"];if(e.includes("flex")||i.includes(e)){if(this.prefixes.options.flexbox===!1)return!0;if(this.prefixes.options.flexbox==="no-2009")return t.includes("2009")}}ruleVendorPrefixes(e){let{parent:t}=e;if(t.type!=="rule")return!1;if(!t.selector.includes(":-"))return!1;let i=CO.prefixes().filter(n=>t.selector.includes(":"+n));return i.length>0?i:!1}};sb.exports=nb});var xr=x((f$,lb)=>{u();var _O=_e(),ob=class{constructor(e,t,i,n){this.unprefixed=e,this.prefixed=t,this.string=i||t,this.regexp=n||_O.regexp(t)}check(e){return e.includes(this.string)?!!e.match(this.regexp):!1}};lb.exports=ob});var He=x((c$,fb)=>{u();var EO=wr(),OO=xr(),TO=Ni(),RO=_e(),ub=class extends EO{static save(e,t){let i=t.prop,n=[];for(let s in t._autoprefixerValues){let a=t._autoprefixerValues[s];if(a===t.value)continue;let o,l=TO.prefix(i);if(l==="-pie-")continue;if(l===s){o=t.value=a,n.push(o);continue}let c=e.prefixed(i,s),f=t.parent;if(!f.every(b=>b.prop!==c)){n.push(o);continue}let d=a.replace(/\s+/," ");if(f.some(b=>b.prop===t.prop&&b.value.replace(/\s+/," ")===d)){n.push(o);continue}let h=this.clone(t,{value:a});o=t.parent.insertBefore(t,h),n.push(o)}return n}check(e){let t=e.value;return t.includes(this.name)?!!t.match(this.regexp()):!1}regexp(){return this.regexpCache||(this.regexpCache=RO.regexp(this.name))}replace(e,t){return e.replace(this.regexp(),`$1${t}$2`)}value(e){return e.raws.value&&e.raws.value.value===e.value?e.raws.value.raw:e.value}add(e,t){e._autoprefixerValues||(e._autoprefixerValues={});let i=e._autoprefixerValues[t]||this.value(e),n;do if(n=i,i=this.replace(i,t),i===!1)return;while(i!==n);e._autoprefixerValues[t]=i}old(e){return new OO(this.name,e+this.name)}};fb.exports=ub});var Bt=x((p$,cb)=>{u();cb.exports={}});var ou=x((d$,hb)=>{u();var pb=Ms(),PO=He(),IO=Bt().insertAreas,DO=/(^|[^-])linear-gradient\(\s*(top|left|right|bottom)/i,qO=/(^|[^-])radial-gradient\(\s*\d+(\w*|%)\s+\d+(\w*|%)\s*,/i,$O=/(!\s*)?autoprefixer:\s*ignore\s+next/i,LO=/(!\s*)?autoprefixer\s*grid:\s*(on|off|(no-)?autoplace)/i,MO=["width","height","min-width","max-width","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size"];function au(r){return r.parent.some(e=>e.prop==="grid-template"||e.prop==="grid-template-areas")}function NO(r){let e=r.parent.some(i=>i.prop==="grid-template-rows"),t=r.parent.some(i=>i.prop==="grid-template-columns");return e&&t}var db=class{constructor(e){this.prefixes=e}add(e,t){let i=this.prefixes.add["@resolution"],n=this.prefixes.add["@keyframes"],s=this.prefixes.add["@viewport"],a=this.prefixes.add["@supports"];e.walkAtRules(f=>{if(f.name==="keyframes"){if(!this.disabled(f,t))return n&&n.process(f)}else if(f.name==="viewport"){if(!this.disabled(f,t))return s&&s.process(f)}else if(f.name==="supports"){if(this.prefixes.options.supports!==!1&&!this.disabled(f,t))return a.process(f)}else if(f.name==="media"&&f.params.includes("-resolution")&&!this.disabled(f,t))return i&&i.process(f)}),e.walkRules(f=>{if(!this.disabled(f,t))return this.prefixes.add.selectors.map(d=>d.process(f,t))});function o(f){return f.parent.nodes.some(d=>{if(d.type!=="decl")return!1;let p=d.prop==="display"&&/(inline-)?grid/.test(d.value),h=d.prop.startsWith("grid-template"),b=/^grid-([A-z]+-)?gap/.test(d.prop);return p||h||b})}function l(f){return f.parent.some(d=>d.prop==="display"&&/(inline-)?flex/.test(d.value))}let c=this.gridStatus(e,t)&&this.prefixes.add["grid-area"]&&this.prefixes.add["grid-area"].prefixes;return e.walkDecls(f=>{if(this.disabledDecl(f,t))return;let d=f.parent,p=f.prop,h=f.value;if(p==="grid-row-span"){t.warn("grid-row-span is not part of final Grid Layout. Use grid-row.",{node:f});return}else if(p==="grid-column-span"){t.warn("grid-column-span is not part of final Grid Layout. Use grid-column.",{node:f});return}else if(p==="display"&&h==="box"){t.warn("You should write display: flex by final spec instead of display: box",{node:f});return}else if(p==="text-emphasis-position")(h==="under"||h==="over")&&t.warn("You should use 2 values for text-emphasis-position For example, `under left` instead of just `under`.",{node:f});else if(/^(align|justify|place)-(items|content)$/.test(p)&&l(f))(h==="start"||h==="end")&&t.warn(`${h} value has mixed support, consider using flex-${h} instead`,{node:f});else if(p==="text-decoration-skip"&&h==="ink")t.warn("Replace text-decoration-skip: ink to text-decoration-skip-ink: auto, because spec had been changed",{node:f});else{if(c&&this.gridStatus(f,t))if(f.value==="subgrid"&&t.warn("IE does not support subgrid",{node:f}),/^(align|justify|place)-items$/.test(p)&&o(f)){let v=p.replace("-items","-self");t.warn(`IE does not support ${p} on grid containers. Try using ${v} on child elements instead: ${f.parent.selector} > * { ${v}: ${f.value} }`,{node:f})}else if(/^(align|justify|place)-content$/.test(p)&&o(f))t.warn(`IE does not support ${f.prop} on grid containers`,{node:f});else if(p==="display"&&f.value==="contents"){t.warn("Please do not use display: contents; if you have grid setting enabled",{node:f});return}else if(f.prop==="grid-gap"){let v=this.gridStatus(f,t);v==="autoplace"&&!NO(f)&&!au(f)?t.warn("grid-gap only works if grid-template(-areas) is being used or both rows and columns have been declared and cells have not been manually placed inside the explicit grid",{node:f}):(v===!0||v==="no-autoplace")&&!au(f)&&t.warn("grid-gap only works if grid-template(-areas) is being used",{node:f})}else if(p==="grid-auto-columns"){t.warn("grid-auto-columns is not supported by IE",{node:f});return}else if(p==="grid-auto-rows"){t.warn("grid-auto-rows is not supported by IE",{node:f});return}else if(p==="grid-auto-flow"){let v=d.some(w=>w.prop==="grid-template-rows"),y=d.some(w=>w.prop==="grid-template-columns");au(f)?t.warn("grid-auto-flow is not supported by IE",{node:f}):h.includes("dense")?t.warn("grid-auto-flow: dense is not supported by IE",{node:f}):!v&&!y&&t.warn("grid-auto-flow works only if grid-template-rows and grid-template-columns are present in the same rule",{node:f});return}else if(h.includes("auto-fit")){t.warn("auto-fit value is not supported by IE",{node:f,word:"auto-fit"});return}else if(h.includes("auto-fill")){t.warn("auto-fill value is not supported by IE",{node:f,word:"auto-fill"});return}else p.startsWith("grid-template")&&h.includes("[")&&t.warn("Autoprefixer currently does not support line names. Try using grid-template-areas instead.",{node:f,word:"["});if(h.includes("radial-gradient"))if(qO.test(f.value))t.warn("Gradient has outdated direction syntax. New syntax is like `closest-side at 0 0` instead of `0 0, closest-side`.",{node:f});else{let v=pb(h);for(let y of v.nodes)if(y.type==="function"&&y.value==="radial-gradient")for(let w of y.nodes)w.type==="word"&&(w.value==="cover"?t.warn("Gradient has outdated direction syntax. Replace `cover` to `farthest-corner`.",{node:f}):w.value==="contain"&&t.warn("Gradient has outdated direction syntax. Replace `contain` to `closest-side`.",{node:f}))}h.includes("linear-gradient")&&DO.test(h)&&t.warn("Gradient has outdated direction syntax. New syntax is like `to left` instead of `right`.",{node:f})}MO.includes(f.prop)&&(f.value.includes("-fill-available")||(f.value.includes("fill-available")?t.warn("Replace fill-available to stretch, because spec had been changed",{node:f}):f.value.includes("fill")&&pb(h).nodes.some(y=>y.type==="word"&&y.value==="fill")&&t.warn("Replace fill to stretch, because spec had been changed",{node:f})));let b;if(f.prop==="transition"||f.prop==="transition-property")return this.prefixes.transition.add(f,t);if(f.prop==="align-self"){if(this.displayType(f)!=="grid"&&this.prefixes.options.flexbox!==!1&&(b=this.prefixes.add["align-self"],b&&b.prefixes&&b.process(f)),this.gridStatus(f,t)!==!1&&(b=this.prefixes.add["grid-row-align"],b&&b.prefixes))return b.process(f,t)}else if(f.prop==="justify-self"){if(this.gridStatus(f,t)!==!1&&(b=this.prefixes.add["grid-column-align"],b&&b.prefixes))return b.process(f,t)}else if(f.prop==="place-self"){if(b=this.prefixes.add["place-self"],b&&b.prefixes&&this.gridStatus(f,t)!==!1)return b.process(f,t)}else if(b=this.prefixes.add[f.prop],b&&b.prefixes)return b.process(f,t)}),this.gridStatus(e,t)&&IO(e,this.disabled),e.walkDecls(f=>{if(this.disabledValue(f,t))return;let d=this.prefixes.unprefixed(f.prop),p=this.prefixes.values("add",d);if(Array.isArray(p))for(let h of p)h.process&&h.process(f,t);PO.save(this.prefixes,f)})}remove(e,t){let i=this.prefixes.remove["@resolution"];e.walkAtRules((n,s)=>{this.prefixes.remove[`@${n.name}`]?this.disabled(n,t)||n.parent.removeChild(s):n.name==="media"&&n.params.includes("-resolution")&&i&&i.clean(n)});for(let n of this.prefixes.remove.selectors)e.walkRules((s,a)=>{n.check(s)&&(this.disabled(s,t)||s.parent.removeChild(a))});return e.walkDecls((n,s)=>{if(this.disabled(n,t))return;let a=n.parent,o=this.prefixes.unprefixed(n.prop);if((n.prop==="transition"||n.prop==="transition-property")&&this.prefixes.transition.remove(n),this.prefixes.remove[n.prop]&&this.prefixes.remove[n.prop].remove){let l=this.prefixes.group(n).down(c=>this.prefixes.normalize(c.prop)===o);if(o==="flex-flow"&&(l=!0),n.prop==="-webkit-box-orient"){let c={"flex-direction":!0,"flex-flow":!0};if(!n.parent.some(f=>c[f.prop]))return}if(l&&!this.withHackValue(n)){n.raw("before").includes(` +`)&&this.reduceSpaces(n),a.removeChild(s);return}}for(let l of this.prefixes.values("remove",o)){if(!l.check||!l.check(n.value))continue;if(o=l.unprefixed,this.prefixes.group(n).down(f=>f.value.includes(o))){a.removeChild(s);return}}})}withHackValue(e){return e.prop==="-webkit-background-clip"&&e.value==="text"}disabledValue(e,t){return this.gridStatus(e,t)===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("grid")||this.prefixes.options.flexbox===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("flex")||e.type==="decl"&&e.prop==="content"?!0:this.disabled(e,t)}disabledDecl(e,t){if(this.gridStatus(e,t)===!1&&e.type==="decl"&&(e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.prefixes.options.flexbox===!1&&e.type==="decl"){let i=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||i.includes(e.prop))return!0}return this.disabled(e,t)}disabled(e,t){if(!e)return!1;if(e._autoprefixerDisabled!==void 0)return e._autoprefixerDisabled;if(e.parent){let n=e.prev();if(n&&n.type==="comment"&&$O.test(n.text))return e._autoprefixerDisabled=!0,e._autoprefixerSelfDisabled=!0,!0}let i=null;if(e.nodes){let n;e.each(s=>{s.type==="comment"&&/(!\s*)?autoprefixer:\s*(off|on)/i.test(s.text)&&(typeof n!="undefined"?t.warn("Second Autoprefixer control comment was ignored. Autoprefixer applies control comment to whole block, not to next rules.",{node:s}):n=/on/i.test(s.text))}),n!==void 0&&(i=!n)}if(!e.nodes||i===null)if(e.parent){let n=this.disabled(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else i=!1;return e._autoprefixerDisabled=i,i}reduceSpaces(e){let t=!1;if(this.prefixes.group(e).up(()=>(t=!0,!0)),t)return;let i=e.raw("before").split(` +`),n=i[i.length-1].length,s=!1;this.prefixes.group(e).down(a=>{i=a.raw("before").split(` +`);let o=i.length-1;i[o].length>n&&(s===!1&&(s=i[o].length-n),i[o]=i[o].slice(0,-s),a.raws.before=i.join(` +`))})}displayType(e){for(let t of e.parent.nodes)if(t.prop==="display"){if(t.value.includes("flex"))return"flex";if(t.value.includes("grid"))return"grid"}return!1}gridStatus(e,t){if(!e)return!1;if(e._autoprefixerGridStatus!==void 0)return e._autoprefixerGridStatus;let i=null;if(e.nodes){let n;e.each(s=>{if(s.type==="comment"&&LO.test(s.text)){let a=/:\s*autoplace/i.test(s.text),o=/no-autoplace/i.test(s.text);typeof n!="undefined"?t.warn("Second Autoprefixer grid control comment was ignored. Autoprefixer applies control comments to the whole block, not to the next rules.",{node:s}):a?n="autoplace":o?n=!0:n=/on/i.test(s.text)}}),n!==void 0&&(i=n)}if(e.type==="atrule"&&e.name==="supports"){let n=e.params;n.includes("grid")&&n.includes("auto")&&(i=!1)}if(!e.nodes||i===null)if(e.parent){let n=this.gridStatus(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else typeof this.prefixes.options.grid!="undefined"?i=this.prefixes.options.grid:typeof m.env.AUTOPREFIXER_GRID!="undefined"?m.env.AUTOPREFIXER_GRID==="autoplace"?i="autoplace":i=!0:i=!1;return e._autoprefixerGridStatus=i,i}};hb.exports=db});var gb=x((h$,mb)=>{u();mb.exports={A:{A:{"2":"K E F G A B JC"},B:{"1":"C L M H N D O P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I"},C:{"1":"2 3 4 5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 KC zB J K E F G A B C L M H N D O k l LC MC"},D:{"1":"8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 2 3 4 5 6 7 J K E F G A B C L M H N D O k l"},E:{"1":"G A B C L M H D RC 6B vB wB 7B SC TC 8B 9B xB AC yB BC CC DC EC FC GC UC","2":"0 J K E F NC 5B OC PC QC"},F:{"1":"1 2 3 4 5 6 7 8 9 H N D O k l AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j wB","2":"G B C VC WC XC YC vB HC ZC"},G:{"1":"D fC gC hC iC jC kC lC mC nC oC pC qC rC sC tC 8B 9B xB AC yB BC CC DC EC FC GC","2":"F 5B aC IC bC cC dC eC"},H:{"1":"uC"},I:{"1":"I zC 0C","2":"zB J vC wC xC yC IC"},J:{"2":"E A"},K:{"1":"m","2":"A B C vB HC wB"},L:{"1":"I"},M:{"1":"uB"},N:{"2":"A B"},O:{"1":"xB"},P:{"1":"J k l 1C 2C 3C 4C 5C 6B 6C 7C 8C 9C AD yB BD CD DD"},Q:{"1":"7B"},R:{"1":"ED"},S:{"1":"FD GD"}},B:4,C:"CSS Feature Queries"}});var vb=x((m$,wb)=>{u();function yb(r){return r[r.length-1]}var bb={parse(r){let e=[""],t=[e];for(let i of r){if(i==="("){e=[""],yb(t).push(e),t.push(e);continue}if(i===")"){t.pop(),e=yb(t),e.push("");continue}e[e.length-1]+=i}return t[0]},stringify(r){let e="";for(let t of r){if(typeof t=="object"){e+=`(${bb.stringify(t)})`;continue}e+=t}return e}};wb.exports=bb});var Cb=x((g$,Ab)=>{u();var BO=gb(),{feature:FO}=(Ps(),Rs),{parse:jO}=$e(),zO=Mt(),lu=vb(),UO=He(),VO=_e(),xb=FO(BO),kb=[];for(let r in xb.stats){let e=xb.stats[r];for(let t in e){let i=e[t];/y/.test(i)&&kb.push(r+" "+t)}}var Sb=class{constructor(e,t){this.Prefixes=e,this.all=t}prefixer(){if(this.prefixerCache)return this.prefixerCache;let e=this.all.browsers.selected.filter(i=>kb.includes(i)),t=new zO(this.all.browsers.data,e,this.all.options);return this.prefixerCache=new this.Prefixes(this.all.data,t,this.all.options),this.prefixerCache}parse(e){let t=e.split(":"),i=t[0],n=t[1];return n||(n=""),[i.trim(),n.trim()]}virtual(e){let[t,i]=this.parse(e),n=jO("a{}").first;return n.append({prop:t,value:i,raws:{before:""}}),n}prefixed(e){let t=this.virtual(e);if(this.disabled(t.first))return t.nodes;let i={warn:()=>null},n=this.prefixer().add[t.first.prop];n&&n.process&&n.process(t.first,i);for(let s of t.nodes){for(let a of this.prefixer().values("add",t.first.prop))a.process(s);UO.save(this.all,s)}return t.nodes}isNot(e){return typeof e=="string"&&/not\s*/i.test(e)}isOr(e){return typeof e=="string"&&/\s*or\s*/i.test(e)}isProp(e){return typeof e=="object"&&e.length===1&&typeof e[0]=="string"}isHack(e,t){return!new RegExp(`(\\(|\\s)${VO.escapeRegexp(t)}:`).test(e)}toRemove(e,t){let[i,n]=this.parse(e),s=this.all.unprefixed(i),a=this.all.cleaner();if(a.remove[i]&&a.remove[i].remove&&!this.isHack(t,s))return!0;for(let o of a.values("remove",s))if(o.check(n))return!0;return!1}remove(e,t){let i=0;for(;itypeof t!="object"?t:t.length===1&&typeof t[0]=="object"?this.cleanBrackets(t[0]):this.cleanBrackets(t))}convert(e){let t=[""];for(let i of e)t.push([`${i.prop}: ${i.value}`]),t.push(" or ");return t[t.length-1]="",t}normalize(e){if(typeof e!="object")return e;if(e=e.filter(t=>t!==""),typeof e[0]=="string"){let t=e[0].trim();if(t.includes(":")||t==="selector"||t==="not selector")return[lu.stringify(e)]}return e.map(t=>this.normalize(t))}add(e,t){return e.map(i=>{if(this.isProp(i)){let n=this.prefixed(i[0]);return n.length>1?this.convert(n):i}return typeof i=="object"?this.add(i,t):i})}process(e){let t=lu.parse(e.params);t=this.normalize(t),t=this.remove(t,e.params),t=this.add(t,e.params),t=this.cleanBrackets(t),e.params=lu.stringify(t)}disabled(e){if(!this.all.options.grid&&(e.prop==="display"&&e.value.includes("grid")||e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.all.options.flexbox===!1){if(e.prop==="display"&&e.value.includes("flex"))return!0;let t=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||t.includes(e.prop))return!0}return!1}};Ab.exports=Sb});var Ob=x((y$,Eb)=>{u();var _b=class{constructor(e,t){this.prefix=t,this.prefixed=e.prefixed(this.prefix),this.regexp=e.regexp(this.prefix),this.prefixeds=e.possible().map(i=>[e.prefixed(i),e.regexp(i)]),this.unprefixed=e.name,this.nameRegexp=e.regexp()}isHack(e){let t=e.parent.index(e)+1,i=e.parent.nodes;for(;t{u();var{list:HO}=$e(),WO=Ob(),GO=wr(),QO=Mt(),YO=_e(),Tb=class extends GO{constructor(e,t,i){super(e,t,i);this.regexpCache=new Map}check(e){return e.selector.includes(this.name)?!!e.selector.match(this.regexp()):!1}prefixed(e){return this.name.replace(/^(\W*)/,`$1${e}`)}regexp(e){if(!this.regexpCache.has(e)){let t=e?this.prefixed(e):this.name;this.regexpCache.set(e,new RegExp(`(^|[^:"'=])${YO.escapeRegexp(t)}`,"gi"))}return this.regexpCache.get(e)}possible(){return QO.prefixes()}prefixeds(e){if(e._autoprefixerPrefixeds){if(e._autoprefixerPrefixeds[this.name])return e._autoprefixerPrefixeds}else e._autoprefixerPrefixeds={};let t={};if(e.selector.includes(",")){let n=HO.comma(e.selector).filter(s=>s.includes(this.name));for(let s of this.possible())t[s]=n.map(a=>this.replace(a,s)).join(", ")}else for(let i of this.possible())t[i]=this.replace(e.selector,i);return e._autoprefixerPrefixeds[this.name]=t,e._autoprefixerPrefixeds}already(e,t,i){let n=e.parent.index(e)-1;for(;n>=0;){let s=e.parent.nodes[n];if(s.type!=="rule")return!1;let a=!1;for(let o in t[this.name]){let l=t[this.name][o];if(s.selector===l){if(i===o)return!0;a=!0;break}}if(!a)return!1;n-=1}return!1}replace(e,t){return e.replace(this.regexp(),`$1${this.prefixed(t)}`)}add(e,t){let i=this.prefixeds(e);if(this.already(e,i,t))return;let n=this.clone(e,{selector:i[this.name][t]});e.parent.insertBefore(e,n)}old(e){return new WO(this,e)}};Rb.exports=Tb});var Db=x((w$,Ib)=>{u();var KO=wr(),Pb=class extends KO{add(e,t){let i=t+e.name;if(e.parent.some(a=>a.name===i&&a.params===e.params))return;let s=this.clone(e,{name:i});return e.parent.insertBefore(e,s)}process(e){let t=this.parentPrefix(e);for(let i of this.prefixes)(!t||t===i)&&this.add(e,i)}};Ib.exports=Pb});var $b=x((v$,qb)=>{u();var XO=kr(),uu=class extends XO{prefixed(e){return e==="-webkit-"?":-webkit-full-screen":e==="-moz-"?":-moz-full-screen":`:${e}fullscreen`}};uu.names=[":fullscreen"];qb.exports=uu});var Mb=x((x$,Lb)=>{u();var ZO=kr(),fu=class extends ZO{possible(){return super.possible().concat(["-moz- old","-ms- old"])}prefixed(e){return e==="-webkit-"?"::-webkit-input-placeholder":e==="-ms-"?"::-ms-input-placeholder":e==="-ms- old"?":-ms-input-placeholder":e==="-moz- old"?":-moz-placeholder":`::${e}placeholder`}};fu.names=["::placeholder"];Lb.exports=fu});var Bb=x((k$,Nb)=>{u();var JO=kr(),cu=class extends JO{prefixed(e){return e==="-ms-"?":-ms-input-placeholder":`:${e}placeholder-shown`}};cu.names=[":placeholder-shown"];Nb.exports=cu});var jb=x((S$,Fb)=>{u();var eT=kr(),tT=_e(),pu=class extends eT{constructor(e,t,i){super(e,t,i);this.prefixes&&(this.prefixes=tT.uniq(this.prefixes.map(n=>"-webkit-")))}prefixed(e){return e==="-webkit-"?"::-webkit-file-upload-button":`::${e}file-selector-button`}};pu.names=["::file-selector-button"];Fb.exports=pu});var Pe=x((A$,zb)=>{u();zb.exports=function(r){let e;return r==="-webkit- 2009"||r==="-moz-"?e=2009:r==="-ms-"?e=2012:r==="-webkit-"&&(e="final"),r==="-webkit- 2009"&&(r="-webkit-"),[e,r]}});var Wb=x((C$,Hb)=>{u();var Ub=$e().list,Vb=Pe(),rT=j(),Sr=class extends rT{prefixed(e,t){let i;return[i,t]=Vb(t),i===2009?t+"box-flex":super.prefixed(e,t)}normalize(){return"flex"}set(e,t){let i=Vb(t)[0];if(i===2009)return e.value=Ub.space(e.value)[0],e.value=Sr.oldValues[e.value]||e.value,super.set(e,t);if(i===2012){let n=Ub.space(e.value);n.length===3&&n[2]==="0"&&(e.value=n.slice(0,2).concat("0px").join(" "))}return super.set(e,t)}};Sr.names=["flex","box-flex"];Sr.oldValues={auto:"1",none:"0"};Hb.exports=Sr});var Yb=x((_$,Qb)=>{u();var Gb=Pe(),iT=j(),du=class extends iT{prefixed(e,t){let i;return[i,t]=Gb(t),i===2009?t+"box-ordinal-group":i===2012?t+"flex-order":super.prefixed(e,t)}normalize(){return"order"}set(e,t){return Gb(t)[0]===2009&&/\d/.test(e.value)?(e.value=(parseInt(e.value)+1).toString(),super.set(e,t)):super.set(e,t)}};du.names=["order","flex-order","box-ordinal-group"];Qb.exports=du});var Xb=x((E$,Kb)=>{u();var nT=j(),hu=class extends nT{check(e){let t=e.value;return!t.toLowerCase().includes("alpha(")&&!t.includes("DXImageTransform.Microsoft")&&!t.includes("data:image/svg+xml")}};hu.names=["filter"];Kb.exports=hu});var Jb=x((O$,Zb)=>{u();var sT=j(),mu=class extends sT{insert(e,t,i,n){if(t!=="-ms-")return super.insert(e,t,i);let s=this.clone(e),a=e.prop.replace(/end$/,"start"),o=t+e.prop.replace(/end$/,"span");if(!e.parent.some(l=>l.prop===o)){if(s.prop=o,e.value.includes("span"))s.value=e.value.replace(/span\s/i,"");else{let l;if(e.parent.walkDecls(a,c=>{l=c}),l){let c=Number(e.value)-Number(l.value)+"";s.value=c}else e.warn(n,`Can not prefix ${e.prop} (${a} is not found)`)}e.cloneBefore(s)}}};mu.names=["grid-row-end","grid-column-end"];Zb.exports=mu});var tw=x((T$,ew)=>{u();var aT=j(),gu=class extends aT{check(e){return!e.value.split(/\s+/).some(t=>{let i=t.toLowerCase();return i==="reverse"||i==="alternate-reverse"})}};gu.names=["animation","animation-direction"];ew.exports=gu});var iw=x((R$,rw)=>{u();var oT=Pe(),lT=j(),yu=class extends lT{insert(e,t,i){let n;if([n,t]=oT(t),n!==2009)return super.insert(e,t,i);let s=e.value.split(/\s+/).filter(d=>d!=="wrap"&&d!=="nowrap"&&"wrap-reverse");if(s.length===0||e.parent.some(d=>d.prop===t+"box-orient"||d.prop===t+"box-direction"))return;let o=s[0],l=o.includes("row")?"horizontal":"vertical",c=o.includes("reverse")?"reverse":"normal",f=this.clone(e);return f.prop=t+"box-orient",f.value=l,this.needCascade(e)&&(f.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,f),f=this.clone(e),f.prop=t+"box-direction",f.value=c,this.needCascade(e)&&(f.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,f)}};yu.names=["flex-flow","box-direction","box-orient"];rw.exports=yu});var sw=x((P$,nw)=>{u();var uT=Pe(),fT=j(),bu=class extends fT{normalize(){return"flex"}prefixed(e,t){let i;return[i,t]=uT(t),i===2009?t+"box-flex":i===2012?t+"flex-positive":super.prefixed(e,t)}};bu.names=["flex-grow","flex-positive"];nw.exports=bu});var ow=x((I$,aw)=>{u();var cT=Pe(),pT=j(),wu=class extends pT{set(e,t){if(cT(t)[0]!==2009)return super.set(e,t)}};wu.names=["flex-wrap"];aw.exports=wu});var uw=x((D$,lw)=>{u();var dT=j(),Ar=Bt(),vu=class extends dT{insert(e,t,i,n){if(t!=="-ms-")return super.insert(e,t,i);let s=Ar.parse(e),[a,o]=Ar.translate(s,0,2),[l,c]=Ar.translate(s,1,3);[["grid-row",a],["grid-row-span",o],["grid-column",l],["grid-column-span",c]].forEach(([f,d])=>{Ar.insertDecl(e,f,d)}),Ar.warnTemplateSelectorNotFound(e,n),Ar.warnIfGridRowColumnExists(e,n)}};vu.names=["grid-area"];lw.exports=vu});var cw=x((q$,fw)=>{u();var hT=j(),Bi=Bt(),xu=class extends hT{insert(e,t,i){if(t!=="-ms-")return super.insert(e,t,i);if(e.parent.some(a=>a.prop==="-ms-grid-row-align"))return;let[[n,s]]=Bi.parse(e);s?(Bi.insertDecl(e,"grid-row-align",n),Bi.insertDecl(e,"grid-column-align",s)):(Bi.insertDecl(e,"grid-row-align",n),Bi.insertDecl(e,"grid-column-align",n))}};xu.names=["place-self"];fw.exports=xu});var dw=x(($$,pw)=>{u();var mT=j(),ku=class extends mT{check(e){let t=e.value;return!t.includes("/")||t.includes("span")}normalize(e){return e.replace("-start","")}prefixed(e,t){let i=super.prefixed(e,t);return t==="-ms-"&&(i=i.replace("-start","")),i}};ku.names=["grid-row-start","grid-column-start"];pw.exports=ku});var gw=x((L$,mw)=>{u();var hw=Pe(),gT=j(),Cr=class extends gT{check(e){return e.parent&&!e.parent.some(t=>t.prop&&t.prop.startsWith("grid-"))}prefixed(e,t){let i;return[i,t]=hw(t),i===2012?t+"flex-item-align":super.prefixed(e,t)}normalize(){return"align-self"}set(e,t){let i=hw(t)[0];if(i===2012)return e.value=Cr.oldValues[e.value]||e.value,super.set(e,t);if(i==="final")return super.set(e,t)}};Cr.names=["align-self","flex-item-align"];Cr.oldValues={"flex-end":"end","flex-start":"start"};mw.exports=Cr});var bw=x((M$,yw)=>{u();var yT=j(),bT=_e(),Su=class extends yT{constructor(e,t,i){super(e,t,i);this.prefixes&&(this.prefixes=bT.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}};Su.names=["appearance"];yw.exports=Su});var xw=x((N$,vw)=>{u();var ww=Pe(),wT=j(),Au=class extends wT{normalize(){return"flex-basis"}prefixed(e,t){let i;return[i,t]=ww(t),i===2012?t+"flex-preferred-size":super.prefixed(e,t)}set(e,t){let i;if([i,t]=ww(t),i===2012||i==="final")return super.set(e,t)}};Au.names=["flex-basis","flex-preferred-size"];vw.exports=Au});var Sw=x((B$,kw)=>{u();var vT=j(),Cu=class extends vT{normalize(){return this.name.replace("box-image","border")}prefixed(e,t){let i=super.prefixed(e,t);return t==="-webkit-"&&(i=i.replace("border","box-image")),i}};Cu.names=["mask-border","mask-border-source","mask-border-slice","mask-border-width","mask-border-outset","mask-border-repeat","mask-box-image","mask-box-image-source","mask-box-image-slice","mask-box-image-width","mask-box-image-outset","mask-box-image-repeat"];kw.exports=Cu});var Cw=x((F$,Aw)=>{u();var xT=j(),lt=class extends xT{insert(e,t,i){let n=e.prop==="mask-composite",s;n?s=e.value.split(","):s=e.value.match(lt.regexp)||[],s=s.map(c=>c.trim()).filter(c=>c);let a=s.length,o;if(a&&(o=this.clone(e),o.value=s.map(c=>lt.oldValues[c]||c).join(", "),s.includes("intersect")&&(o.value+=", xor"),o.prop=t+"mask-composite"),n)return a?(this.needCascade(e)&&(o.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,o)):void 0;let l=this.clone(e);return l.prop=t+l.prop,a&&(l.value=l.value.replace(lt.regexp,"")),this.needCascade(e)&&(l.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,l),a?(this.needCascade(e)&&(o.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,o)):e}};lt.names=["mask","mask-composite"];lt.oldValues={add:"source-over",subtract:"source-out",intersect:"source-in",exclude:"xor"};lt.regexp=new RegExp(`\\s+(${Object.keys(lt.oldValues).join("|")})\\b(?!\\))\\s*(?=[,])`,"ig");Aw.exports=lt});var Ow=x((j$,Ew)=>{u();var _w=Pe(),kT=j(),_r=class extends kT{prefixed(e,t){let i;return[i,t]=_w(t),i===2009?t+"box-align":i===2012?t+"flex-align":super.prefixed(e,t)}normalize(){return"align-items"}set(e,t){let i=_w(t)[0];return(i===2009||i===2012)&&(e.value=_r.oldValues[e.value]||e.value),super.set(e,t)}};_r.names=["align-items","flex-align","box-align"];_r.oldValues={"flex-end":"end","flex-start":"start"};Ew.exports=_r});var Rw=x((z$,Tw)=>{u();var ST=j(),_u=class extends ST{set(e,t){return t==="-ms-"&&e.value==="contain"&&(e.value="element"),super.set(e,t)}insert(e,t,i){if(!(e.value==="all"&&t==="-ms-"))return super.insert(e,t,i)}};_u.names=["user-select"];Tw.exports=_u});var Dw=x((U$,Iw)=>{u();var Pw=Pe(),AT=j(),Eu=class extends AT{normalize(){return"flex-shrink"}prefixed(e,t){let i;return[i,t]=Pw(t),i===2012?t+"flex-negative":super.prefixed(e,t)}set(e,t){let i;if([i,t]=Pw(t),i===2012||i==="final")return super.set(e,t)}};Eu.names=["flex-shrink","flex-negative"];Iw.exports=Eu});var $w=x((V$,qw)=>{u();var CT=j(),Ou=class extends CT{prefixed(e,t){return`${t}column-${e}`}normalize(e){return e.includes("inside")?"break-inside":e.includes("before")?"break-before":"break-after"}set(e,t){return(e.prop==="break-inside"&&e.value==="avoid-column"||e.value==="avoid-page")&&(e.value="avoid"),super.set(e,t)}insert(e,t,i){if(e.prop!=="break-inside")return super.insert(e,t,i);if(!(/region/i.test(e.value)||/page/i.test(e.value)))return super.insert(e,t,i)}};Ou.names=["break-inside","page-break-inside","column-break-inside","break-before","page-break-before","column-break-before","break-after","page-break-after","column-break-after"];qw.exports=Ou});var Mw=x((H$,Lw)=>{u();var _T=j(),Tu=class extends _T{prefixed(e,t){return t+"print-color-adjust"}normalize(){return"color-adjust"}};Tu.names=["color-adjust","print-color-adjust"];Lw.exports=Tu});var Bw=x((W$,Nw)=>{u();var ET=j(),Er=class extends ET{insert(e,t,i){if(t==="-ms-"){let n=this.set(this.clone(e),t);this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,t));let s="ltr";return e.parent.nodes.forEach(a=>{a.prop==="direction"&&(a.value==="rtl"||a.value==="ltr")&&(s=a.value)}),n.value=Er.msValues[s][e.value]||e.value,e.parent.insertBefore(e,n)}return super.insert(e,t,i)}};Er.names=["writing-mode"];Er.msValues={ltr:{"horizontal-tb":"lr-tb","vertical-rl":"tb-rl","vertical-lr":"tb-lr"},rtl:{"horizontal-tb":"rl-tb","vertical-rl":"bt-rl","vertical-lr":"bt-lr"}};Nw.exports=Er});var jw=x((G$,Fw)=>{u();var OT=j(),Ru=class extends OT{set(e,t){return e.value=e.value.replace(/\s+fill(\s)/,"$1"),super.set(e,t)}};Ru.names=["border-image"];Fw.exports=Ru});var Vw=x((Q$,Uw)=>{u();var zw=Pe(),TT=j(),Or=class extends TT{prefixed(e,t){let i;return[i,t]=zw(t),i===2012?t+"flex-line-pack":super.prefixed(e,t)}normalize(){return"align-content"}set(e,t){let i=zw(t)[0];if(i===2012)return e.value=Or.oldValues[e.value]||e.value,super.set(e,t);if(i==="final")return super.set(e,t)}};Or.names=["align-content","flex-line-pack"];Or.oldValues={"flex-end":"end","flex-start":"start","space-between":"justify","space-around":"distribute"};Uw.exports=Or});var Ww=x((Y$,Hw)=>{u();var RT=j(),We=class extends RT{prefixed(e,t){return t==="-moz-"?t+(We.toMozilla[e]||e):super.prefixed(e,t)}normalize(e){return We.toNormal[e]||e}};We.names=["border-radius"];We.toMozilla={};We.toNormal={};for(let r of["top","bottom"])for(let e of["left","right"]){let t=`border-${r}-${e}-radius`,i=`border-radius-${r}${e}`;We.names.push(t),We.names.push(i),We.toMozilla[t]=i,We.toNormal[i]=t}Hw.exports=We});var Qw=x((K$,Gw)=>{u();var PT=j(),Pu=class extends PT{prefixed(e,t){return e.includes("-start")?t+e.replace("-block-start","-before"):t+e.replace("-block-end","-after")}normalize(e){return e.includes("-before")?e.replace("-before","-block-start"):e.replace("-after","-block-end")}};Pu.names=["border-block-start","border-block-end","margin-block-start","margin-block-end","padding-block-start","padding-block-end","border-before","border-after","margin-before","margin-after","padding-before","padding-after"];Gw.exports=Pu});var Kw=x((X$,Yw)=>{u();var IT=j(),{parseTemplate:DT,warnMissedAreas:qT,getGridGap:$T,warnGridGap:LT,inheritGridGap:MT}=Bt(),Iu=class extends IT{insert(e,t,i,n){if(t!=="-ms-")return super.insert(e,t,i);if(e.parent.some(h=>h.prop==="-ms-grid-rows"))return;let s=$T(e),a=MT(e,s),{rows:o,columns:l,areas:c}=DT({decl:e,gap:a||s}),f=Object.keys(c).length>0,d=Boolean(o),p=Boolean(l);return LT({gap:s,hasColumns:p,decl:e,result:n}),qT(c,e,n),(d&&p||f)&&e.cloneBefore({prop:"-ms-grid-rows",value:o,raws:{}}),p&&e.cloneBefore({prop:"-ms-grid-columns",value:l,raws:{}}),e}};Iu.names=["grid-template"];Yw.exports=Iu});var Zw=x((Z$,Xw)=>{u();var NT=j(),Du=class extends NT{prefixed(e,t){return t+e.replace("-inline","")}normalize(e){return e.replace(/(margin|padding|border)-(start|end)/,"$1-inline-$2")}};Du.names=["border-inline-start","border-inline-end","margin-inline-start","margin-inline-end","padding-inline-start","padding-inline-end","border-start","border-end","margin-start","margin-end","padding-start","padding-end"];Xw.exports=Du});var e0=x((J$,Jw)=>{u();var BT=j(),qu=class extends BT{check(e){return!e.value.includes("flex-")&&e.value!=="baseline"}prefixed(e,t){return t+"grid-row-align"}normalize(){return"align-self"}};qu.names=["grid-row-align"];Jw.exports=qu});var r0=x((eL,t0)=>{u();var FT=j(),Tr=class extends FT{keyframeParents(e){let{parent:t}=e;for(;t;){if(t.type==="atrule"&&t.name==="keyframes")return!0;({parent:t}=t)}return!1}contain3d(e){if(e.prop==="transform-origin")return!1;for(let t of Tr.functions3d)if(e.value.includes(`${t}(`))return!0;return!1}set(e,t){return e=super.set(e,t),t==="-ms-"&&(e.value=e.value.replace(/rotatez/gi,"rotate")),e}insert(e,t,i){if(t==="-ms-"){if(!this.contain3d(e)&&!this.keyframeParents(e))return super.insert(e,t,i)}else if(t==="-o-"){if(!this.contain3d(e))return super.insert(e,t,i)}else return super.insert(e,t,i)}};Tr.names=["transform","transform-origin"];Tr.functions3d=["matrix3d","translate3d","translateZ","scale3d","scaleZ","rotate3d","rotateX","rotateY","perspective"];t0.exports=Tr});var s0=x((tL,n0)=>{u();var i0=Pe(),jT=j(),$u=class extends jT{normalize(){return"flex-direction"}insert(e,t,i){let n;if([n,t]=i0(t),n!==2009)return super.insert(e,t,i);if(e.parent.some(f=>f.prop===t+"box-orient"||f.prop===t+"box-direction"))return;let a=e.value,o,l;a==="inherit"||a==="initial"||a==="unset"?(o=a,l=a):(o=a.includes("row")?"horizontal":"vertical",l=a.includes("reverse")?"reverse":"normal");let c=this.clone(e);return c.prop=t+"box-orient",c.value=o,this.needCascade(e)&&(c.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,c),c=this.clone(e),c.prop=t+"box-direction",c.value=l,this.needCascade(e)&&(c.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,c)}old(e,t){let i;return[i,t]=i0(t),i===2009?[t+"box-orient",t+"box-direction"]:super.old(e,t)}};$u.names=["flex-direction","box-direction","box-orient"];n0.exports=$u});var o0=x((rL,a0)=>{u();var zT=j(),Lu=class extends zT{check(e){return e.value==="pixelated"}prefixed(e,t){return t==="-ms-"?"-ms-interpolation-mode":super.prefixed(e,t)}set(e,t){return t!=="-ms-"?super.set(e,t):(e.prop="-ms-interpolation-mode",e.value="nearest-neighbor",e)}normalize(){return"image-rendering"}process(e,t){return super.process(e,t)}};Lu.names=["image-rendering","interpolation-mode"];a0.exports=Lu});var u0=x((iL,l0)=>{u();var UT=j(),VT=_e(),Mu=class extends UT{constructor(e,t,i){super(e,t,i);this.prefixes&&(this.prefixes=VT.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}};Mu.names=["backdrop-filter"];l0.exports=Mu});var c0=x((nL,f0)=>{u();var HT=j(),WT=_e(),Nu=class extends HT{constructor(e,t,i){super(e,t,i);this.prefixes&&(this.prefixes=WT.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}check(e){return e.value.toLowerCase()==="text"}};Nu.names=["background-clip"];f0.exports=Nu});var d0=x((sL,p0)=>{u();var GT=j(),QT=["none","underline","overline","line-through","blink","inherit","initial","unset"],Bu=class extends GT{check(e){return e.value.split(/\s+/).some(t=>!QT.includes(t))}};Bu.names=["text-decoration"];p0.exports=Bu});var g0=x((aL,m0)=>{u();var h0=Pe(),YT=j(),Rr=class extends YT{prefixed(e,t){let i;return[i,t]=h0(t),i===2009?t+"box-pack":i===2012?t+"flex-pack":super.prefixed(e,t)}normalize(){return"justify-content"}set(e,t){let i=h0(t)[0];if(i===2009||i===2012){let n=Rr.oldValues[e.value]||e.value;if(e.value=n,i!==2009||n!=="distribute")return super.set(e,t)}else if(i==="final")return super.set(e,t)}};Rr.names=["justify-content","flex-pack","box-pack"];Rr.oldValues={"flex-end":"end","flex-start":"start","space-between":"justify","space-around":"distribute"};m0.exports=Rr});var b0=x((oL,y0)=>{u();var KT=j(),Fu=class extends KT{set(e,t){let i=e.value.toLowerCase();return t==="-webkit-"&&!i.includes(" ")&&i!=="contain"&&i!=="cover"&&(e.value=e.value+" "+e.value),super.set(e,t)}};Fu.names=["background-size"];y0.exports=Fu});var v0=x((lL,w0)=>{u();var XT=j(),ju=Bt(),zu=class extends XT{insert(e,t,i){if(t!=="-ms-")return super.insert(e,t,i);let n=ju.parse(e),[s,a]=ju.translate(n,0,1);n[0]&&n[0].includes("span")&&(a=n[0].join("").replace(/\D/g,"")),[[e.prop,s],[`${e.prop}-span`,a]].forEach(([l,c])=>{ju.insertDecl(e,l,c)})}};zu.names=["grid-row","grid-column"];w0.exports=zu});var S0=x((uL,k0)=>{u();var ZT=j(),{prefixTrackProp:x0,prefixTrackValue:JT,autoplaceGridItems:eR,getGridGap:tR,inheritGridGap:rR}=Bt(),iR=ou(),Uu=class extends ZT{prefixed(e,t){return t==="-ms-"?x0({prop:e,prefix:t}):super.prefixed(e,t)}normalize(e){return e.replace(/^grid-(rows|columns)/,"grid-template-$1")}insert(e,t,i,n){if(t!=="-ms-")return super.insert(e,t,i);let{parent:s,prop:a,value:o}=e,l=a.includes("rows"),c=a.includes("columns"),f=s.some(k=>k.prop==="grid-template"||k.prop==="grid-template-areas");if(f&&l)return!1;let d=new iR({options:{}}),p=d.gridStatus(s,n),h=tR(e);h=rR(e,h)||h;let b=l?h.row:h.column;(p==="no-autoplace"||p===!0)&&!f&&(b=null);let v=JT({value:o,gap:b});e.cloneBefore({prop:x0({prop:a,prefix:t}),value:v});let y=s.nodes.find(k=>k.prop==="grid-auto-flow"),w="row";if(y&&!d.disabled(y,n)&&(w=y.value.trim()),p==="autoplace"){let k=s.nodes.find(E=>E.prop==="grid-template-rows");if(!k&&f)return;if(!k&&!f){e.warn(n,"Autoplacement does not work without grid-template-rows property");return}!s.nodes.find(E=>E.prop==="grid-template-columns")&&!f&&e.warn(n,"Autoplacement does not work without grid-template-columns property"),c&&!f&&eR(e,n,h,w)}}};Uu.names=["grid-template-rows","grid-template-columns","grid-rows","grid-columns"];k0.exports=Uu});var C0=x((fL,A0)=>{u();var nR=j(),Vu=class extends nR{check(e){return!e.value.includes("flex-")&&e.value!=="baseline"}prefixed(e,t){return t+"grid-column-align"}normalize(){return"justify-self"}};Vu.names=["grid-column-align"];A0.exports=Vu});var E0=x((cL,_0)=>{u();var sR=j(),Hu=class extends sR{prefixed(e,t){return t+"scroll-chaining"}normalize(){return"overscroll-behavior"}set(e,t){return e.value==="auto"?e.value="chained":(e.value==="none"||e.value==="contain")&&(e.value="none"),super.set(e,t)}};Hu.names=["overscroll-behavior","scroll-chaining"];_0.exports=Hu});var R0=x((pL,T0)=>{u();var aR=j(),{parseGridAreas:oR,warnMissedAreas:lR,prefixTrackProp:uR,prefixTrackValue:O0,getGridGap:fR,warnGridGap:cR,inheritGridGap:pR}=Bt();function dR(r){return r.trim().slice(1,-1).split(/["']\s*["']?/g)}var Wu=class extends aR{insert(e,t,i,n){if(t!=="-ms-")return super.insert(e,t,i);let s=!1,a=!1,o=e.parent,l=fR(e);l=pR(e,l)||l,o.walkDecls(/-ms-grid-rows/,d=>d.remove()),o.walkDecls(/grid-template-(rows|columns)/,d=>{if(d.prop==="grid-template-rows"){a=!0;let{prop:p,value:h}=d;d.cloneBefore({prop:uR({prop:p,prefix:t}),value:O0({value:h,gap:l.row})})}else s=!0});let c=dR(e.value);s&&!a&&l.row&&c.length>1&&e.cloneBefore({prop:"-ms-grid-rows",value:O0({value:`repeat(${c.length}, auto)`,gap:l.row}),raws:{}}),cR({gap:l,hasColumns:s,decl:e,result:n});let f=oR({rows:c,gap:l});return lR(f,e,n),e}};Wu.names=["grid-template-areas"];T0.exports=Wu});var I0=x((dL,P0)=>{u();var hR=j(),Gu=class extends hR{set(e,t){return t==="-webkit-"&&(e.value=e.value.replace(/\s*(right|left)\s*/i,"")),super.set(e,t)}};Gu.names=["text-emphasis-position"];P0.exports=Gu});var q0=x((hL,D0)=>{u();var mR=j(),Qu=class extends mR{set(e,t){return e.prop==="text-decoration-skip-ink"&&e.value==="auto"?(e.prop=t+"text-decoration-skip",e.value="ink",e):super.set(e,t)}};Qu.names=["text-decoration-skip-ink","text-decoration-skip"];D0.exports=Qu});var F0=x((mL,B0)=>{u();"use strict";B0.exports={wrap:$0,limit:L0,validate:M0,test:Yu,curry:gR,name:N0};function $0(r,e,t){var i=e-r;return((t-r)%i+i)%i+r}function L0(r,e,t){return Math.max(r,Math.min(e,t))}function M0(r,e,t,i,n){if(!Yu(r,e,t,i,n))throw new Error(t+" is outside of range ["+r+","+e+")");return t}function Yu(r,e,t,i,n){return!(te||n&&t===e||i&&t===r)}function N0(r,e,t,i){return(t?"(":"[")+r+","+e+(i?")":"]")}function gR(r,e,t,i){var n=N0.bind(null,r,e,t,i);return{wrap:$0.bind(null,r,e),limit:L0.bind(null,r,e),validate:function(s){return M0(r,e,s,t,i)},test:function(s){return Yu(r,e,s,t,i)},toString:n,name:n}}});var U0=x((gL,z0)=>{u();var Ku=Ms(),yR=F0(),bR=xr(),wR=He(),vR=_e(),j0=/top|left|right|bottom/gi,wt=class extends wR{replace(e,t){let i=Ku(e);for(let n of i.nodes)if(n.type==="function"&&n.value===this.name)if(n.nodes=this.newDirection(n.nodes),n.nodes=this.normalize(n.nodes),t==="-webkit- old"){if(!this.oldWebkit(n))return!1}else n.nodes=this.convertDirection(n.nodes),n.value=t+n.value;return i.toString()}replaceFirst(e,...t){return t.map(n=>n===" "?{type:"space",value:n}:{type:"word",value:n}).concat(e.slice(1))}normalizeUnit(e,t){return`${parseFloat(e)/t*360}deg`}normalize(e){if(!e[0])return e;if(/-?\d+(.\d+)?grad/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,400);else if(/-?\d+(.\d+)?rad/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,2*Math.PI);else if(/-?\d+(.\d+)?turn/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,1);else if(e[0].value.includes("deg")){let t=parseFloat(e[0].value);t=yR.wrap(0,360,t),e[0].value=`${t}deg`}return e[0].value==="0deg"?e=this.replaceFirst(e,"to"," ","top"):e[0].value==="90deg"?e=this.replaceFirst(e,"to"," ","right"):e[0].value==="180deg"?e=this.replaceFirst(e,"to"," ","bottom"):e[0].value==="270deg"&&(e=this.replaceFirst(e,"to"," ","left")),e}newDirection(e){if(e[0].value==="to"||(j0.lastIndex=0,!j0.test(e[0].value)))return e;e.unshift({type:"word",value:"to"},{type:"space",value:" "});for(let t=2;t0&&(e[0].value==="to"?this.fixDirection(e):e[0].value.includes("deg")?this.fixAngle(e):this.isRadial(e)&&this.fixRadial(e)),e}fixDirection(e){e.splice(0,2);for(let t of e){if(t.type==="div")break;t.type==="word"&&(t.value=this.revertDirection(t.value))}}fixAngle(e){let t=e[0].value;t=parseFloat(t),t=Math.abs(450-t)%360,t=this.roundFloat(t,3),e[0].value=`${t}deg`}fixRadial(e){let t=[],i=[],n,s,a,o,l;for(o=0;o{u();var xR=xr(),kR=He();function V0(r){return new RegExp(`(^|[\\s,(])(${r}($|[\\s),]))`,"gi")}var Xu=class extends kR{regexp(){return this.regexpCache||(this.regexpCache=V0(this.name)),this.regexpCache}isStretch(){return this.name==="stretch"||this.name==="fill"||this.name==="fill-available"}replace(e,t){return t==="-moz-"&&this.isStretch()?e.replace(this.regexp(),"$1-moz-available$3"):t==="-webkit-"&&this.isStretch()?e.replace(this.regexp(),"$1-webkit-fill-available$3"):super.replace(e,t)}old(e){let t=e+this.name;return this.isStretch()&&(e==="-moz-"?t="-moz-available":e==="-webkit-"&&(t="-webkit-fill-available")),new xR(this.name,t,t,V0(t))}add(e,t){if(!(e.prop.includes("grid")&&t!=="-webkit-"))return super.add(e,t)}};Xu.names=["max-content","min-content","fit-content","fill","fill-available","stretch"];H0.exports=Xu});var Y0=x((bL,Q0)=>{u();var G0=xr(),SR=He(),Zu=class extends SR{replace(e,t){return t==="-webkit-"?e.replace(this.regexp(),"$1-webkit-optimize-contrast"):t==="-moz-"?e.replace(this.regexp(),"$1-moz-crisp-edges"):super.replace(e,t)}old(e){return e==="-webkit-"?new G0(this.name,"-webkit-optimize-contrast"):e==="-moz-"?new G0(this.name,"-moz-crisp-edges"):super.old(e)}};Zu.names=["pixelated"];Q0.exports=Zu});var X0=x((wL,K0)=>{u();var AR=He(),Ju=class extends AR{replace(e,t){let i=super.replace(e,t);return t==="-webkit-"&&(i=i.replace(/("[^"]+"|'[^']+')(\s+\d+\w)/gi,"url($1)$2")),i}};Ju.names=["image-set"];K0.exports=Ju});var J0=x((vL,Z0)=>{u();var CR=$e().list,_R=He(),ef=class extends _R{replace(e,t){return CR.space(e).map(i=>{if(i.slice(0,+this.name.length+1)!==this.name+"(")return i;let n=i.lastIndexOf(")"),s=i.slice(n+1),a=i.slice(this.name.length+1,n);if(t==="-webkit-"){let o=a.match(/\d*.?\d+%?/);o?(a=a.slice(o[0].length).trim(),a+=`, ${o[0]}`):a+=", 0.5"}return t+this.name+"("+a+")"+s}).join(" ")}};ef.names=["cross-fade"];Z0.exports=ef});var tv=x((xL,ev)=>{u();var ER=Pe(),OR=xr(),TR=He(),tf=class extends TR{constructor(e,t){super(e,t);e==="display-flex"&&(this.name="flex")}check(e){return e.prop==="display"&&e.value===this.name}prefixed(e){let t,i;return[t,e]=ER(e),t===2009?this.name==="flex"?i="box":i="inline-box":t===2012?this.name==="flex"?i="flexbox":i="inline-flexbox":t==="final"&&(i=this.name),e+i}replace(e,t){return this.prefixed(t)}old(e){let t=this.prefixed(e);if(!!t)return new OR(this.name,t)}};tf.names=["display-flex","inline-flex"];ev.exports=tf});var iv=x((kL,rv)=>{u();var RR=He(),rf=class extends RR{constructor(e,t){super(e,t);e==="display-grid"&&(this.name="grid")}check(e){return e.prop==="display"&&e.value===this.name}};rf.names=["display-grid","inline-grid"];rv.exports=rf});var sv=x((SL,nv)=>{u();var PR=He(),nf=class extends PR{constructor(e,t){super(e,t);e==="filter-function"&&(this.name="filter")}};nf.names=["filter","filter-function"];nv.exports=nf});var uv=x((AL,lv)=>{u();var av=Ni(),z=j(),ov=zy(),IR=ab(),DR=ou(),qR=Cb(),sf=Mt(),Pr=kr(),$R=Db(),ut=He(),Ir=_e(),LR=$b(),MR=Mb(),NR=Bb(),BR=jb(),FR=Wb(),jR=Yb(),zR=Xb(),UR=Jb(),VR=tw(),HR=iw(),WR=sw(),GR=ow(),QR=uw(),YR=cw(),KR=dw(),XR=gw(),ZR=bw(),JR=xw(),e5=Sw(),t5=Cw(),r5=Ow(),i5=Rw(),n5=Dw(),s5=$w(),a5=Mw(),o5=Bw(),l5=jw(),u5=Vw(),f5=Ww(),c5=Qw(),p5=Kw(),d5=Zw(),h5=e0(),m5=r0(),g5=s0(),y5=o0(),b5=u0(),w5=c0(),v5=d0(),x5=g0(),k5=b0(),S5=v0(),A5=S0(),C5=C0(),_5=E0(),E5=R0(),O5=I0(),T5=q0(),R5=U0(),P5=W0(),I5=Y0(),D5=X0(),q5=J0(),$5=tv(),L5=iv(),M5=sv();Pr.hack(LR);Pr.hack(MR);Pr.hack(NR);Pr.hack(BR);z.hack(FR);z.hack(jR);z.hack(zR);z.hack(UR);z.hack(VR);z.hack(HR);z.hack(WR);z.hack(GR);z.hack(QR);z.hack(YR);z.hack(KR);z.hack(XR);z.hack(ZR);z.hack(JR);z.hack(e5);z.hack(t5);z.hack(r5);z.hack(i5);z.hack(n5);z.hack(s5);z.hack(a5);z.hack(o5);z.hack(l5);z.hack(u5);z.hack(f5);z.hack(c5);z.hack(p5);z.hack(d5);z.hack(h5);z.hack(m5);z.hack(g5);z.hack(y5);z.hack(b5);z.hack(w5);z.hack(v5);z.hack(x5);z.hack(k5);z.hack(S5);z.hack(A5);z.hack(C5);z.hack(_5);z.hack(E5);z.hack(O5);z.hack(T5);ut.hack(R5);ut.hack(P5);ut.hack(I5);ut.hack(D5);ut.hack(q5);ut.hack($5);ut.hack(L5);ut.hack(M5);var af=new Map,Fi=class{constructor(e,t,i={}){this.data=e,this.browsers=t,this.options=i,[this.add,this.remove]=this.preprocess(this.select(this.data)),this.transition=new IR(this),this.processor=new DR(this)}cleaner(){if(this.cleanerCache)return this.cleanerCache;if(this.browsers.selected.length){let e=new sf(this.browsers.data,[]);this.cleanerCache=new Fi(this.data,e,this.options)}else return this;return this.cleanerCache}select(e){let t={add:{},remove:{}};for(let i in e){let n=e[i],s=n.browsers.map(l=>{let c=l.split(" ");return{browser:`${c[0]} ${c[1]}`,note:c[2]}}),a=s.filter(l=>l.note).map(l=>`${this.browsers.prefix(l.browser)} ${l.note}`);a=Ir.uniq(a),s=s.filter(l=>this.browsers.isSelected(l.browser)).map(l=>{let c=this.browsers.prefix(l.browser);return l.note?`${c} ${l.note}`:c}),s=this.sort(Ir.uniq(s)),this.options.flexbox==="no-2009"&&(s=s.filter(l=>!l.includes("2009")));let o=n.browsers.map(l=>this.browsers.prefix(l));n.mistakes&&(o=o.concat(n.mistakes)),o=o.concat(a),o=Ir.uniq(o),s.length?(t.add[i]=s,s.length!s.includes(l)))):t.remove[i]=o}return t}sort(e){return e.sort((t,i)=>{let n=Ir.removeNote(t).length,s=Ir.removeNote(i).length;return n===s?i.length-t.length:s-n})}preprocess(e){let t={selectors:[],"@supports":new qR(Fi,this)};for(let n in e.add){let s=e.add[n];if(n==="@keyframes"||n==="@viewport")t[n]=new $R(n,s,this);else if(n==="@resolution")t[n]=new ov(n,s,this);else if(this.data[n].selector)t.selectors.push(Pr.load(n,s,this));else{let a=this.data[n].props;if(a){let o=ut.load(n,s,this);for(let l of a)t[l]||(t[l]={values:[]}),t[l].values.push(o)}else{let o=t[n]&&t[n].values||[];t[n]=z.load(n,s,this),t[n].values=o}}}let i={selectors:[]};for(let n in e.remove){let s=e.remove[n];if(this.data[n].selector){let a=Pr.load(n,s);for(let o of s)i.selectors.push(a.old(o))}else if(n==="@keyframes"||n==="@viewport")for(let a of s){let o=`@${a}${n.slice(1)}`;i[o]={remove:!0}}else if(n==="@resolution")i[n]=new ov(n,s,this);else{let a=this.data[n].props;if(a){let o=ut.load(n,[],this);for(let l of s){let c=o.old(l);if(c)for(let f of a)i[f]||(i[f]={}),i[f].values||(i[f].values=[]),i[f].values.push(c)}}else for(let o of s){let l=this.decl(n).old(n,o);if(n==="align-self"){let c=t[n]&&t[n].prefixes;if(c){if(o==="-webkit- 2009"&&c.includes("-webkit-"))continue;if(o==="-webkit-"&&c.includes("-webkit- 2009"))continue}}for(let c of l)i[c]||(i[c]={}),i[c].remove=!0}}}return[t,i]}decl(e){return af.has(e)||af.set(e,z.load(e)),af.get(e)}unprefixed(e){let t=this.normalize(av.unprefixed(e));return t==="flex-direction"&&(t="flex-flow"),t}normalize(e){return this.decl(e).normalize(e)}prefixed(e,t){return e=av.unprefixed(e),this.decl(e).prefixed(e,t)}values(e,t){let i=this[e],n=i["*"]&&i["*"].values,s=i[t]&&i[t].values;return n&&s?Ir.uniq(n.concat(s)):n||s||[]}group(e){let t=e.parent,i=t.index(e),{length:n}=t.nodes,s=this.unprefixed(e.prop),a=(o,l)=>{for(i+=o;i>=0&&i{u();fv.exports={"backdrop-filter":{feature:"css-backdrop-filter",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},element:{props:["background","background-image","border-image","mask","list-style","list-style-image","content","mask-image"],feature:"css-element-function",browsers:["firefox 114"]},"user-select":{mistakes:["-khtml-"],feature:"user-select-none",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},"background-clip":{feature:"background-clip-text",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},hyphens:{feature:"css-hyphens",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},fill:{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"fill-available":{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},stretch:{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["firefox 114"]},"fit-content":{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["firefox 114"]},"text-decoration-style":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-color":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-line":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-skip":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-skip-ink":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-size-adjust":{feature:"text-size-adjust",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"mask-clip":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-composite":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-image":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-origin":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-repeat":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-repeat":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-source":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},mask:{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-position":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-size":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-outset":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-width":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-slice":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"clip-path":{feature:"css-clip-path",browsers:["samsung 21"]},"box-decoration-break":{feature:"css-boxdecorationbreak",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","opera 99","safari 16.5","samsung 21"]},appearance:{feature:"css-appearance",browsers:["samsung 21"]},"image-set":{props:["background","background-image","border-image","cursor","mask","mask-image","list-style","list-style-image","content"],feature:"css-image-set",browsers:["and_uc 15.5","chrome 109","samsung 21"]},"cross-fade":{props:["background","background-image","border-image","mask","list-style","list-style-image","content","mask-image"],feature:"css-cross-fade",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},isolate:{props:["unicode-bidi"],feature:"css-unicode-bidi",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},"color-adjust":{feature:"css-color-adjust",browsers:["chrome 109","chrome 113","chrome 114","edge 114","opera 99"]}}});var dv=x((_L,pv)=>{u();pv.exports={}});var yv=x((EL,gv)=>{u();var N5=Yl(),{agents:B5}=(Ps(),Rs),of=Oy(),F5=Mt(),j5=uv(),z5=cv(),U5=dv(),hv={browsers:B5,prefixes:z5},mv=` + Replace Autoprefixer \`browsers\` option to Browserslist config. + Use \`browserslist\` key in \`package.json\` or \`.browserslistrc\` file. + + Using \`browsers\` option can cause errors. Browserslist config can + be used for Babel, Autoprefixer, postcss-normalize and other tools. + + If you really need to use option, rename it to \`overrideBrowserslist\`. + + Learn more at: + https://github.com/browserslist/browserslist#readme + https://twitter.com/browserslist + +`;function V5(r){return Object.prototype.toString.apply(r)==="[object Object]"}var lf=new Map;function H5(r,e){e.browsers.selected.length!==0&&(e.add.selectors.length>0||Object.keys(e.add).length>2||r.warn(`Autoprefixer target browsers do not need any prefixes.You do not need Autoprefixer anymore. +Check your Browserslist config to be sure that your targets are set up correctly. + + Learn more at: + https://github.com/postcss/autoprefixer#readme + https://github.com/browserslist/browserslist#readme + +`))}gv.exports=Dr;function Dr(...r){let e;if(r.length===1&&V5(r[0])?(e=r[0],r=void 0):r.length===0||r.length===1&&!r[0]?r=void 0:r.length<=2&&(Array.isArray(r[0])||!r[0])?(e=r[1],r=r[0]):typeof r[r.length-1]=="object"&&(e=r.pop()),e||(e={}),e.browser)throw new Error("Change `browser` option to `overrideBrowserslist` in Autoprefixer");if(e.browserslist)throw new Error("Change `browserslist` option to `overrideBrowserslist` in Autoprefixer");e.overrideBrowserslist?r=e.overrideBrowserslist:e.browsers&&(typeof console!="undefined"&&console.warn&&(of.red?console.warn(of.red(mv.replace(/`[^`]+`/g,n=>of.yellow(n.slice(1,-1))))):console.warn(mv)),r=e.browsers);let t={ignoreUnknownVersions:e.ignoreUnknownVersions,stats:e.stats,env:e.env};function i(n){let s=hv,a=new F5(s.browsers,r,n,t),o=a.selected.join(", ")+JSON.stringify(e);return lf.has(o)||lf.set(o,new j5(s.prefixes,a,e)),lf.get(o)}return{postcssPlugin:"autoprefixer",prepare(n){let s=i({from:n.opts.from,env:e.env});return{OnceExit(a){H5(n,s),e.remove!==!1&&s.processor.remove(a,n),e.add!==!1&&s.processor.add(a,n)}}},info(n){return n=n||{},n.from=n.from||m.cwd(),U5(i(n))},options:e,browsers:r}}Dr.postcss=!0;Dr.data=hv;Dr.defaults=N5.defaults;Dr.info=()=>Dr().info()});var bv={};Ge(bv,{default:()=>W5});var W5,wv=P(()=>{u();W5=[]});var xv={};Ge(xv,{default:()=>G5});var vv,G5,kv=P(()=>{u();Xi();vv=pe(rn()),G5=St(vv.default.theme)});var Av={};Ge(Av,{default:()=>Q5});var Sv,Q5,Cv=P(()=>{u();Xi();Sv=pe(rn()),Q5=St(Sv.default)});u();"use strict";var Y5=vt(_y()),K5=vt($e()),X5=vt(yv()),Z5=vt((wv(),bv)),J5=vt((kv(),xv)),eP=vt((Cv(),Av)),tP=vt((Vs(),_f)),rP=vt((al(),sl)),iP=vt((sa(),sc));function vt(r){return r&&r.__esModule?r:{default:r}}console.warn("cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation");var Ns="tailwind",uf="text/tailwindcss",_v="/template.html",Yt,Ev=!0,Ov=0,ff=new Set,cf,Tv="",Rv=(r=!1)=>({get(e,t){return(!r||t==="config")&&typeof e[t]=="object"&&e[t]!==null?new Proxy(e[t],Rv()):e[t]},set(e,t,i){return e[t]=i,(!r||t==="config")&&pf(!0),!0}});window[Ns]=new Proxy({config:{},defaultTheme:J5.default,defaultConfig:eP.default,colors:tP.default,plugin:rP.default,resolveConfig:iP.default},Rv(!0));function Pv(r){cf.observe(r,{attributes:!0,attributeFilter:["type"],characterData:!0,subtree:!0,childList:!0})}new MutationObserver(async r=>{let e=!1;if(!cf){cf=new MutationObserver(async()=>await pf(!0));for(let t of document.querySelectorAll(`style[type="${uf}"]`))Pv(t)}for(let t of r)for(let i of t.addedNodes)i.nodeType===1&&i.tagName==="STYLE"&&i.getAttribute("type")===uf&&(Pv(i),e=!0);await pf(e)}).observe(document.documentElement,{attributes:!0,attributeFilter:["class"],childList:!0,subtree:!0});async function pf(r=!1){r&&(Ov++,ff.clear());let e="";for(let i of document.querySelectorAll(`style[type="${uf}"]`))e+=i.textContent;let t=new Set;for(let i of document.querySelectorAll("[class]"))for(let n of i.classList)ff.has(n)||t.add(n);if(document.body&&(Ev||t.size>0||e!==Tv||!Yt||!Yt.isConnected)){for(let n of t)ff.add(n);Ev=!1,Tv=e,self[_v]=Array.from(t).join(" ");let{css:i}=await(0,K5.default)([(0,Y5.default)({...window[Ns].config,_hash:Ov,content:{files:[_v],extract:{html:n=>n.split(" ")}},plugins:[...Z5.default,...Array.isArray(window[Ns].config.plugins)?window[Ns].config.plugins:[]]}),(0,X5.default)({remove:!1})]).process(`@tailwind base;@tailwind components;@tailwind utilities;${e}`);(!Yt||!Yt.isConnected)&&(Yt=document.createElement("style"),document.head.append(Yt)),Yt.textContent=i}}})(); +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ +/*! https://mths.be/cssesc v3.0.0 by @mathias */ diff --git a/src/routes/admin.js b/src/routes/admin.js new file mode 100644 index 0000000..3d462af --- /dev/null +++ b/src/routes/admin.js @@ -0,0 +1,1248 @@ +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const { getPrisma } = require('../config/prisma'); +const monitorService = require('../services/monitorService'); +const IncidentService = require('../services/incidentService'); +const { adminPageAuth } = require('../middleware/auth'); +const chalk = require('../utils/colors'); +const { v4: uuidv4 } = require('uuid'); + +// Admin login page (GET) +router.get('/login', (req, res) => { + if (req.session && req.session.adminAuthenticated) { + return res.redirect('/admin'); + } + res.render('admin/login'); +}); + +// Admin login (POST) +router.post('/login', async (req, res) => { + const { username, password } = req.body; + const adminUsername = process.env.ADMIN_USERNAME; + const adminPassword = process.env.ADMIN_PASSWORD; + + if (!adminUsername || !adminPassword) { + return res.status(401).json({ success: false, error: 'Admin authentication not configured' }); + } + + const providedUsername = (username || '').trim(); + const providedPassword = (password || '').trim(); + const storedUsername = (adminUsername || '').trim(); + const storedPassword = (adminPassword || '').trim(); + + if (providedUsername === storedUsername && providedPassword === storedPassword) { + const prisma = getPrisma(); + let sessionDurationDays = 30; + try { + const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + if (settings?.sessionDurationDays) { + sessionDurationDays = settings.sessionDurationDays; + } + } catch (error) { + console.error('Error loading session duration:', error); + } + + req.session.adminAuthenticated = true; + req.session.loginTime = new Date(); + req.session.username = providedUsername; + + const maxAge = sessionDurationDays * 24 * 60 * 60 * 1000; + req.session.cookie.maxAge = maxAge; + req.session.cookie.expires = new Date(Date.now() + maxAge); + + return res.json({ success: true, message: 'Authenticated' }); + } else { + return res.status(401).json({ success: false, error: 'Invalid username or password' }); + } +}); + +// Admin logout +router.get('/logout', (req, res) => { + req.session.adminAuthenticated = false; + req.session.destroy((err) => { + if (err) console.error('Error destroying session:', err); + res.redirect('/admin/login'); + }); +}); + +// Admin dashboard - Monitors tab (default) +router.get('/', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'monitors' }); +}); + +// Admin Incidents tab +router.get('/incidents', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'incidents' }); +}); + +// Admin Event Detection Rules tab +router.get('/events', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'event-rules' }); +}); + +// Admin Blog Posts tab +router.get('/blogs', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'posts' }); +}); + +// Admin Public Visibility tab +router.get('/visibility', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'visibility' }); +}); + +// Admin Settings tab +router.get('/settings', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'settings' }); +}); + +// Admin Backup & Restore tab +router.get('/backup', adminPageAuth, (req, res) => { + res.render('admin/index', { currentTab: 'backup' }); +}); + +// Proxy endpoint for icons +router.get('/api/proxy-icon', async (req, res) => { + try { + const { url } = req.query; + if (!url) return res.status(400).json({ success: false, error: 'URL parameter is required' }); + + let targetUrl; + try { + targetUrl = new URL(url); + } catch (e) { + return res.status(400).json({ success: false, error: 'Invalid URL' }); + } + + const https = require('https'); + const response = await axios.get(url, { + responseType: 'arraybuffer', + timeout: 10000, + headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }, + validateStatus: (status) => status < 500, + httpsAgent: new https.Agent({ rejectUnauthorized: false }), + }); + + if (response.status >= 400) { + return res.status(404).json({ success: false, error: 'Icon not found' }); + } + + const contentType = response.headers['content-type'] || 'image/png'; + res.setHeader('Content-Type', contentType); + res.setHeader('Cache-Control', 'public, max-age=86400'); + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(Buffer.from(response.data)); + } catch (error) { + console.error('Error proxying icon:', error.message); + res.status(500).json({ success: false, error: 'Failed to fetch icon' }); + } +}); + +// Apply auth middleware to all admin API routes (except proxy-icon) +router.use('/api', (req, res, next) => { + if (req.path === '/proxy-icon') return next(); + adminPageAuth(req, res, next); +}); + +// Site (public frontend) management: per-service explainers/tiers + branding +router.get('/site', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'site.html'))); +router.get('/api/site/meta', async (req, res) => { + const prisma = getPrisma(); + const targets = await prisma.target.findMany({ select: { id: true, name: true, description: true, tier: true, linkPublic: true, publicVisible: true, appUrl: true, position: true }, orderBy: { position: 'asc' } }); + const b = await prisma.siteBrand.findUnique({ where: { id: 'brand' } }); + res.json({ targets, brand: { name: b?.name || '', accent: b?.accent || '', tagline: b?.tagline || '', hasIcon: !!b?.iconData } }); +}); +router.put('/api/site/meta/:id', async (req, res) => { + const { description, tier, linkPublic } = req.body; + const data = {}; + if (description !== undefined) data.description = String(description).slice(0, 400) || null; + if (['featured', 'normal', 'background'].includes(tier)) data.tier = tier; + if (linkPublic !== undefined) data.linkPublic = !!linkPublic; + await getPrisma().target.update({ where: { id: req.params.id }, data }); + require('./site').invalidate && require('./site').invalidate(); + res.json({ success: true }); +}); +router.put('/api/site/brand', express.json({ limit: '3mb' }), async (req, res) => { + const { name, accent, tagline, iconBase64, resetIcon } = req.body; + const data = { name: name || null, tagline: tagline || null, accent: /^#[0-9a-f]{6}$/i.test(accent || '') ? accent : null }; + if (resetIcon) { data.iconData = null; data.iconType = null; } + if (iconBase64) { + const m = /^data:(image\/(png|webp|jpeg|svg\+xml));base64,(.+)$/.exec(iconBase64); + if (!m) return res.status(400).json({ success: false, error: 'Icon must be a PNG, JPEG, WebP or SVG data URL' }); + const buf = Buffer.from(m[3], 'base64'); + if (buf.length > 2 * 1024 * 1024) return res.status(400).json({ success: false, error: 'Icon too large (max 2 MB)' }); + data.iconData = buf; data.iconType = m[1]; + } + await getPrisma().siteBrand.upsert({ where: { id: 'brand' }, create: { id: 'brand', ...data }, update: data }); + require('./site').invalidateBrand(); + res.json({ success: true }); +}); + +// Dashboard API +router.get('/api/dashboard', async (req, res) => { + try { + const prisma = getPrisma(); + + const targets = await prisma.target.findMany({ + select: { + id: true, + name: true, + host: true, + protocol: true, + port: true, + enabled: true, + publicVisible: true, + appUrl: true, + appIcon: true, + group: true, + position: true, + interval: true, + retries: true, + timeout: true, + createdAt: true, + updatedAt: true, + }, + }); + + const targetsWithStatus = targets.map((target) => ({ + ...target, + _id: target.id, + currentStatus: monitorService.getTargetStatus(target.id), + })); + + const alerts = await prisma.alert.findMany({ + orderBy: { timestamp: 'desc' }, + take: 20, + select: { + id: true, + targetId: true, + type: true, + timestamp: true, + message: true, + }, + }); + + res.json({ + success: true, + dashboard: { + targets: targetsWithStatus, + recentAlerts: alerts.map(a => ({ ...a, _id: a.id })), + timestamp: new Date(), + }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ ACTIONS ============ +router.get('/api/actions', async (req, res) => { + try { + const prisma = getPrisma(); + const actions = await prisma.action.findMany(); + res.json({ success: true, actions: actions.map(a => ({ ...a, _id: a.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/actions/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const action = await prisma.action.findUnique({ where: { id: req.params.id } }); + if (!action) return res.status(404).json({ success: false, error: 'Action not found' }); + res.json({ success: true, action: { ...action, _id: action.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/actions', async (req, res) => { + try { + const { name, type, targetId, command } = req.body; + if (!name || !type) return res.status(400).json({ success: false, error: 'Missing required fields' }); + + const prisma = getPrisma(); + const action = await prisma.action.create({ + data: { name, type, targetId: targetId || null, command: command || null }, + }); + + res.json({ success: true, actionId: action.id, action: { ...action, _id: action.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/actions/:id', async (req, res) => { + try { + const prisma = getPrisma(); + await prisma.action.update({ where: { id: req.params.id }, data: req.body }); + res.json({ success: true, message: 'Action updated' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Action not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.delete('/api/actions/:id', async (req, res) => { + try { + const prisma = getPrisma(); + await prisma.action.delete({ where: { id: req.params.id } }); + res.json({ success: true, message: 'Action deleted' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Action not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/actions/:id/execute', async (req, res) => { + try { + const prisma = getPrisma(); + const action = await prisma.action.findUnique({ where: { id: req.params.id } }); + if (!action) return res.status(404).json({ success: false, error: 'Action not found' }); + + const actionService = require('../services/actionService'); + const result = await actionService.executeAction(action); + res.json({ success: true, result }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ INCIDENTS ============ +router.get('/api/incidents', async (req, res) => { + try { + const prisma = getPrisma(); + const incidentService = new IncidentService(prisma); + const incidents = await incidentService.getIncidents(); + res.json({ success: true, incidents: incidents.map(i => ({ ...i, _id: i.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/incidents/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const incidentService = new IncidentService(prisma); + const incident = await incidentService.getIncidentById(req.params.id); + if (!incident) return res.status(404).json({ success: false, error: 'Incident not found' }); + res.json({ success: true, incident: { ...incident, _id: incident.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/incidents', async (req, res) => { + try { + const prisma = getPrisma(); + const incidentService = new IncidentService(prisma); + const { title, description, status, severity, affectedServices, isScheduled, scheduledStart, scheduledEnd } = req.body; + + if (!title || !description) { + return res.status(400).json({ success: false, error: 'Title and description are required' }); + } + + // Ensure isScheduled is a boolean + const isScheduledBool = isScheduled === true || isScheduled === 'true' || isScheduled === 1; + + const result = await incidentService.createIncident({ + title, + description, + status, + severity, + affectedServices, + isScheduled: isScheduledBool, + scheduledStart, + scheduledEnd + }); + res.json(result); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/incidents/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const incidentService = new IncidentService(prisma); + const { title, description, status, severity, affectedServices, updateMessage, isScheduled, scheduledStart, scheduledEnd } = req.body; + + // Ensure isScheduled is a boolean + const isScheduledBool = isScheduled === true || isScheduled === 'true' || isScheduled === 1; + + const updated = await incidentService.updateIncident(req.params.id, { + title, description, status, severity, affectedServices, updateMessage, + isScheduled: isScheduledBool, scheduledStart, scheduledEnd + }); + + if (!updated) return res.status(404).json({ success: false, error: 'Incident not found' }); + res.json({ success: true, message: 'Incident updated' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.delete('/api/incidents/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const incidentService = new IncidentService(prisma); + const deleted = await incidentService.deleteIncident(req.params.id); + if (!deleted) return res.status(404).json({ success: false, error: 'Incident not found' }); + res.json({ success: true, message: 'Incident deleted' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ EVENT RULES ============ +router.get('/api/event-rules', async (req, res) => { + try { + const prisma = getPrisma(); + const rules = await prisma.eventRule.findMany({ orderBy: { createdAt: 'desc' } }); + res.json({ success: true, rules: rules.map(r => ({ ...r, _id: r.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/event-rules/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const rule = await prisma.eventRule.findUnique({ where: { id: req.params.id } }); + if (!rule) return res.status(404).json({ success: false, error: 'Event rule not found' }); + res.json({ success: true, rule: { ...rule, _id: rule.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/event-rules', async (req, res) => { + try { + const prisma = getPrisma(); + const { + name, eventType, enabled, conditions, incidentTitle, incidentDescription, + incidentSeverity, incidentStatus, autoResolve, autoResolveMessage, cooldownMinutes, + } = req.body; + + if (!name || !eventType || !conditions || !incidentTitle || !incidentDescription) { + return res.status(400).json({ success: false, error: 'Missing required fields' }); + } + + const rule = await prisma.eventRule.create({ + data: { + name, eventType, enabled: enabled !== false, conditions, + incidentTitle, incidentDescription, + incidentSeverity: incidentSeverity || 'major', + incidentStatus: incidentStatus || 'investigating', + autoResolve: autoResolve === true, + autoResolveMessage: autoResolveMessage || null, + cooldownMinutes: cooldownMinutes || 0, + }, + }); + + res.json({ success: true, ruleId: rule.id, rule: { ...rule, _id: rule.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/event-rules/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const updateData = { ...req.body }; + delete updateData.id; + delete updateData._id; + + await prisma.eventRule.update({ where: { id: req.params.id }, data: updateData }); + res.json({ success: true, message: 'Event rule updated' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Event rule not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.delete('/api/event-rules/:id', async (req, res) => { + try { + const prisma = getPrisma(); + await prisma.eventRule.delete({ where: { id: req.params.id } }); + res.json({ success: true, message: 'Event rule deleted' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Event rule not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/event-rules/:id/test', async (req, res) => { + try { + const prisma = getPrisma(); + const eventDetectionService = require('../services/eventDetectionService'); + await eventDetectionService.initialize(); + + const rule = await prisma.eventRule.findUnique({ where: { id: req.params.id } }); + if (!rule) return res.status(404).json({ success: false, error: 'Event rule not found' }); + + const context = req.body.context || {}; + const shouldTrigger = await eventDetectionService.evaluateRule(rule, context); + res.json({ success: true, shouldTrigger, context }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ TARGETS ============ +router.get('/api/targets', async (req, res) => { + try { + const prisma = getPrisma(); + const targets = await prisma.target.findMany(); + + const targetsWithStatus = targets.map((target) => ({ + ...target, + _id: target.id, + currentStatus: monitorService.getTargetStatus(target.id), + })); + + res.json({ success: true, targets: targetsWithStatus }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/targets/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const target = await prisma.target.findUnique({ where: { id: req.params.id } }); + if (!target) return res.status(404).json({ success: false, error: 'Target not found' }); + + res.json({ + success: true, + target: { ...target, _id: target.id, currentStatus: monitorService.getTargetStatus(target.id) }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/targets', async (req, res) => { + try { + const { + name, host, port, protocol, path, interval, enabled, publicVisible, + publicShowDetails, publicShowStatus, publicShowAppLink, appUrl, appIcon, + retries, retryInterval, timeout, httpMethod, statusCodes, maxRedirects, + ignoreSsl, upsideDown, important, auth, position, group, quickCommands, + } = req.body; + + if (!name || !host || !protocol) { + return res.status(400).json({ success: false, error: 'Missing required fields: name, host, protocol' }); + } + + const prisma = getPrisma(); + const target = await prisma.target.create({ + data: { + name, host, port: port || null, protocol: protocol.toUpperCase(), path: path || null, + interval: interval || 60, enabled: enabled !== false, publicVisible: publicVisible !== false, + publicShowDetails: publicShowDetails === true, publicShowStatus: publicShowStatus !== false, + publicShowAppLink: publicShowAppLink !== false, appUrl: appUrl || null, appIcon: appIcon || null, + retries: retries || 0, retryInterval: retryInterval || 5, timeout: timeout || 30, + httpMethod: httpMethod || 'GET', statusCodes: statusCodes || '200-299', + maxRedirects: maxRedirects !== undefined ? maxRedirects : 5, ignoreSsl: ignoreSsl === true, + upsideDown: upsideDown === true, important: important === true, auth: auth || null, position: position || 0, + group: group || null, quickCommands: quickCommands || null, + }, + }); + + if (target.enabled) { + monitorService.startTargetMonitor({ ...target, _id: target.id }); + } + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ success: true, targetId: target.id, target: { ...target, _id: target.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/targets/positions', async (req, res) => { + try { + const prisma = getPrisma(); + const { positions } = req.body; + + if (!Array.isArray(positions)) { + return res.status(400).json({ success: false, error: 'Positions must be an array' }); + } + + const cacheService = require('../services/cacheService'); + cacheService.invalidateCollection('targets'); + cacheService.invalidateCollection('public-all'); + + for (const { targetId, position } of positions) { + await prisma.target.update({ + where: { id: String(targetId).trim() }, + data: { position: position || 0 }, + }); + } + + res.json({ success: true, message: 'Positions updated' }); + } catch (error) { + console.error('Error updating positions:', error); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/targets/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + const existingTarget = await prisma.target.findUnique({ where: { id: targetId } }); + if (!existingTarget) return res.status(404).json({ success: false, error: 'Target not found' }); + const { enabled, ...updateData } = req.body; + + delete updateData.id; + delete updateData._id; + + if (updateData.protocol) updateData.protocol = updateData.protocol.toUpperCase(); + + // Keep the admin and API target contracts aligned and avoid passing + // arbitrary request properties to Prisma. + const allowedFields = [ + 'name', 'host', 'port', 'protocol', 'path', 'interval', 'publicVisible', + 'publicShowDetails', 'publicShowStatus', 'publicShowAppLink', 'appUrl', + 'appIcon', 'retries', 'retryInterval', 'timeout', 'httpMethod', + 'statusCodes', 'maxRedirects', 'ignoreSsl', 'upsideDown', 'important', + 'auth', 'position', 'group', 'quickCommands', 'description', 'tier', 'linkPublic', + ]; + Object.keys(updateData).forEach((key) => { + if (!allowedFields.includes(key)) delete updateData[key]; + }); + + if (enabled !== undefined) updateData.enabled = enabled === true; + const updatedTarget = await prisma.target.update({ where: { id: targetId }, data: updateData }); + + // Restart only when ping behavior changed. Metadata/visibility edits must + // keep an active outage timer intact, otherwise saving a monitor at minute + // four would silently postpone its sustained-outage notification. + const monitorConfigFields = [ + 'host', 'port', 'protocol', 'path', 'interval', 'retries', 'retryInterval', + 'timeout', 'httpMethod', 'statusCodes', 'maxRedirects', 'ignoreSsl', + 'upsideDown', 'auth', + ]; + const valuesEqual = (left, right) => { + if (left === right || (left == null && right == null)) return true; + return JSON.stringify(left) === JSON.stringify(right); + }; + const requiresRestart = monitorConfigFields.some(field => ( + Object.prototype.hasOwnProperty.call(updateData, field) + && !valuesEqual(updateData[field], existingTarget[field]) + )); + const isActive = monitorService.getActiveMonitors().includes(targetId); + + if (requiresRestart || (!updatedTarget.enabled && isActive)) { + monitorService.stopTargetMonitor(targetId); + if (updatedTarget.enabled) monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id }); + } else if (updatedTarget.enabled && !isActive) { + monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id }); + } else { + monitorService.updateTargetReference({ ...updatedTarget, _id: updatedTarget.id }); + } + + require('../services/cacheService').invalidateCollection('public-all'); + res.json({ success: true, message: 'Target updated' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.delete('/api/targets/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + + monitorService.stopTargetMonitor(targetId); + + // Manually delete related data to avoid foreign key constraint issues + await prisma.pingResult.deleteMany({ where: { targetId } }); + await prisma.alert.deleteMany({ where: { targetId } }); + await prisma.statistic.deleteMany({ where: { targetId } }); + await prisma.action.deleteMany({ where: { targetId } }); + + // Now delete the target + await prisma.target.delete({ where: { id: targetId } }); + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ success: true, message: 'Target deleted' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/targets/:id/statistics', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + + const target = await prisma.target.findUnique({ where: { id: targetId } }); + if (!target) return res.status(404).json({ success: false, error: 'Target not found' }); + + const targetWithStatus = { + ...target, _id: target.id, + currentStatus: monitorService.getTargetStatus(targetId), + }; + + const period = req.query.period || '24h'; + let startDateObj = new Date(); + let endDateObj = new Date(); + let intervalMinutes = 30; + let maxPoints = 48; + + if (period === '1h') { + startDateObj.setHours(startDateObj.getHours() - 1); + intervalMinutes = 1; + maxPoints = 60; + } else if (period === '24h') { + startDateObj.setHours(startDateObj.getHours() - 24); + intervalMinutes = 30; + maxPoints = 48; + } else if (period === '7d') { + startDateObj.setDate(startDateObj.getDate() - 7); + intervalMinutes = 180; + maxPoints = 56; + } else if (period === '30d') { + startDateObj.setDate(startDateObj.getDate() - 30); + intervalMinutes = 720; + maxPoints = 60; + } else if (period === 'all' || period === 'ALL') { + // For ALL period, use daily statistics (much more efficient) + const dailyStats = await prisma.statistic.findMany({ + where: { targetId }, + orderBy: { date: 'asc' }, + select: { + date: true, + totalPings: true, + successfulPings: true, + avgResponseTime: true, + }, + }); + + const stats = dailyStats.map(s => ({ + date: s.date.toISOString(), + totalPings: s.totalPings || 0, + successfulPings: s.successfulPings || 0, + failedPings: (s.totalPings || 0) - (s.successfulPings || 0), + uptime: s.totalPings > 0 ? ((s.successfulPings / s.totalPings) * 100) : 0, + avgResponseTime: s.avgResponseTime || 0, + })); + + // Get uptime data using aggregation + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + + const [uptime24h, uptime30d] = await Promise.all([ + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime24hStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime30dStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + ]); + + const totalPings24h = uptime24h._sum.totalPings || 0; + const successfulPings24h = uptime24h._sum.successfulPings || 0; + const totalPings30d = uptime30d._sum.totalPings || 0; + const successfulPings30d = uptime30d._sum.successfulPings || 0; + + return res.json({ + success: true, + target: targetWithStatus, + statistics: stats, + uptime: { + '24h': { + uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0, + totalPings: totalPings24h, + successfulPings: successfulPings24h, + failedPings: totalPings24h - successfulPings24h, + }, + '30d': { + uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0, + totalPings: totalPings30d, + successfulPings: successfulPings30d, + failedPings: totalPings30d - successfulPings30d, + }, + }, + }); + } + + const intervalSeconds = intervalMinutes * 60; + const startEpoch = Math.floor(startDateObj.getTime() / 1000); + const endEpoch = Math.floor(endDateObj.getTime() / 1000); + + const result = await prisma.$queryRaw` + WITH time_buckets AS ( + -- Keep the database join in UTC while returning an absolute instant + -- for browser-local rendering. + SELECT + to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start, + to_timestamp(bucket_epoch) AS bucket_time + FROM generate_series(${startEpoch}::bigint, ${endEpoch}::bigint, ${intervalSeconds}::bigint) as bucket_epoch + ORDER BY bucket_epoch + LIMIT ${maxPoints} + ) + SELECT + -- Keep the value as a timestamptz; browsers render the UTC instant in + -- each client's own local timezone. + time_buckets.bucket_time as date, + COALESCE(COUNT(pr."_id"), 0)::integer as "totalPings", + COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer as "successfulPings", + COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) as "avgResponseTime" + FROM time_buckets + LEFT JOIN "pingResults" pr ON + pr."targetId" = ${targetId} + AND pr.timestamp >= time_buckets.bucket_start + AND pr.timestamp < (time_buckets.bucket_start + (${intervalSeconds} || ' seconds')::interval) + GROUP BY time_buckets.bucket_start, time_buckets.bucket_time + ORDER BY time_buckets.bucket_time ASC + `; + + const stats = result.map(r => ({ + date: new Date(r.date).toISOString(), + totalPings: Number(r.totalPings) || 0, + successfulPings: Number(r.successfulPings) || 0, + failedPings: (Number(r.totalPings) || 0) - (Number(r.successfulPings) || 0), + uptime: r.totalPings > 0 ? ((r.successfulPings / r.totalPings) * 100) : 0, + avgResponseTime: Number(r.avgResponseTime) || 0, + })); + + // Get uptime data using aggregation (much faster) + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + + // Use aggregation queries instead of fetching all records + const [uptime24h, uptime30d] = await Promise.all([ + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime24hStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime30dStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + ]); + + const totalPings24h = uptime24h._sum.totalPings || 0; + const successfulPings24h = uptime24h._sum.successfulPings || 0; + const totalPings30d = uptime30d._sum.totalPings || 0; + const successfulPings30d = uptime30d._sum.successfulPings || 0; + + res.json({ + success: true, + target: targetWithStatus, + statistics: stats, + uptime: { + '24h': { + uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0, + totalPings: totalPings24h, + successfulPings: successfulPings24h, + failedPings: totalPings24h - successfulPings24h, + }, + '30d': { + uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0, + totalPings: totalPings30d, + successfulPings: successfulPings30d, + failedPings: totalPings30d - successfulPings30d, + }, + }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/targets/:id/uptime', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + const days = parseInt(req.query.days) || 30; + + const startDate = new Date(); + startDate.setDate(startDate.getDate() - days); + + const stats = await prisma.statistic.findMany({ + where: { targetId, date: { gte: startDate } }, + orderBy: { date: 'asc' }, + }); + + let totalPings = 0, successfulPings = 0; + stats.forEach(stat => { + totalPings += stat.totalPings || 0; + successfulPings += stat.successfulPings || 0; + }); + + res.json({ + success: true, + uptime: totalPings > 0 ? (successfulPings / totalPings) * 100 : 0, + totalPings, + successfulPings, + failedPings: totalPings - successfulPings, + dailyStats: stats.map(s => ({ ...s, _id: s.id })), + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/targets/:id/test', async (req, res) => { + const timeout = setTimeout(() => { + if (!res.headersSent) res.status(504).json({ success: false, error: 'Test timeout' }); + }, 60000); + + try { + const prisma = getPrisma(); + const target = await prisma.target.findUnique({ where: { id: req.params.id } }); + if (!target) { + clearTimeout(timeout); + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + const testTarget = { ...target, ...req.body, _id: target.id }; + const pingService = require('../services/pingService'); + const result = await pingService.ping(testTarget); + + clearTimeout(timeout); + + let pingSuccess = result.success; + if (testTarget.upsideDown === true) pingSuccess = !pingSuccess; + monitorService.setTargetStatus(target.id, pingSuccess ? 'up' : 'down'); + + if (!res.headersSent) res.json({ success: result.success, result }); + } catch (error) { + clearTimeout(timeout); + if (!res.headersSent) res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/cache/clear', async (req, res) => { + try { + const cacheService = require('../services/cacheService'); + cacheService.clear(); + res.json({ success: true, message: 'Cache cleared' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ POSTS ============ +router.get('/api/posts', async (req, res) => { + try { + const prisma = getPrisma(); + const posts = await prisma.post.findMany({ orderBy: { createdAt: 'desc' } }); + res.json({ success: true, posts: posts.map(p => ({ ...p, _id: p.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.get('/api/posts/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const post = await prisma.post.findUnique({ where: { id: req.params.id } }); + if (!post) return res.status(404).json({ success: false, error: 'Post not found' }); + res.json({ success: true, post: { ...post, _id: post.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/posts', async (req, res) => { + try { + const { title, content, published } = req.body; + if (!title || !content) return res.status(400).json({ success: false, error: 'Title and content are required' }); + + const prisma = getPrisma(); + const post = await prisma.post.create({ + data: { title, content, published: published !== false }, + }); + + res.json({ success: true, post: { ...post, _id: post.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/posts/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const { title, content, published } = req.body; + const updateData = {}; + if (title !== undefined) updateData.title = title; + if (content !== undefined) updateData.content = content; + if (published !== undefined) updateData.published = published === true; + + await prisma.post.update({ where: { id: req.params.id }, data: updateData }); + res.json({ success: true, message: 'Post updated' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Post not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.delete('/api/posts/:id', async (req, res) => { + try { + const prisma = getPrisma(); + await prisma.post.delete({ where: { id: req.params.id } }); + res.json({ success: true, message: 'Post deleted' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Post not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ DATA MANAGEMENT ============ +router.post('/api/clear-ping-data', async (req, res) => { + try { + const prisma = getPrisma(); + const pingResults = await prisma.pingResult.deleteMany({}); + const statistics = await prisma.statistic.deleteMany({}); + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ + success: true, + message: 'All ping data cleared', + details: { pingResults: pingResults.count, statistics: statistics.count }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Clear ping data for specific monitor +router.post('/api/targets/:id/clear-ping-data', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + + // Verify target exists + const target = await prisma.target.findUnique({ where: { id: targetId } }); + if (!target) { + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + // Clear pingResults for this target + const pingResults = await prisma.pingResult.deleteMany({ where: { targetId: targetId } }); + + // Clear statistics for this target + const statistics = await prisma.statistic.deleteMany({ where: { targetId: targetId } }); + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ + success: true, + message: `Ping data cleared for ${target.name}`, + details: { pingResults: pingResults.count, statistics: statistics.count }, + }); + } catch (error) { + console.error('Error clearing ping data for target:', error); + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ ADMIN SETTINGS ============ +router.get('/api/admin-settings', async (req, res) => { + try { + const prisma = getPrisma(); + let settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + + if (!settings) { + settings = { id: 'settings', _id: 'settings', sessionDurationDays: 30, dataRetentionDays: 30, debugLogging: false }; + } else { + settings = { ...settings, _id: settings.id }; + } + + // Get database size + let dbSize = 0; + try { + const result = await prisma.$queryRaw`SELECT pg_database_size(current_database()) as size`; + dbSize = Number(result[0]?.size) || 0; + } catch (dbSizeError) { + console.error('Error getting database size:', dbSizeError.message); + } + + res.json({ success: true, settings, dbSize }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/admin-settings', async (req, res) => { + try { + const prisma = getPrisma(); + const { sessionDurationDays, dataRetentionDays, debugLogging } = req.body; + + const updateData = {}; + if (sessionDurationDays !== undefined) updateData.sessionDurationDays = parseInt(sessionDurationDays, 10); + if (dataRetentionDays !== undefined) updateData.dataRetentionDays = parseInt(dataRetentionDays, 10); + if (debugLogging !== undefined) updateData.debugLogging = debugLogging === true || debugLogging === 'true'; + + await prisma.adminSettings.upsert({ + where: { id: 'settings' }, + update: updateData, + create: { id: 'settings', sessionDurationDays: 30, dataRetentionDays: 30, debugLogging: false, ...updateData }, + }); + + res.json({ success: true, message: 'Admin settings updated' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ PUBLIC UI SETTINGS ============ +router.get('/api/public-ui-settings', async (req, res) => { + try { + const prisma = getPrisma(); + let settings = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } }); + + if (!settings) { + settings = { id: 'settings', _id: 'settings', title: 'Homelab', subtitle: 'System Status & Application Dashboard', customCSS: null }; + } else { + settings = { ...settings, _id: settings.id }; + } + + res.json({ success: true, settings }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/public-ui-settings', async (req, res) => { + try { + const prisma = getPrisma(); + const { title, subtitle, customCSS } = req.body; + + await prisma.publicUISettings.upsert({ + where: { id: 'settings' }, + update: { title: title || 'Homelab', subtitle: subtitle || 'System Status & Application Dashboard', customCSS: customCSS || null }, + create: { id: 'settings', title: title || 'Homelab', subtitle: subtitle || 'System Status & Application Dashboard', customCSS: customCSS || null }, + }); + + res.json({ success: true, message: 'Public UI settings updated' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ NOTIFICATION SETTINGS ============ +router.get('/api/notification-settings', async (req, res) => { + try { + const prisma = getPrisma(); + let settings = await prisma.notificationSettings.findUnique({ where: { id: 'settings' } }); + + if (!settings) { + settings = { + id: 'settings', _id: 'settings', enabled: false, + monitorDownDelayMinutes: 5, + discord: { enabled: false, webhookUrl: null, username: 'LocalPing', avatarUrl: null }, + events: { monitorDown: true, monitorUp: true, incidentCreated: true, incidentUpdated: true }, + }; + } else { + settings = { + ...settings, + _id: settings.id, + monitorDownDelayMinutes: Math.min(1440, Math.max(1, Number.parseInt(settings.monitorDownDelayMinutes, 10) || 5)), + }; + } + + res.json({ success: true, settings }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.put('/api/notification-settings', async (req, res) => { + try { + const prisma = getPrisma(); + const { enabled, discord, events } = req.body; + const currentSettings = req.body.monitorDownDelayMinutes === undefined + ? await prisma.notificationSettings.findUnique({ where: { id: 'settings' } }) + : null; + const parsedDelay = Number.parseInt( + req.body.monitorDownDelayMinutes === undefined + ? (currentSettings?.monitorDownDelayMinutes || 5) + : req.body.monitorDownDelayMinutes, + 10, + ); + if (!Number.isFinite(parsedDelay) || parsedDelay < 1 || parsedDelay > 1440) { + return res.status(400).json({ success: false, error: 'Monitor notification delay must be between 1 and 1,440 minutes' }); + } + + const updateData = {}; + if (enabled !== undefined) updateData.enabled = enabled === true; + if (discord !== undefined) updateData.discord = discord; + if (events !== undefined) updateData.events = events; + updateData.monitorDownDelayMinutes = parsedDelay; + + await prisma.notificationSettings.upsert({ + where: { id: 'settings' }, + update: updateData, + create: { id: 'settings', enabled: false, discord: null, events: null, monitorDownDelayMinutes: 5, ...updateData }, + }); + + const notificationService = require('../services/notificationService'); + notificationService.invalidateCache(); + monitorService.setNotificationDelayMinutes(parsedDelay); + + res.json({ success: true, message: 'Notification settings updated' }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/notification-settings/test', async (req, res) => { + try { + const { provider = 'discord' } = req.body; + const notificationService = require('../services/notificationService'); + const result = await notificationService.testNotification(provider); + + if (result.success) { + res.json({ success: true, message: 'Test notification sent successfully' }); + } else { + res.status(400).json({ success: false, error: result.error || 'Failed to send test notification' }); + } + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// ============ BACKUP/EXPORT ============ +router.post('/api/backup/export', async (req, res) => { + try { + const backupService = require('../services/backupService'); + const exportData = await backupService.exportData(req.body); + res.json({ success: true, data: exportData }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +router.post('/api/backup/import', async (req, res) => { + try { + const backupService = require('../services/backupService'); + const { importData, overwrite } = req.body; + + if (!importData?.data) { + return res.status(400).json({ success: false, error: 'Invalid import data format' }); + } + + const results = await backupService.importData(importData, { overwrite: overwrite === true }); + require('../services/cacheService').clear(); + res.json({ success: true, results }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +module.exports = router; diff --git a/src/routes/api.js b/src/routes/api.js new file mode 100644 index 0000000..47b625c --- /dev/null +++ b/src/routes/api.js @@ -0,0 +1,537 @@ +const express = require('express'); +const router = express.Router(); +const { getPrisma } = require('../config/prisma'); +const { v4: uuidv4 } = require('uuid'); +const monitorService = require('../services/monitorService'); +const pingService = require('../services/pingService'); +const actionService = require('../services/actionService'); +const gatewayService = require('../services/gatewayService'); +const chalk = require('../utils/colors'); +const { validateTargetInput } = require('../middleware/auth'); + +// Get all targets +router.get('/targets', async (req, res) => { + try { + const prisma = getPrisma(); + const targets = await prisma.target.findMany(); + + const targetsWithStatus = targets.map((target) => ({ + ...target, + _id: target.id, + currentStatus: monitorService.getTargetStatus(target.id), + })); + + res.json({ success: true, targets: targetsWithStatus }); + } catch (error) { + console.error(chalk.red('Error fetching targets:'), error.message); + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Get target by ID +router.get('/targets/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const target = await prisma.target.findUnique({ where: { id: req.params.id } }); + + if (!target) { + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + res.json({ + success: true, + target: { ...target, _id: target.id, currentStatus: monitorService.getTargetStatus(target.id) }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Create target +router.post('/targets', validateTargetInput, async (req, res) => { + try { + const prisma = getPrisma(); + const faviconService = require('../services/faviconService'); + + const { + name, host, port, protocol, interval, enabled, publicVisible, + publicShowDetails, publicShowStatus, publicShowAppLink, path, appUrl, appIcon, + retries, retryInterval, timeout, httpMethod, statusCodes, maxRedirects, + ignoreSsl, upsideDown, important, auth, position, group, quickCommands, + } = req.body; + + if (!name || !host || !protocol) { + return res.status(400).json({ success: false, error: 'Missing required fields: name, host, protocol' }); + } + + const protocolLower = protocol.toUpperCase(); + const defaultPort = protocolLower === 'HTTPS' ? 443 : protocolLower === 'HTTP' ? 80 : null; + const targetPort = port || defaultPort; + const targetPath = path || '/'; + const targetUrl = targetPort && targetPort !== defaultPort + ? `${protocolLower.toLowerCase()}://${host}:${targetPort}${targetPath}` + : `${protocolLower.toLowerCase()}://${host}${targetPath}`; + + let fetchedAppIcon = appIcon; + let finalAppUrl = appUrl; + + if ((protocolLower === 'HTTP' || protocolLower === 'HTTPS') && !appIcon) { + try { + let authObj = auth; + if (auth && typeof auth === 'string') { + try { authObj = JSON.parse(auth); } catch (e) { authObj = null; } + } + + const faviconUrl = await faviconService.getFaviconUrlFromHtml(targetUrl, { + timeout: (timeout || 30) * 1000, + maxRedirects: maxRedirects !== undefined ? maxRedirects : 5, + ignoreSsl: ignoreSsl === true, + auth: authObj, + }); + + if (faviconUrl) { + fetchedAppIcon = faviconUrl; + if (!finalAppUrl) finalAppUrl = targetUrl; + } + } catch (error) { + console.error(`Failed to fetch favicon for ${targetUrl}:`, error.message); + } + } + + const target = await prisma.target.create({ + data: { + name, host, port: port || null, protocol: protocol.toUpperCase(), path: path || null, + interval: interval || 60, enabled: enabled !== false, publicVisible: publicVisible !== false, + publicShowDetails: publicShowDetails === true, publicShowStatus: publicShowStatus !== false, + publicShowAppLink: publicShowAppLink !== false, appUrl: finalAppUrl || null, + appIcon: fetchedAppIcon || null, retries: retries !== undefined ? retries : 0, + retryInterval: retryInterval !== undefined ? retryInterval : 5, + timeout: timeout !== undefined ? timeout : 30, httpMethod: httpMethod || 'GET', + statusCodes: statusCodes || '200-299', maxRedirects: maxRedirects !== undefined ? maxRedirects : 5, + ignoreSsl: ignoreSsl === true, upsideDown: upsideDown === true, important: important === true, auth: auth || null, + position: position !== undefined ? position : 0, group: group || null, quickCommands: quickCommands || [], + }, + }); + + if (target.enabled) { + monitorService.startTargetMonitor({ ...target, _id: target.id }); + } + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ success: true, targetId: target.id, target: { ...target, _id: target.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Update target +router.put('/targets/:id', validateTargetInput, async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + const existingTarget = await prisma.target.findUnique({ where: { id: targetId } }); + if (!existingTarget) return res.status(404).json({ success: false, error: 'Target not found' }); + + const { + name, host, port, protocol, interval, enabled, publicVisible, + publicShowDetails, publicShowStatus, publicShowAppLink, path, appUrl, appIcon, + retries, retryInterval, timeout, httpMethod, statusCodes, maxRedirects, + ignoreSsl, upsideDown, important, auth, position, group, quickCommands, + } = req.body; + + const updateData = {}; + if (name !== undefined) updateData.name = name; + if (host !== undefined) updateData.host = host; + if (port !== undefined) updateData.port = port; + if (protocol !== undefined) updateData.protocol = protocol.toUpperCase(); + if (interval !== undefined) updateData.interval = interval; + if (path !== undefined) updateData.path = path; + if (appUrl !== undefined) updateData.appUrl = appUrl; + if (appIcon !== undefined) updateData.appIcon = appIcon; + if (retries !== undefined) updateData.retries = retries; + if (retryInterval !== undefined) updateData.retryInterval = retryInterval; + if (timeout !== undefined) updateData.timeout = timeout; + if (httpMethod !== undefined) updateData.httpMethod = httpMethod; + if (statusCodes !== undefined) updateData.statusCodes = statusCodes; + if (maxRedirects !== undefined) updateData.maxRedirects = maxRedirects; + if (ignoreSsl !== undefined) updateData.ignoreSsl = ignoreSsl === true; + if (upsideDown !== undefined) updateData.upsideDown = upsideDown === true; + if (auth !== undefined) updateData.auth = auth; + if (position !== undefined) updateData.position = position; + if (group !== undefined) updateData.group = group; + if (quickCommands !== undefined) updateData.quickCommands = quickCommands; + if (publicVisible !== undefined) updateData.publicVisible = publicVisible === true; + if (publicShowDetails !== undefined) updateData.publicShowDetails = publicShowDetails === true; + if (publicShowStatus !== undefined) updateData.publicShowStatus = publicShowStatus !== false; + if (publicShowAppLink !== undefined) updateData.publicShowAppLink = publicShowAppLink !== false; + if (important !== undefined) updateData.important = important === true; + + if (enabled !== undefined) updateData.enabled = enabled === true; + const updatedTarget = await prisma.target.update({ where: { id: targetId }, data: updateData }); + + // Restart only when ping behavior changed. Metadata/visibility edits must + // keep an active outage timer intact, otherwise saving a monitor at minute + // four would silently postpone its sustained-outage notification. + const monitorConfigFields = [ + 'host', 'port', 'protocol', 'path', 'interval', 'retries', 'retryInterval', + 'timeout', 'httpMethod', 'statusCodes', 'maxRedirects', 'ignoreSsl', + 'upsideDown', 'auth', + ]; + const valuesEqual = (left, right) => { + if (left === right || (left == null && right == null)) return true; + return JSON.stringify(left) === JSON.stringify(right); + }; + const requiresRestart = monitorConfigFields.some(field => ( + Object.prototype.hasOwnProperty.call(updateData, field) + && !valuesEqual(updateData[field], existingTarget[field]) + )); + const isActive = monitorService.getActiveMonitors().includes(targetId); + + if (requiresRestart || (!updatedTarget.enabled && isActive)) { + monitorService.stopTargetMonitor(targetId); + if (updatedTarget.enabled) monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id }); + } else if (updatedTarget.enabled && !isActive) { + monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id }); + } else { + monitorService.updateTargetReference({ ...updatedTarget, _id: updatedTarget.id }); + } + + require('../services/cacheService').invalidateCollection('public-all'); + res.json({ success: true, message: 'Target updated' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Delete target +router.delete('/targets/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + + monitorService.stopTargetMonitor(targetId); + + // Manually delete related data to avoid foreign key constraint issues + await prisma.pingResult.deleteMany({ where: { targetId } }); + await prisma.alert.deleteMany({ where: { targetId } }); + await prisma.statistic.deleteMany({ where: { targetId } }); + await prisma.action.deleteMany({ where: { targetId } }); + + // Now delete the target + await prisma.target.delete({ where: { id: targetId } }); + require('../services/cacheService').invalidateCollection('public-all'); + + res.json({ success: true, message: 'Target deleted' }); + } catch (error) { + if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' }); + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Get ping results for target +router.get('/targets/:id/results', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + const limit = parseInt(req.query.limit) || 100; + const skip = parseInt(req.query.skip) || 0; + + const results = await prisma.pingResult.findMany({ + where: { targetId }, + orderBy: { timestamp: 'desc' }, + take: limit, + skip: skip, + }); + + const count = await prisma.pingResult.count({ where: { targetId } }); + + res.json({ + success: true, + results: results.map(r => ({ ...r, _id: r.id })), + total: count, + limit, + skip, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Get statistics for target +router.get('/targets/:id/statistics', async (req, res) => { + try { + const prisma = getPrisma(); + const targetId = req.params.id; + const period = req.query.period || '24h'; + + let startDateObj = new Date(); + let endDateObj = new Date(); + let intervalMinutes = 30; + let maxPoints = 48; + + if (period === '1h') { + startDateObj.setHours(startDateObj.getHours() - 1); + intervalMinutes = 1; + maxPoints = 60; + } else if (period === '24h') { + startDateObj.setHours(startDateObj.getHours() - 24); + intervalMinutes = 30; + maxPoints = 48; + } else if (period === '7d') { + startDateObj.setDate(startDateObj.getDate() - 7); + intervalMinutes = 180; + maxPoints = 56; + } else if (period === '30d') { + startDateObj.setDate(startDateObj.getDate() - 30); + intervalMinutes = 720; + maxPoints = 60; + } else if (period === 'all' || period === 'ALL') { + // For ALL period, use daily statistics (much more efficient) + const dailyStats = await prisma.statistic.findMany({ + where: { targetId }, + orderBy: { date: 'asc' }, + select: { + date: true, + totalPings: true, + successfulPings: true, + avgResponseTime: true, + }, + }); + + const stats = dailyStats.map(s => ({ + date: s.date.toISOString(), + totalPings: s.totalPings || 0, + successfulPings: s.successfulPings || 0, + failedPings: (s.totalPings || 0) - (s.successfulPings || 0), + uptime: s.totalPings > 0 ? parseFloat(((s.successfulPings / s.totalPings) * 100).toFixed(2)) : 0, + avgResponseTime: s.avgResponseTime || 0, + })); + + // Get uptime data using aggregation + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + + const [uptime24h, uptime30d] = await Promise.all([ + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime24hStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime30dStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + ]); + + const totalPings24h = uptime24h._sum.totalPings || 0; + const successfulPings24h = uptime24h._sum.successfulPings || 0; + const totalPings30d = uptime30d._sum.totalPings || 0; + const successfulPings30d = uptime30d._sum.successfulPings || 0; + + return res.json({ + success: true, + statistics: stats, + uptime: { + '24h': { + uptime: totalPings24h > 0 ? parseFloat(((successfulPings24h / totalPings24h) * 100).toFixed(2)) : 0, + totalPings: totalPings24h, + successfulPings: successfulPings24h, + failedPings: totalPings24h - successfulPings24h, + }, + '30d': { + uptime: totalPings30d > 0 ? parseFloat(((successfulPings30d / totalPings30d) * 100).toFixed(2)) : 0, + totalPings: totalPings30d, + successfulPings: successfulPings30d, + failedPings: totalPings30d - successfulPings30d, + }, + }, + }); + } + + const intervalSeconds = intervalMinutes * 60; + const startEpoch = Math.floor(startDateObj.getTime() / 1000); + const endEpoch = Math.floor(endDateObj.getTime() / 1000); + + const result = await prisma.$queryRaw` + WITH time_buckets AS ( + -- Keep the database join in UTC while returning an absolute instant + -- for browser-local rendering. + SELECT + to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start, + to_timestamp(bucket_epoch) AS bucket_time + FROM generate_series(${startEpoch}::bigint, ${endEpoch}::bigint, ${intervalSeconds}::bigint) as bucket_epoch + ORDER BY bucket_epoch + LIMIT ${maxPoints} + ) + SELECT + -- Keep the value as a timestamptz; browsers render the UTC instant in + -- each client's own local timezone. + time_buckets.bucket_time as date, + COALESCE(COUNT(pr."_id"), 0)::integer as "totalPings", + COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer as "successfulPings", + COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) as "avgResponseTime" + FROM time_buckets + LEFT JOIN "pingResults" pr ON + pr."targetId" = ${targetId} + AND pr.timestamp >= time_buckets.bucket_start + AND pr.timestamp < (time_buckets.bucket_start + (${intervalSeconds} || ' seconds')::interval) + GROUP BY time_buckets.bucket_start, time_buckets.bucket_time + ORDER BY time_buckets.bucket_time ASC + `; + + const stats = result.map(r => ({ + date: new Date(r.date).toISOString(), + totalPings: Number(r.totalPings) || 0, + successfulPings: Number(r.successfulPings) || 0, + failedPings: (Number(r.totalPings) || 0) - (Number(r.successfulPings) || 0), + uptime: r.totalPings > 0 ? ((r.successfulPings / r.totalPings) * 100) : 0, + avgResponseTime: Number(r.avgResponseTime) || 0, + })); + + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + + // Use aggregation queries instead of fetching all records + const [uptime24h, uptime30d] = await Promise.all([ + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime24hStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + prisma.statistic.aggregate({ + where: { targetId, date: { gte: uptime30dStart } }, + _sum: { totalPings: true, successfulPings: true }, + }), + ]); + + const totalPings24h = uptime24h._sum.totalPings || 0; + const successfulPings24h = uptime24h._sum.successfulPings || 0; + const totalPings30d = uptime30d._sum.totalPings || 0; + const successfulPings30d = uptime30d._sum.successfulPings || 0; + + res.json({ + success: true, + statistics: stats, + uptime: { + '24h': { + uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0, + totalPings: totalPings24h, + successfulPings: successfulPings24h, + failedPings: totalPings24h - successfulPings24h, + }, + '30d': { + uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0, + totalPings: totalPings30d, + successfulPings: successfulPings30d, + failedPings: totalPings30d - successfulPings30d, + }, + }, + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Get alerts +router.get('/alerts', async (req, res) => { + try { + const prisma = getPrisma(); + const limit = parseInt(req.query.limit) || 50; + const targetId = req.query.targetId || null; + + const where = targetId ? { targetId } : {}; + const alerts = await prisma.alert.findMany({ + where, + orderBy: { timestamp: 'desc' }, + take: limit, + }); + + res.json({ success: true, alerts: alerts.map(a => ({ ...a, _id: a.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Test ping a target +router.post('/targets/:id/test', async (req, res) => { + const timeout = setTimeout(() => { + if (!res.headersSent) res.status(504).json({ success: false, error: 'Test timeout' }); + }, 60000); + + try { + const prisma = getPrisma(); + const target = await prisma.target.findUnique({ where: { id: req.params.id } }); + + if (!target) { + clearTimeout(timeout); + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + const result = await pingService.ping({ ...target, _id: target.id }); + clearTimeout(timeout); + + if (!res.headersSent) res.json({ success: result.success, result }); + } catch (error) { + clearTimeout(timeout); + if (!res.headersSent) res.status(500).json({ success: false, error: error.message }); + } +}); + +// Execute action +router.post('/actions/:id/execute', async (req, res) => { + try { + const prisma = getPrisma(); + const action = await prisma.action.findUnique({ where: { id: req.params.id } }); + + if (!action) { + return res.status(404).json({ success: false, error: 'Action not found' }); + } + + const result = await actionService.executeAction(action); + res.json({ success: result.success, result }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Get gateway information +router.get('/gateway', (req, res) => { + const gateways = gatewayService.getAllGateways(); + res.json({ + success: true, + primaryGateway: gatewayService.getPrimaryGateway(), + allGateways: gateways, + }); +}); + +// Get system status +router.get('/status', async (req, res) => { + try { + const prisma = getPrisma(); + + const targetCount = await prisma.target.count(); + const enabledCount = await prisma.target.count({ where: { enabled: true } }); + const recentAlerts = await prisma.alert.findMany({ + orderBy: { timestamp: 'desc' }, + take: 10, + }); + + res.json({ + success: true, + status: { + totalTargets: targetCount, + enabledTargets: enabledCount, + activeMonitors: monitorService.getActiveMonitors().length, + gateway: gatewayService.getPrimaryGateway(), + }, + recentAlerts: recentAlerts.map(a => ({ ...a, _id: a.id })), + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +module.exports = router; diff --git a/src/routes/public.js b/src/routes/public.js new file mode 100644 index 0000000..0303941 --- /dev/null +++ b/src/routes/public.js @@ -0,0 +1,788 @@ +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const { getPrisma } = require('../config/prisma'); +const monitorService = require('../services/monitorService'); +const faviconService = require('../services/faviconService'); + +// The public summary and on-demand graph responses are immutable enough to +// keep for an hour. Live status is still refreshed by `hydrateSummary` on +// every request, so a warm summary never hides a current outage. +const PUBLIC_DATA_CACHE_TTL = 60 * 60 * 1000; +const PUBLIC_DATA_CACHE_MAX_AGE = Math.floor(PUBLIC_DATA_CACHE_TTL / 1000); + +function publicCacheKey(cacheService, type, req, extra = {}) { + return cacheService.generateKey('public-all', { + type, + ...extra, + privileged: isPrivilegedViewer(req), + }); +} + +function setPublicCacheHeaders(res) { + res.set('Cache-Control', `private, max-age=${PUBLIC_DATA_CACHE_MAX_AGE}, stale-while-revalidate=60`); +} + +function isAdminViewer(req) { + return req.session?.adminAuthenticated === true; +} + +/** + * Public routes are mounted before the authenticated `/api` router so the + * browser can use the same `/api/*` paths without an API key. When a caller + * does send an API credential, preserve the REST API contract and let it see + * the complete monitor inventory (including private monitors). In local + * development authentication is intentionally disabled, so the presence of + * an API header is the only useful signal there. + */ +function isApiClient(req) { + const authHeader = req.headers.authorization || ''; + const xApiKey = req.headers['x-api-key'] || ''; + const providedKey = authHeader.replace(/^Bearer\s+/i, '') || xApiKey; + if (!providedKey) return false; + const configuredKey = process.env.ADMIN_API_KEY; + return !configuredKey || providedKey === configuredKey; +} + +function isPrivilegedViewer(req) { + return isAdminViewer(req) || isApiClient(req); +} + +// The public router is mounted before the authenticated API router. Exit this +// router whenever a caller explicitly presents API credentials so valid keys +// reach the protected API implementation and invalid keys receive its 401 +// response instead of being silently downgraded to public data. +router.use('/api', (req, res, next) => { + if (req.headers.authorization || req.headers['x-api-key']) { + return next('router'); + } + return next(); +}); + +function targetVisibilityWhere(req) { + return isPrivilegedViewer(req) ? {} : { enabled: true, publicVisible: true }; +} + +function liveNotificationState(targetId) { + if (typeof monitorService.getNotificationState !== 'function') return {}; + return monitorService.getNotificationState(targetId); +} + +function publicTargetStatus(target, req) { + const adminViewer = isPrivilegedViewer(req); + const status = monitorService.getTargetStatus(target.id); + const showDetails = adminViewer || target.publicShowDetails === true; + const result = { + _id: target.id, + name: target.name, + currentStatus: status, + isUp: status === 'up', + isDown: status === 'down', + notification: liveNotificationState(target.id), + publicShowDetails: showDetails, + publicShowStatus: adminViewer || target.publicShowStatus !== false, + publicShowAppLink: adminViewer || target.publicShowAppLink !== false, + }; + + if (target.enabled !== undefined) result.enabled = target.enabled; + if (target.publicVisible !== undefined) result.publicVisible = target.publicVisible; + if (showDetails) { + result.host = target.host; + result.protocol = target.protocol; + if (target.port !== undefined) result.port = target.port; + } + if (target.appUrl && (adminViewer || target.publicShowAppLink !== false)) result.appUrl = target.appUrl; + if (target.appIcon) result.appIcon = target.appIcon; + if (target.position !== undefined) result.position = target.position || 0; + if (target.group) result.group = target.group; + if (target.quickCommands && (adminViewer || target.publicShowAppLink !== false)) result.quickCommands = target.quickCommands; + return result; +} + +function hydrateSummary(cached, req) { + const targets = cached.targets.map((target) => { + const currentStatus = monitorService.getTargetStatus(target._id); + return { + ...target, + currentStatus, + isUp: currentStatus === 'up', + isDown: currentStatus === 'down', + notification: liveNotificationState(target._id), + }; + }); + const upTargets = targets.filter((target) => target.isUp).length; + const downTargets = targets.filter((target) => target.isDown).length; + const overallStatus = downTargets === 0 ? 'operational' : downTargets === targets.length ? 'down' : 'degraded'; + return { + success: true, + status: { overallStatus, upTargets, downTargets, totalTargets: targets.length }, + targets, + viewer: { isAdmin: isAdminViewer(req), isApiClient: isApiClient(req) }, + timestamp: new Date(), + }; +} + +async function renderPublicPage(req, res, initialPage) { + try { + const prisma = getPrisma(); + const settings = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } }) || {}; + return res.render('public/index', { + title: settings.title || 'Homelab', + subtitle: settings.subtitle || 'System Status & Application Dashboard', + customCSS: settings.customCSS || '', + initialPage, + isAdminViewer: isAdminViewer(req), + }); + } catch (error) { + return res.render('public/index', { + title: 'Homelab', + subtitle: 'System Status & Application Dashboard', + customCSS: '', + initialPage, + isAdminViewer: isAdminViewer(req), + }); + } +} + +// Public status page +router.get('/', async (req, res) => { + return renderPublicPage(req, res, 'home'); +}); + +router.get('/uptime', (req, res) => renderPublicPage(req, res, 'status')); +router.get('/blog', (req, res) => renderPublicPage(req, res, 'blog')); + +// Public API - Get all targets (read-only) +router.get('/api/targets', async (req, res) => { + try { + const prisma = getPrisma(); + const targets = await prisma.target.findMany({ + where: targetVisibilityWhere(req), + }); + + const targetsWithStatus = targets.map((target) => publicTargetStatus(target, req)); + + res.json({ success: true, targets: targetsWithStatus }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get target statistics (read-only) +router.get('/api/targets/:id/statistics', async (req, res) => { + try { + const prisma = getPrisma(); + const cacheService = require('../services/cacheService'); + const targetId = req.params.id; + // Support both 'period' and 'days' query parameters + const period = req.query.period || (req.query.days ? `${req.query.days}d` : '24h'); + const days = parseInt(req.query.days) || null; + const cacheKey = publicCacheKey(cacheService, 'statistics', req, { targetId, period, days }); + const cachedStatistics = cacheService.get(cacheKey); + if (cachedStatistics) { + setPublicCacheHeaders(res); + return res.json(cachedStatistics); + } + + const target = await prisma.target.findFirst({ + where: { id: targetId, ...targetVisibilityWhere(req) }, + select: { id: true, name: true }, + }); + + if (!target) { + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + let startDateObj = new Date(); + let endDateObj = new Date(); + let intervalMinutes = 30; + let maxPoints = 48; + let useDailyStats = false; + + // Handle 'days' parameter for daily statistics + if (days !== null) { + if (days === 1) { + startDateObj.setHours(startDateObj.getHours() - 24); + intervalMinutes = 30; + maxPoints = 48; + useDailyStats = false; + } else if (days === 30) { + // For 30 days, use daily statistics table instead of raw ping results + useDailyStats = true; + startDateObj.setDate(startDateObj.getDate() - 30); + } else { + startDateObj.setDate(startDateObj.getDate() - days); + intervalMinutes = Math.max(60, Math.floor((days * 24 * 60) / 60)); + maxPoints = 60; + useDailyStats = days >= 7; + } + } else if (period === '1h') { + startDateObj.setHours(startDateObj.getHours() - 1); + intervalMinutes = 1; + maxPoints = 60; + } else if (period === '24h') { + startDateObj.setHours(startDateObj.getHours() - 24); + intervalMinutes = 30; + maxPoints = 48; + } else if (period === '7d') { + startDateObj.setDate(startDateObj.getDate() - 7); + intervalMinutes = 180; + maxPoints = 56; + } else if (period === '30d') { + startDateObj.setDate(startDateObj.getDate() - 30); + useDailyStats = true; + } else if (period === 'all' || period === 'ALL') { + // For ALL period, use daily statistics (much more efficient) + useDailyStats = true; + startDateObj = new Date(0); // Start from beginning + } + + let stats = []; + + if (useDailyStats) { + // Use pre-aggregated daily statistics for better performance + const dailyStats = await prisma.statistic.findMany({ + where: { + targetId, + date: { gte: startDateObj }, + }, + orderBy: { date: 'asc' }, + select: { + date: true, + totalPings: true, + successfulPings: true, + avgResponseTime: true, + }, + }); + + stats = dailyStats.map(s => ({ + date: s.date.toISOString(), + totalPings: s.totalPings || 0, + successfulPings: s.successfulPings || 0, + failedPings: (s.totalPings || 0) - (s.successfulPings || 0), + uptime: s.totalPings > 0 ? ((s.successfulPings / s.totalPings) * 100) : 0, + avgResponseTime: s.avgResponseTime || 0, + })); + } else { + // Use optimized raw query for shorter time periods + const intervalSeconds = intervalMinutes * 60; + const startEpoch = Math.floor(startDateObj.getTime() / 1000); + const endEpoch = Math.floor(endDateObj.getTime() / 1000); + + // Optimized query with proper index usage + const result = await prisma.$queryRaw` + WITH time_buckets AS ( + -- Prisma DateTime columns are stored as UTC timestamp values without + -- a timezone. Keep the join in UTC, but return a timestamptz instant + -- so browsers can render it in their own local timezone. + SELECT + to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start, + to_timestamp(bucket_epoch) AS bucket_time + FROM generate_series(${startEpoch}::bigint, ${endEpoch}::bigint, ${intervalSeconds}::bigint) as bucket_epoch + ORDER BY bucket_epoch + LIMIT ${maxPoints} + ) + SELECT + -- Keep the value as a timestamptz; browsers render the UTC instant in + -- each client's own local timezone. + time_buckets.bucket_time as date, + COALESCE(COUNT(pr."_id"), 0)::integer as "totalPings", + COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer as "successfulPings", + COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) as "avgResponseTime" + FROM time_buckets + LEFT JOIN "pingResults" pr ON + pr."targetId" = ${targetId} + AND pr.timestamp >= time_buckets.bucket_start + AND pr.timestamp < (time_buckets.bucket_start + (${intervalSeconds} || ' seconds')::interval) + GROUP BY time_buckets.bucket_start, time_buckets.bucket_time + ORDER BY time_buckets.bucket_time ASC + `; + + stats = result.map(r => ({ + date: new Date(r.date).toISOString(), + totalPings: Number(r.totalPings) || 0, + successfulPings: Number(r.successfulPings) || 0, + failedPings: (Number(r.totalPings) || 0) - (Number(r.successfulPings) || 0), + uptime: r.totalPings > 0 ? ((r.successfulPings / r.totalPings) * 100) : 0, + avgResponseTime: Number(r.avgResponseTime) || 0, + })); + } + + // Get uptime summary using aggregated statistics (much faster) + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + + // Use single aggregation query instead of fetching all records + const uptime24h = await prisma.statistic.aggregate({ + where: { + targetId, + date: { gte: uptime24hStart }, + }, + _sum: { + totalPings: true, + successfulPings: true, + }, + }); + + const uptime30d = await prisma.statistic.aggregate({ + where: { + targetId, + date: { gte: uptime30dStart }, + }, + _sum: { + totalPings: true, + successfulPings: true, + }, + }); + + const totalPings24h = uptime24h._sum.totalPings || 0; + const successfulPings24h = uptime24h._sum.successfulPings || 0; + const totalPings30d = uptime30d._sum.totalPings || 0; + const successfulPings30d = uptime30d._sum.successfulPings || 0; + + const response = { + success: true, + statistics: stats, + uptime: { + '24h': { + uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0, + totalPings: totalPings24h, + successfulPings: successfulPings24h, + failedPings: totalPings24h - successfulPings24h, + }, + '30d': { + uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0, + totalPings: totalPings30d, + successfulPings: successfulPings30d, + failedPings: totalPings30d - successfulPings30d, + }, + }, + target: { + _id: target.id, + name: target.name, + }, + }; + cacheService.set(cacheKey, response, PUBLIC_DATA_CACHE_TTL); + setPublicCacheHeaders(res); + res.json(response); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get target uptime summary (read-only) +router.get('/api/targets/:id/uptime', async (req, res) => { + try { + const prisma = getPrisma(); + const cacheService = require('../services/cacheService'); + const targetId = req.params.id; + const days = parseInt(req.query.days) || 30; + const cacheKey = publicCacheKey(cacheService, 'uptime', req, { targetId, days }); + const cachedUptime = cacheService.get(cacheKey); + if (cachedUptime) { + setPublicCacheHeaders(res); + return res.json(cachedUptime); + } + + const target = await prisma.target.findFirst({ + where: { id: targetId, ...targetVisibilityWhere(req) }, + }); + + if (!target) { + return res.status(404).json({ success: false, error: 'Target not found' }); + } + + const startDate = new Date(); + startDate.setDate(startDate.getDate() - days); + + // Use aggregation instead of fetching all records + const stats = await prisma.statistic.aggregate({ + where: { targetId, date: { gte: startDate } }, + _sum: { totalPings: true, successfulPings: true }, + }); + + const totalPings = stats._sum.totalPings || 0; + const successfulPings = stats._sum.successfulPings || 0; + const uptime = totalPings > 0 ? ((successfulPings / totalPings) * 100).toFixed(2) : 0; + + const response = { + success: true, + targetName: target.name, + uptime: parseFloat(uptime), + daysTracked: days, + totalPings, + successfulPings, + failedPings: totalPings - successfulPings, + }; + cacheService.set(cacheKey, response, PUBLIC_DATA_CACHE_TTL); + setPublicCacheHeaders(res); + res.json(response); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get all data for public UI (consolidated endpoint) +router.get('/api/public/all', async (req, res) => { + try { + const prisma = getPrisma(); + const cacheService = require('../services/cacheService'); + const cacheKey = publicCacheKey(cacheService, 'summary', req); + const cachedSummary = cacheService.get(cacheKey); + if (cachedSummary) { + setPublicCacheHeaders(res); + return res.json(hydrateSummary(cachedSummary, req)); + } + + // Get all visible targets + const targets = await prisma.target.findMany({ + where: targetVisibilityWhere(req), + select: { + id: true, + name: true, + host: true, + protocol: true, + appUrl: true, + appIcon: true, + position: true, + group: true, + quickCommands: true, + publicShowDetails: true, + publicShowStatus: true, + publicShowAppLink: true, + enabled: true, + publicVisible: true, + }, + orderBy: { position: 'asc' }, + }); + + // Calculate date ranges + const uptime24hStart = new Date(); + uptime24hStart.setDate(uptime24hStart.getDate() - 1); + const uptime30dStart = new Date(); + uptime30dStart.setDate(uptime30dStart.getDate() - 30); + // Mini graphs use one point per hour for the latest 24 hours. Align the + // window to a bucket boundary so every monitor receives the same compact + // timeline from one batched query. + const miniBucketSeconds = 60 * 60; + // Date.now() is milliseconds while PostgreSQL's to_timestamp and the + // generated bucket values use Unix seconds. Convert before aligning to a + // bucket boundary; passing milliseconds here creates dates thousands of + // years in the future and causes `Invalid time value` during serialization. + const miniEndEpoch = Math.floor(Date.now() / 1000 / miniBucketSeconds) * miniBucketSeconds; + const miniStartEpoch = miniEndEpoch - (23 * miniBucketSeconds); + + // Get uptime statistics for all targets in parallel using aggregation + const targetIds = targets.map(t => t.id); + + if (targetIds.length === 0) { + const emptySummary = { + success: true, + status: { + overallStatus: 'operational', + upTargets: 0, + downTargets: 0, + totalTargets: 0, + }, + targets: [], + }; + cacheService.set(cacheKey, emptySummary, PUBLIC_DATA_CACHE_TTL); + setPublicCacheHeaders(res); + return res.json(hydrateSummary(emptySummary, req)); + } + + // Use raw SQL for efficient aggregation across all targets + const [uptime24hData, uptime30dData, miniStatsData] = await Promise.all([ + // 24h uptime aggregation for all targets + prisma.$queryRaw` + SELECT + "targetId", + COALESCE(SUM("totalPings"), 0)::bigint as "totalPings", + COALESCE(SUM("successfulPings"), 0)::bigint as "successfulPings" + FROM statistics + WHERE "targetId" = ANY(${targetIds}::text[]) + AND date >= ${uptime24hStart} + GROUP BY "targetId" + `, + // 30d uptime aggregation for all targets + prisma.$queryRaw` + SELECT + "targetId", + COALESCE(SUM("totalPings"), 0)::bigint as "totalPings", + COALESCE(SUM("successfulPings"), 0)::bigint as "successfulPings" + FROM statistics + WHERE "targetId" = ANY(${targetIds}::text[]) + AND date >= ${uptime30dStart} + GROUP BY "targetId" + `, + // Raw ping buckets power the compact 24-hour graph shown for every + // service. Cross joining the small 24-bucket timeline with the target + // IDs keeps this to one indexed query instead of one request per row. + prisma.$queryRaw` + WITH time_buckets AS ( + SELECT + to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start, + to_timestamp(bucket_epoch) AS bucket_time + FROM generate_series( + ${miniStartEpoch}::bigint, + ${miniEndEpoch}::bigint, + ${miniBucketSeconds}::bigint + ) AS bucket_epoch + ) + SELECT + target_ids."targetId", + time_buckets.bucket_time AS date, + COALESCE(COUNT(pr."_id"), 0)::integer AS "totalPings", + COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer AS "successfulPings", + COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) AS "avgResponseTime" + FROM time_buckets + CROSS JOIN unnest(${targetIds}::text[]) AS target_ids("targetId") + LEFT JOIN "pingResults" pr ON + pr."targetId" = target_ids."targetId" + AND pr.timestamp >= time_buckets.bucket_start + AND pr.timestamp < (time_buckets.bucket_start + interval '1 hour') + GROUP BY target_ids."targetId", time_buckets.bucket_start, time_buckets.bucket_time + ORDER BY target_ids."targetId", time_buckets.bucket_time ASC + `, + ]); + + // Create lookup maps for fast access + const uptime24hMap = new Map(); + uptime24hData.forEach(item => { + const total = Number(item.totalPings) || 0; + const successful = Number(item.successfulPings) || 0; + const uptime = total > 0 ? (successful / total) * 100 : 0; + uptime24hMap.set(item.targetId, { + uptime: parseFloat(uptime.toFixed(2)), + totalPings: total, + successfulPings: successful, + failedPings: total - successful, + }); + }); + + const uptime30dMap = new Map(); + uptime30dData.forEach(item => { + const total = Number(item.totalPings) || 0; + const successful = Number(item.successfulPings) || 0; + const uptime = total > 0 ? (successful / total) * 100 : 0; + uptime30dMap.set(item.targetId, { + uptime: parseFloat(uptime.toFixed(2)), + totalPings: total, + successfulPings: successful, + failedPings: total - successful, + }); + }); + + // Group the fixed 24-hour buckets by target so the browser can draw all + // rows from the consolidated response without additional network calls. + const miniStatsMap = new Map(); + miniStatsData.forEach(stat => { + if (!miniStatsMap.has(stat.targetId)) { + miniStatsMap.set(stat.targetId, []); + } + miniStatsMap.get(stat.targetId).push({ + date: new Date(stat.date).toISOString(), + totalPings: Number(stat.totalPings) || 0, + successfulPings: Number(stat.successfulPings) || 0, + failedPings: (Number(stat.totalPings) || 0) - (Number(stat.successfulPings) || 0), + avgResponseTime: Number(stat.avgResponseTime) || 0, + }); + }); + + // Build response with targets and their statistics (only include needed fields) + const targetsWithStats = targets.map(target => { + const status = monitorService.getTargetStatus(target.id); + const uptime24h = uptime24hMap.get(target.id) || { uptime: 0, totalPings: 0, successfulPings: 0, failedPings: 0 }; + const uptime30d = uptime30dMap.get(target.id) || { uptime: 0, totalPings: 0, successfulPings: 0, failedPings: 0 }; + const miniStats = miniStatsMap.get(target.id) || []; + const adminViewer = isPrivilegedViewer(req); + const showDetails = adminViewer || target.publicShowDetails === true; + + const result = { + _id: target.id, + name: target.name, + currentStatus: status, + isUp: status === 'up', + isDown: status === 'down', + enabled: target.enabled, + publicVisible: target.publicVisible, + notification: liveNotificationState(target.id), + publicShowDetails: showDetails, + publicShowStatus: adminViewer ? true : target.publicShowStatus !== false, + publicShowAppLink: adminViewer ? true : target.publicShowAppLink !== false, + uptime: { + '24h': uptime24h, + '30d': uptime30d, + }, + miniStats, + }; + + // Only include host/protocol if publicShowDetails is true + if (showDetails) { + result.host = target.host; + result.protocol = target.protocol; + } + + // Only expose an app URL when the public app-link setting allows it. + // Icons remain available for service rows even when linking is disabled. + if (target.appUrl && (adminViewer || target.publicShowAppLink !== false)) { + result.appUrl = target.appUrl; + } + if (target.appIcon) { + result.appIcon = target.appIcon; + } + + // Only include group/position/quickCommands if they have values + if (target.group) { + result.group = target.group; + } + if (target.position !== 0) { + result.position = target.position; + } + if (target.quickCommands && target.quickCommands.length > 0 && (adminViewer || target.publicShowAppLink !== false)) { + result.quickCommands = target.quickCommands; + } + + return result; + }); + + // Calculate overall status + const upCount = targetsWithStats.filter(t => t.isUp).length; + const downCount = targetsWithStats.filter(t => t.isDown).length; + let overallStatus = 'operational'; + if (downCount > 0) { + overallStatus = downCount === targetsWithStats.length ? 'down' : 'degraded'; + } + + const summary = { + success: true, + status: { + overallStatus, + upTargets: upCount, + downTargets: downCount, + totalTargets: targetsWithStats.length, + }, + targets: targetsWithStats, + }; + cacheService.set(cacheKey, summary, PUBLIC_DATA_CACHE_TTL); + setPublicCacheHeaders(res); + res.json(hydrateSummary(summary, req)); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get overall status +router.get('/api/status', async (req, res) => { + try { + const prisma = getPrisma(); + + const targets = await prisma.target.findMany({ + where: targetVisibilityWhere(req), + }); + + const targetsWithStatus = targets.map((target) => publicTargetStatus(target, req)); + + const upCount = targetsWithStatus.filter((t) => t.isUp).length; + const downCount = targetsWithStatus.filter((t) => t.isDown).length; + + res.json({ + success: true, + status: { + totalTargets: targetsWithStatus.length, + upTargets: upCount, + downTargets: downCount, + overallStatus: downCount === 0 ? 'operational' : downCount === targetsWithStatus.length ? 'down' : 'degraded', + }, + targets: targetsWithStatus, + viewer: { isAdmin: isAdminViewer(req), isApiClient: isApiClient(req) }, + timestamp: new Date(), + }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Proxy endpoint for icons +router.get('/api/proxy-icon', async (req, res) => { + try { + const { url } = req.query; + if (!url) return res.status(400).json({ success: false, error: 'URL parameter is required' }); + + let targetUrl; + try { + targetUrl = new URL(url); + } catch (e) { + return res.status(400).json({ success: false, error: 'Invalid URL' }); + } + + const https = require('https'); + const response = await axios.get(url, { + responseType: 'arraybuffer', + timeout: 10000, + headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }, + validateStatus: (status) => status < 500, + httpsAgent: new https.Agent({ rejectUnauthorized: false }), + }); + + if (response.status >= 400) { + return res.status(404).json({ success: false, error: 'Icon not found' }); + } + + const contentType = response.headers['content-type'] || 'image/png'; + res.setHeader('Content-Type', contentType); + res.setHeader('Cache-Control', 'public, max-age=86400'); + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(Buffer.from(response.data)); + } catch (error) { + console.error('Error proxying icon:', error.message); + res.status(500).json({ success: false, error: 'Failed to fetch icon' }); + } +}); + +// Public API - Get incidents (read-only) +router.get('/api/incidents', async (req, res) => { + try { + const prisma = getPrisma(); + const incidents = await prisma.incident.findMany({ orderBy: { createdAt: 'desc' } }); + res.json({ success: true, incidents: incidents.map(i => ({ ...i, _id: i.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get posts (read-only, only published) +router.get('/api/posts', async (req, res) => { + try { + const prisma = getPrisma(); + const posts = await prisma.post.findMany({ + where: { published: true }, + orderBy: { createdAt: 'desc' }, + }); + res.json({ success: true, posts: posts.map(p => ({ ...p, _id: p.id })) }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +// Public API - Get single post (read-only, only published) +router.get('/api/posts/:id', async (req, res) => { + try { + const prisma = getPrisma(); + const post = await prisma.post.findFirst({ + where: { id: req.params.id, published: true }, + }); + + if (!post) { + return res.status(404).json({ success: false, error: 'Post not found' }); + } + + res.json({ success: true, post: { ...post, _id: post.id } }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +module.exports = router; diff --git a/src/routes/setup.js b/src/routes/setup.js new file mode 100644 index 0000000..4c494e2 --- /dev/null +++ b/src/routes/setup.js @@ -0,0 +1,192 @@ +const express = require('express'); +const fs = require('fs'); +const path = require('path'); +const { v4: uuidv4 } = require('uuid'); +const chalk = require('../utils/colors'); +const { getPrisma } = require('../config/prisma'); +const { isSetupComplete } = require('../middleware/setupCheck'); + +const router = express.Router(); + +// Get gateway IP using default-gateway package +async function detectGateway() { + try { + const defaultGateway = require('default-gateway'); + // The package exports gateway4 and gateway6 for IPv4/IPv6 + const result = await defaultGateway.gateway4async(); + + if (result && result.gateway) { + console.log(chalk.cyan(`Detected gateway: ${result.gateway}`)); + return result.gateway; + } + + console.warn(chalk.yellow('Could not detect gateway, no gateway found')); + return null; + } catch (err) { + console.warn(chalk.yellow(`Gateway detection error: ${err.message}`)); + return null; + } +} + +// GET setup page +router.get('/', async (req, res) => { + // If already set up, redirect to admin + if (isSetupComplete()) { + return res.redirect('/admin/login'); + } + + try { + const detectedGateway = await detectGateway(); + res.render('setup/wizard', { + detectedGateway: detectedGateway || null, + error: null, + }); + } catch (err) { + console.error(chalk.red('Setup page error:'), err.message); + res.render('setup/wizard', { + detectedGateway: null, + error: 'Failed to load setup page', + }); + } +}); + +// POST setup form +router.post('/', async (req, res) => { + try { + // If already set up, redirect to admin + if (isSetupComplete()) { + return res.redirect('/admin/login'); + } + + const { adminUsername, adminPassword, passwordConfirm, gatewayIp } = req.body; + + // Validation + const errors = []; + + if (!adminUsername || adminUsername.trim().length === 0) { + errors.push('Admin username is required'); + } + + if (!adminPassword || adminPassword.length < 6) { + errors.push('Password must be at least 6 characters'); + } + + if (adminPassword !== passwordConfirm) { + errors.push('Passwords do not match'); + } + + if (!gatewayIp || gatewayIp.trim().length === 0) { + errors.push('Gateway IP is required'); + } + + // Validate IP format + const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/; + if (gatewayIp && !ipRegex.test(gatewayIp)) { + errors.push('Invalid IP address format'); + } + + if (errors.length > 0) { + const detectedGateway = await detectGateway(); + return res.status(400).render('setup/wizard', { + detectedGateway: detectedGateway || '192.168.1.1', + error: errors[0], + formData: { adminUsername, gatewayIp }, + }); + } + + // Update .env file + const envPath = path.join(process.cwd(), '.env'); + let envContent = ''; + + if (fs.existsSync(envPath)) { + envContent = fs.readFileSync(envPath, 'utf8'); + } + + // Add admin credentials - handle both commented and uncommented lines + if (!envContent.includes('ADMIN_PASSWORD') || envContent.includes('# ADMIN_PASSWORD')) { + // Either no ADMIN_PASSWORD at all, or it's commented out - replace commented line or add new line + if (envContent.includes('# ADMIN_PASSWORD')) { + // Replace commented line with uncommented one + envContent = envContent.replace(/# ADMIN_PASSWORD=.*/g, `ADMIN_PASSWORD=${adminPassword}`); + envContent = envContent.replace(/# ADMIN_USERNAME=.*/g, `ADMIN_USERNAME=${adminUsername}`); + } else { + // Add new lines + envContent += `\n# Admin Credentials (set during setup)\nADMIN_PASSWORD=${adminPassword}\nADMIN_USERNAME=${adminUsername}\n`; + } + } else { + // Update existing uncommented lines + envContent = envContent.replace(/ADMIN_PASSWORD=.*/g, `ADMIN_PASSWORD=${adminPassword}`); + envContent = envContent.replace(/ADMIN_USERNAME=.*/g, `ADMIN_USERNAME=${adminUsername}`); + } + + fs.writeFileSync(envPath, envContent); + + // Update in-memory environment variables so isSetupComplete() works + process.env.ADMIN_PASSWORD = adminPassword; + process.env.ADMIN_USERNAME = adminUsername; + + // Create default monitors in database using Prisma + try { + const prisma = getPrisma(); + + // Create default targets + const targets = [ + { + name: 'Gateway', + host: gatewayIp, + protocol: 'ICMP', + group: 'Network', + position: 0, + }, + { + name: 'Cloudflare DNS', + host: '1.1.1.1', + protocol: 'ICMP', + group: 'Network', + position: 1, + }, + ]; + + for (const target of targets) { + try { + await prisma.target.create({ + data: { + name: target.name, + host: target.host, + protocol: target.protocol, + group: target.group, + position: target.position, + enabled: true, + interval: 60, + timeout: 30, + }, + }); + } catch (err) { + // Ignore duplicate key errors (P2002 is Prisma's unique constraint error) + if (err.code !== 'P2002') { + console.error(chalk.yellow(`Warning creating ${target.name}:`), err.message); + } + } + } + } catch (err) { + console.error(chalk.red('Database error during setup:'), err.message); + } + + console.log(chalk.green('βœ“ Setup completed successfully')); + + // Automatically log the user in after setup + req.session.adminAuthenticated = true; + + // Redirect to admin dashboard - middleware will set cookie automatically + res.redirect('/admin'); + } catch (err) { + console.error(chalk.red('Setup error:'), err.message); + const detectedGateway = await detectGateway(); + res.status(500).render('setup/wizard', { + detectedGateway: detectedGateway || '192.168.1.1', + error: 'An error occurred during setup. Please try again.', + }); + } +}); + +module.exports = router; diff --git a/src/routes/site.js b/src/routes/site.js new file mode 100644 index 0000000..998ff6a --- /dev/null +++ b/src/routes/site.js @@ -0,0 +1,147 @@ +// Slim, cache-friendly JSON for the static public site (src/site). +const express = require('express'); +const { getPrisma } = require('../config/prisma'); +const monitorService = require('../services/monitorService'); +const router = express.Router(); + +const TTL = 30 * 1000; +let cache = { at: 0, data: null, inflight: null }; + +async function build() { + const prisma = getPrisma(); + const targets = await prisma.target.findMany({ + where: { enabled: true, publicVisible: true }, + select: { id: true, name: true, appUrl: true, appIcon: true, position: true, group: true, publicShowStatus: true, publicShowAppLink: true, description: true, tier: true, linkPublic: true }, + orderBy: { position: 'asc' }, + }); + const ids = targets.map((t) => t.id); + const now = Date.now(); + const d1 = new Date(now - 24 * 3600e3), d30 = new Date(now - 30 * 24 * 3600e3); + const end = Math.floor(now / 3600e3) * 3600, start = end - 23 * 3600; + const [u24, u30, hourly] = ids.length ? await Promise.all([ + prisma.$queryRaw`SELECT "targetId", SUM("totalPings")::int t, SUM("successfulPings")::int s FROM statistics WHERE "targetId" = ANY(${ids}::text[]) AND date >= ${d1} GROUP BY "targetId"`, + prisma.$queryRaw`SELECT "targetId", SUM("totalPings")::int t, SUM("successfulPings")::int s FROM statistics WHERE "targetId" = ANY(${ids}::text[]) AND date >= ${d30} GROUP BY "targetId"`, + prisma.$queryRaw` + SELECT "targetId", floor(extract(epoch from timestamp)/3600)::bigint*3600 AS b, + count(*)::int t, sum(CASE WHEN success THEN 1 ELSE 0 END)::int s, + COALESCE(avg("responseTime"),0)::int rt + FROM "pingResults" + WHERE "targetId" = ANY(${ids}::text[]) AND timestamp >= to_timestamp(${start}::bigint) + GROUP BY 1,2`, + ]) : [[], [], []]; + const pct = (r) => (r && r.t ? Math.round((r.s / r.t) * 10000) / 100 : null); + const m24 = new Map(u24.map((r) => [r.targetId, r])), m30 = new Map(u30.map((r) => [r.targetId, r])); + const hb = new Map(); + for (const r of hourly) { + if (!hb.has(r.targetId)) hb.set(r.targetId, new Map()); + hb.get(r.targetId).set(Number(r.b), r); + } + const services = targets.map((t) => { + const status = monitorService.getTargetStatus(t.id); + const h = hb.get(t.id) || new Map(); + // 24 hourly buckets: 0 = no data, 1 = ok, 2 = partial, 3 = down + const bars = []; + let rtSum = 0, rtN = 0; + for (let i = 0; i < 24; i++) { + const r = h.get(start + i * 3600); + if (!r || !r.t) { bars.push(0); continue; } + const f = r.s / r.t; + bars.push(f >= 0.98 ? 1 : f >= 0.5 ? 2 : 3); + if (r.rt) { rtSum += r.rt; rtN++; } + } + return { + id: t.id, name: t.name, status, + url: t.publicShowAppLink !== false && t.linkPublic !== false ? t.appUrl || null : null, + description: t.description || null, tier: t.tier || 'normal', + icon: t.appIcon || null, group: t.group || null, + up24: pct(m24.get(t.id)), up30: pct(m30.get(t.id)), + rt: rtN ? Math.round(rtSum / rtN) : null, bars, + }; + }); + const down = services.filter((s) => s.status === 'down').length; + const incidents = (await prisma.incident.findMany({ orderBy: { createdAt: 'desc' }, take: 30 })).map((i) => ({ + id: i.id, title: i.title, description: i.description, severity: i.severity, status: i.status, + services: i.affectedServices || [], updates: i.updates || [], + scheduled: i.isScheduled, start: i.scheduledStart, end: i.scheduledEnd, + createdAt: i.createdAt, resolvedAt: i.resolvedAt, + })); + return { + generatedAt: new Date().toISOString(), + overall: !services.length ? 'unknown' : down === 0 ? 'operational' : down === services.length ? 'down' : 'degraded', + up: services.filter((s) => s.status === 'up').length, down, total: services.length, + services, incidents, + }; +} + +async function get() { + if (cache.data && Date.now() - cache.at < TTL) return cache.data; + if (!cache.inflight) { + cache.inflight = build().then((d) => { cache = { at: Date.now(), data: d, inflight: null }; return d; }) + .catch((e) => { cache.inflight = null; if (cache.data) return cache.data; throw e; }); + } + return cache.inflight; +} + +router.get('/api/site/summary', async (req, res) => { + try { + const d = await get(); + res.set('Cache-Control', 'public, max-age=15, stale-while-revalidate=60'); + res.json(d); + } catch (e) { res.status(500).json({ error: 'unavailable' }); } +}); + +router.get('/api/site/news', async (req, res) => { + try { + const posts = await getPrisma().post.findMany({ where: { published: true }, orderBy: { createdAt: 'desc' }, take: 50 }); + res.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300'); + res.json({ posts: posts.map((p) => ({ id: p.id, title: p.title, content: p.content, createdAt: p.createdAt, updatedAt: p.updatedAt })) }); + } catch (e) { res.status(500).json({ error: 'unavailable' }); } +}); + +router.get('/api/site/news.rss', async (req, res) => { + try { + const base = process.env.SITE_URL || `${req.protocol}://${req.get('host')}`; + const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c])); + const posts = await getPrisma().post.findMany({ where: { published: true }, orderBy: { createdAt: 'desc' }, take: 30 }); + res.type('application/rss+xml').send(`${esc(process.env.SITE_NAME || 'Status')} news${base}/newsNews and status updates${posts.map((p) => `${esc(p.title)}${base}/news#${p.id}${p.id}${p.createdAt.toUTCString()}${esc(p.content)}`).join('')}`); + } catch (e) { res.status(500).end(); } +}); + +router.get('/api/site/tools/ip', (req, res) => { + const ip = req.headers['cf-connecting-ip'] || req.ip; + res.set('Cache-Control', 'no-store'); + res.json({ ip }); +}); + +// ---- Branding / PWA ---- +const fs = require('fs'), path = require('path'); +const BR = path.join(__dirname, '..', 'site', 'brand'); +let brandCache = null; +async function brand() { + if (brandCache && Date.now() - brandCache.at < 15000) return brandCache.v; + let b = null; + try { b = await getPrisma().siteBrand.findUnique({ where: { id: 'brand' } }); } catch (e) {} + const v = { name: b?.name || process.env.SITE_NAME || 'LocalPing', accent: b?.accent || '#6ea8ff', tagline: b?.tagline || '', icon: b?.iconData ? Buffer.from(b.iconData) : null, iconType: b?.iconType || 'image/png', v: b?.updatedAt?.getTime() || 0 }; + brandCache = { at: Date.now(), v }; + return v; +} +router.get('/api/site/brand', async (req, res) => { const b = await brand(); res.set('Cache-Control', 'public, max-age=60'); res.json({ name: b.name, accent: b.accent, tagline: b.tagline, v: b.v }); }); +router.get(['/brand/icon.svg', '/brand/icon-:size.png', '/favicon.ico'], async (req, res) => { + const b = await brand(); + res.set('Cache-Control', 'public, max-age=3600'); + if (b.icon) return res.type(b.iconType).send(b.icon); + if (req.path.endsWith('.svg')) return res.type('image/svg+xml').sendFile(path.join(BR, 'icon.svg')); + const size = [512, 192, 180, 32].includes(+req.params.size) ? +req.params.size : req.path === '/favicon.ico' ? 32 : 512; + res.type('image/png').sendFile(path.join(BR, `icon-${size}.png`)); +}); +router.get('/manifest.webmanifest', async (req, res) => { + const b = await brand(); + res.type('application/manifest+json').set('Cache-Control', 'public, max-age=300').json({ + name: b.name, short_name: b.name.slice(0, 12), start_url: '/', display: 'standalone', background_color: '#0b0d12', theme_color: b.accent, + icons: [192, 512].map((n) => ({ src: `/brand/icon-${n}.png?v=${b.v}`, sizes: `${n}x${n}`, type: 'image/png', purpose: 'any maskable' })), + }); +}); +router.invalidateBrand = () => { brandCache = null; }; +router.invalidate = () => { cache = { at: 0, data: null, inflight: null }; }; + +module.exports = router; diff --git a/src/services/actionService.js b/src/services/actionService.js new file mode 100644 index 0000000..1f30ba7 --- /dev/null +++ b/src/services/actionService.js @@ -0,0 +1,235 @@ +const { exec } = require('child_process'); +const { promisify } = require('util'); +const axios = require('axios'); +const chalk = require('../utils/colors'); +const sh = require('shell-escape'); + +const execAsync = promisify(exec); + +class ActionService { + /** + * Execute a quick-fix action + */ + async executeAction(action) { + try { + const start = Date.now(); + + switch (action.type) { + case 'command': + return await this.executeCommand(action); + case 'ssh': + return await this.executeSSH(action); + case 'http': + return await this.executeHTTP(action); + case 'script': + return await this.executeScript(action); + default: + return { + success: false, + error: 'Unknown action type: ' + action.type, + executionTime: Date.now() - start, + }; + } + } catch (error) { + return { + success: false, + error: error.message, + executionTime: 0, + }; + } + } + + /** + * Execute a local shell command + */ + async executeCommand(action) { + const start = Date.now(); + + try { + const { stdout, stderr } = await execAsync(action.command, { + timeout: action.timeout || 30000, + maxBuffer: 1024 * 1024 * 10, // 10MB + }); + + const executionTime = Date.now() - start; + + return { + success: true, + stdout, + stderr, + executionTime, + }; + } catch (error) { + return { + success: false, + error: error.message, + stdout: error.stdout, + stderr: error.stderr, + executionTime: Date.now() - start, + }; + } + } + + /** + * Execute a command via SSH + */ + async executeSSH(action) { + const start = Date.now(); + + try { + // Build SSH command with proper argument escaping + const sshArgs = []; + + // Add port if specified + if (action.port) { + sshArgs.push('-p', String(action.port)); + } + + // Add user@host + const host = action.user ? `${action.user}@${action.host}` : action.host; + sshArgs.push(host); + + // Add the remote command - properly escaped + sshArgs.push(action.command); + + // Use shell-escape to properly quote the entire command + const cmd = sh(['ssh', ...sshArgs]); + + const { stdout, stderr } = await execAsync(cmd, { + timeout: action.timeout || 30000, + maxBuffer: 1024 * 1024 * 10, + }); + + const executionTime = Date.now() - start; + + return { + success: true, + stdout, + stderr, + executionTime, + host: action.host, + }; + } catch (error) { + return { + success: false, + error: error.message, + stdout: error.stdout, + stderr: error.stderr, + executionTime: Date.now() - start, + host: action.host, + }; + } + } + + /** + * Execute an HTTP request + */ + async executeHTTP(action) { + const start = Date.now(); + + try { + const method = action.method || 'GET'; + const url = action.url; + const headers = action.headers || {}; + const data = action.data || null; + + const response = await axios({ + method, + url, + headers, + data, + timeout: action.timeout || 10000, + validateStatus: () => true, + }); + + const executionTime = Date.now() - start; + + return { + success: response.status >= 200 && response.status < 400, + statusCode: response.status, + responseData: response.data, + executionTime, + url, + }; + } catch (error) { + return { + success: false, + error: error.message, + executionTime: Date.now() - start, + url: action.url, + }; + } + } + + /** + * Execute a script file + */ + async executeScript(action) { + const start = Date.now(); + + try { + // Build script command with proper argument escaping + const scriptArgs = [action.scriptPath]; + + // Add arguments if provided - each argument is separately escaped + if (action.args && Array.isArray(action.args)) { + scriptArgs.push(...action.args); + } + + // Use shell-escape to properly quote the command and arguments + const cmd = sh(scriptArgs); + + const { stdout, stderr } = await execAsync(cmd, { + timeout: action.timeout || 60000, + maxBuffer: 1024 * 1024 * 10, + }); + + const executionTime = Date.now() - start; + + return { + success: true, + stdout, + stderr, + executionTime, + script: action.scriptPath, + }; + } catch (error) { + return { + success: false, + error: error.message, + stdout: error.stdout, + stderr: error.stderr, + executionTime: Date.now() - start, + script: action.scriptPath, + }; + } + } + + /** + * Execute multiple actions in sequence + */ + async executeActionSequence(actions) { + const results = []; + + for (const action of actions) { + const result = await this.executeAction(action); + results.push(result); + + // Stop on first failure if stopOnError is true + if (!result.success && action.stopOnError) { + break; + } + } + + return results; + } + + /** + * Execute multiple actions in parallel + */ + async executeActionParallel(actions) { + return Promise.all(actions.map((action) => this.executeAction(action))); + } +} + +module.exports = new ActionService(); diff --git a/src/services/backupService.js b/src/services/backupService.js new file mode 100644 index 0000000..1a0b300 --- /dev/null +++ b/src/services/backupService.js @@ -0,0 +1,451 @@ +const { getPrisma } = require('../config/prisma'); +const path = require('path'); +const fs = require('fs'); + +/** + * Export data from the database + * @param {Object} options - Export options + * @param {boolean} options.full - Export everything + * @param {boolean} options.monitors - Export monitors (targets) + * @param {boolean} options.incidents - Export incidents + * @param {boolean} options.posts - Export blog posts + * @param {boolean} options.dataPoints - Export ping results and statistics + * @param {boolean} options.actions - Export actions + * @param {boolean} options.alerts - Export alerts + * @param {boolean} options.settings - Export admin and public UI settings + * @param {boolean} options.favicons - Export favicons + * @returns {Promise} Exported data + */ +async function exportData(options = {}) { + const prisma = getPrisma(); + const exportResult = { + version: '1.0.0', + exportDate: new Date().toISOString(), + data: {} + }; + + // If full export, set all options to true + if (options.full) { + options.monitors = true; + options.incidents = true; + options.posts = true; + options.dataPoints = true; + options.actions = true; + options.alerts = true; + options.settings = true; + options.favicons = true; + } + + // Export monitors (targets) + if (options.monitors) { + const targets = await prisma.target.findMany(); + // Map id to _id for compatibility + exportResult.data.targets = targets.map(target => ({ + ...target, + _id: target.id, + })); + } + + // Export incidents + if (options.incidents) { + const incidents = await prisma.incident.findMany(); + exportResult.data.incidents = incidents.map(inc => ({ ...inc, _id: inc.id })); + } + + // Export posts + if (options.posts) { + const posts = await prisma.post.findMany(); + exportResult.data.posts = posts.map(post => ({ ...post, _id: post.id })); + } + + // Export data points (ping results and statistics) + if (options.dataPoints) { + const pingResults = await prisma.pingResult.findMany(); + const statistics = await prisma.statistic.findMany(); + + // Map id to _id for compatibility + exportResult.data.pingResults = pingResults.map(pr => ({ ...pr, _id: pr.id })); + exportResult.data.statistics = statistics.map(s => ({ ...s, _id: s.id })); + + // Legacy format names for compatibility + exportResult.data.ping_results = exportResult.data.pingResults; + exportResult.data.daily_stats = exportResult.data.statistics; + } + + // Export actions + if (options.actions) { + const actions = await prisma.action.findMany(); + exportResult.data.actions = actions.map(a => ({ ...a, _id: a.id })); + } + + // Export alerts + if (options.alerts) { + const alerts = await prisma.alert.findMany(); + exportResult.data.alerts = alerts.map(a => ({ ...a, _id: a.id })); + } + + // Export settings + if (options.settings) { + const adminSettings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + const publicUISettings = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } }); + exportResult.data.adminSettings = adminSettings ? { ...adminSettings, _id: adminSettings.id } : null; + exportResult.data.publicUISettings = publicUISettings ? { ...publicUISettings, _id: publicUISettings.id } : null; + } + + // Export favicons + if (options.favicons) { + const favicons = await prisma.favicon.findMany(); + exportResult.data.favicons = favicons.map(f => ({ ...f, _id: f.id })); + } + + return exportResult; +} + +/** + * Import data into the database + * @param {Object} importData - Data to import + * @param {Object} options - Import options + * @param {boolean} options.overwrite - Overwrite existing data + * @returns {Promise} Import result + */ +async function importData(importDataObj, options = {}) { + const prisma = getPrisma(); + const results = { + imported: {}, + errors: [] + }; + + try { + // Validate import data structure + if (!importDataObj.data || typeof importDataObj.data !== 'object') { + throw new Error('Invalid import data format'); + } + + // Import targets (monitors) + if (importDataObj.data.targets && Array.isArray(importDataObj.data.targets)) { + try { + let imported = 0; + let updated = 0; + let skipped = 0; + for (const target of importDataObj.data.targets) { + try { + const targetId = target.id || target._id; + // Check if target exists by id + const existingById = await prisma.target.findUnique({ where: { id: targetId } }); + if (existingById) { + if (options.overwrite) { + const { id, _id, ...updateData } = target; + await prisma.target.update({ + where: { id: targetId }, + data: updateData, + }); + updated++; + } else { + skipped++; + } + } else { + // Check if target with same name exists (UNIQUE constraint on name) + const existingByName = await prisma.target.findUnique({ where: { name: target.name } }); + if (existingByName) { + if (options.overwrite) { + const { id, _id, ...updateData } = target; + await prisma.target.update({ + where: { id: existingByName.id }, + data: updateData, + }); + updated++; + } else { + skipped++; + } + } else { + const { _id, ...insertData } = target; + await prisma.target.create({ + data: { + id: targetId, + ...insertData, + }, + }); + imported++; + } + } + } catch (error) { + // Handle individual target errors (e.g., UNIQUE constraint) + if (error.code === 'P2002') { + skipped++; + } else { + throw error; + } + } + } + results.imported.targets = { imported, updated, skipped }; + } catch (error) { + results.errors.push({ type: 'targets', error: error.message }); + } + } + + // Import incidents + if (importDataObj.data.incidents && Array.isArray(importDataObj.data.incidents)) { + try { + let imported = 0; + let updated = 0; + for (const incident of importDataObj.data.incidents) { + const incidentId = incident.id || incident._id; + const existing = await prisma.incident.findUnique({ where: { id: incidentId } }); + if (existing) { + if (options.overwrite) { + const { id, _id, ...updateData } = incident; + await prisma.incident.update({ where: { id: incidentId }, data: updateData }); + updated++; + } + } else { + const { _id, ...insertData } = incident; + await prisma.incident.create({ data: { id: incidentId, ...insertData } }); + imported++; + } + } + results.imported.incidents = { imported, updated }; + } catch (error) { + results.errors.push({ type: 'incidents', error: error.message }); + } + } + + // Import posts + if (importDataObj.data.posts && Array.isArray(importDataObj.data.posts)) { + try { + let imported = 0; + let updated = 0; + for (const post of importDataObj.data.posts) { + const postId = post.id || post._id; + const existing = await prisma.post.findUnique({ where: { id: postId } }); + if (existing) { + if (options.overwrite) { + const { id, _id, ...updateData } = post; + await prisma.post.update({ where: { id: postId }, data: updateData }); + updated++; + } + } else { + const { _id, ...insertData } = post; + await prisma.post.create({ data: { id: postId, ...insertData } }); + imported++; + } + } + results.imported.posts = { imported, updated }; + } catch (error) { + results.errors.push({ type: 'posts', error: error.message }); + } + } + + // Import data points + if (importDataObj.data.pingResults && Array.isArray(importDataObj.data.pingResults)) { + try { + let imported = 0; + for (const pingResult of importDataObj.data.pingResults) { + const pingResultId = pingResult.id || pingResult._id; + const existing = await prisma.pingResult.findUnique({ where: { id: pingResultId } }); + if (!existing) { + const { _id, ...insertData } = pingResult; + await prisma.pingResult.create({ data: { id: pingResultId, ...insertData } }); + imported++; + } + } + results.imported.pingResults = { imported }; + } catch (error) { + results.errors.push({ type: 'pingResults', error: error.message }); + } + } + + if (importDataObj.data.statistics && Array.isArray(importDataObj.data.statistics)) { + try { + let imported = 0; + for (const stat of importDataObj.data.statistics) { + const statId = stat.id || stat._id; + const existing = await prisma.statistic.findUnique({ where: { id: statId } }); + if (!existing) { + const { _id, ...insertData } = stat; + await prisma.statistic.create({ data: { id: statId, ...insertData } }); + imported++; + } + } + results.imported.statistics = { imported }; + } catch (error) { + results.errors.push({ type: 'statistics', error: error.message }); + } + } + + // Import ping_results (legacy format) - convert to pingResults + if (importDataObj.data.ping_results && Array.isArray(importDataObj.data.ping_results)) { + try { + let imported = 0; + for (const pingResult of importDataObj.data.ping_results) { + try { + await prisma.pingResult.create({ + data: { + targetId: pingResult.targetId, + success: pingResult.success === 1 || pingResult.success === true, + responseTime: pingResult.responseTime || null, + timestamp: pingResult.timestamp ? new Date(pingResult.timestamp) : new Date(), + statusCode: pingResult.statusCode || null, + error: pingResult.error || null, + protocol: pingResult.protocol || null, + }, + }); + imported++; + } catch (error) { + // Skip duplicates + } + } + results.imported.ping_results = { imported }; + } catch (error) { + results.errors.push({ type: 'ping_results', error: error.message }); + } + } + + // Import daily_stats (legacy format) - convert to statistics + if (importDataObj.data.daily_stats && Array.isArray(importDataObj.data.daily_stats)) { + try { + let imported = 0; + for (const stat of importDataObj.data.daily_stats) { + try { + await prisma.statistic.create({ + data: { + targetId: stat.targetId, + date: stat.date ? new Date(stat.date) : new Date(), + totalPings: stat.totalPings || 0, + successfulPings: stat.successfulPings || 0, + failedPings: (stat.totalPings || 0) - (stat.successfulPings || 0), + uptime: stat.totalPings > 0 ? (stat.successfulPings / stat.totalPings) * 100 : 0, + lastResponseTime: 0, + avgResponseTime: stat.avgResponseTime || 0, + minResponseTime: stat.minResponseTime || null, + maxResponseTime: stat.maxResponseTime || null, + }, + }); + imported++; + } catch (error) { + // Skip duplicates + } + } + results.imported.daily_stats = { imported }; + } catch (error) { + results.errors.push({ type: 'daily_stats', error: error.message }); + } + } + + // Import actions + if (importDataObj.data.actions && Array.isArray(importDataObj.data.actions)) { + try { + let imported = 0; + let updated = 0; + for (const action of importDataObj.data.actions) { + const actionId = action.id || action._id; + const existing = await prisma.action.findUnique({ where: { id: actionId } }); + if (existing) { + if (options.overwrite) { + const { id, _id, ...updateData } = action; + await prisma.action.update({ where: { id: actionId }, data: updateData }); + updated++; + } + } else { + const { _id, ...insertData } = action; + await prisma.action.create({ data: { id: actionId, ...insertData } }); + imported++; + } + } + results.imported.actions = { imported, updated }; + } catch (error) { + results.errors.push({ type: 'actions', error: error.message }); + } + } + + // Import alerts + if (importDataObj.data.alerts && Array.isArray(importDataObj.data.alerts)) { + try { + let imported = 0; + for (const alert of importDataObj.data.alerts) { + const alertId = alert.id || alert._id; + const existing = await prisma.alert.findUnique({ where: { id: alertId } }); + if (!existing) { + const { _id, ...insertData } = alert; + await prisma.alert.create({ data: { id: alertId, ...insertData } }); + imported++; + } + } + results.imported.alerts = { imported }; + } catch (error) { + results.errors.push({ type: 'alerts', error: error.message }); + } + } + + // Import settings + if (importDataObj.data.adminSettings) { + try { + const existing = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + const { id, _id, ...settingsData } = importDataObj.data.adminSettings; + if (existing) { + if (options.overwrite) { + await prisma.adminSettings.update({ where: { id: 'settings' }, data: settingsData }); + results.imported.adminSettings = { updated: 1 }; + } + } else { + await prisma.adminSettings.create({ data: { id: 'settings', ...settingsData } }); + results.imported.adminSettings = { imported: 1 }; + } + } catch (error) { + results.errors.push({ type: 'adminSettings', error: error.message }); + } + } + + if (importDataObj.data.publicUISettings) { + try { + const existing = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } }); + const { id, _id, ...settingsData } = importDataObj.data.publicUISettings; + if (existing) { + if (options.overwrite) { + await prisma.publicUISettings.update({ where: { id: 'settings' }, data: settingsData }); + results.imported.publicUISettings = { updated: 1 }; + } + } else { + await prisma.publicUISettings.create({ data: { id: 'settings', ...settingsData } }); + results.imported.publicUISettings = { imported: 1 }; + } + } catch (error) { + results.errors.push({ type: 'publicUISettings', error: error.message }); + } + } + + // Import favicons + if (importDataObj.data.favicons && Array.isArray(importDataObj.data.favicons)) { + try { + let imported = 0; + let updated = 0; + for (const favicon of importDataObj.data.favicons) { + const faviconId = favicon.id || favicon._id; + const existing = await prisma.favicon.findUnique({ where: { id: faviconId } }); + if (existing) { + if (options.overwrite) { + const { id, _id, ...updateData } = favicon; + await prisma.favicon.update({ where: { id: faviconId }, data: updateData }); + updated++; + } + } else { + const { _id, ...insertData } = favicon; + await prisma.favicon.create({ data: { id: faviconId, ...insertData } }); + imported++; + } + } + results.imported.favicons = { imported, updated }; + } catch (error) { + results.errors.push({ type: 'favicons', error: error.message }); + } + } + + return results; + } catch (error) { + throw new Error(`Import failed: ${error.message}`); + } +} + +module.exports = { + exportData, + importData, +}; diff --git a/src/services/cacheService.js b/src/services/cacheService.js new file mode 100644 index 0000000..ee006f4 --- /dev/null +++ b/src/services/cacheService.js @@ -0,0 +1,124 @@ +/** + * In-memory cache service for database queries + * Improves performance by caching frequently accessed data + */ + +class CacheService { + constructor() { + this.cache = new Map(); + this.defaultTTL = 60000; // 60 seconds default TTL + this.maxSize = 1000; // Maximum cache entries + } + + /** + * Generate a cache key from collection name and query + */ + generateKey(collection, query, options = {}) { + const queryStr = JSON.stringify(query || {}); + const optionsStr = JSON.stringify(options || {}); + return `${collection}:${queryStr}:${optionsStr}`; + } + + /** + * Get cached value + */ + get(key) { + const entry = this.cache.get(key); + if (!entry) { + return null; + } + + // Check if expired + if (Date.now() > entry.expiresAt) { + this.cache.delete(key); + return null; + } + + return entry.value; + } + + /** + * Set cached value with TTL + */ + set(key, value, ttl = null) { + // If cache is too large, remove oldest entries + if (this.cache.size >= this.maxSize) { + this.evictOldest(); + } + + const expiresAt = Date.now() + (ttl || this.defaultTTL); + this.cache.set(key, { value, expiresAt, createdAt: Date.now() }); + } + + /** + * Remove entry from cache + */ + delete(key) { + this.cache.delete(key); + } + + /** + * Invalidate all entries for a collection + */ + invalidateCollection(collection) { + const keysToDelete = []; + for (const key of this.cache.keys()) { + if (key.startsWith(`${collection}:`)) { + keysToDelete.push(key); + } + } + keysToDelete.forEach(key => this.cache.delete(key)); + } + + /** + * Invalidate all cache entries + */ + clear() { + this.cache.clear(); + } + + /** + * Remove oldest entries when cache is full + */ + evictOldest() { + const entries = Array.from(this.cache.entries()) + .map(([key, value]) => ({ key, createdAt: value.createdAt })) + .sort((a, b) => a.createdAt - b.createdAt); + + // Remove oldest 10% of entries + const toRemove = Math.max(1, Math.floor(entries.length * 0.1)); + for (let i = 0; i < toRemove; i++) { + this.cache.delete(entries[i].key); + } + } + + /** + * Get cache statistics + */ + getStats() { + const now = Date.now(); + let expired = 0; + let active = 0; + + for (const entry of this.cache.values()) { + if (now > entry.expiresAt) { + expired++; + } else { + active++; + } + } + + return { + total: this.cache.size, + active, + expired, + maxSize: this.maxSize, + }; + } +} + +// Singleton instance +const cacheService = new CacheService(); + +module.exports = cacheService; + diff --git a/src/services/dataRetentionService.js b/src/services/dataRetentionService.js new file mode 100644 index 0000000..91248c0 --- /dev/null +++ b/src/services/dataRetentionService.js @@ -0,0 +1,336 @@ +const { getPrisma } = require('../config/prisma'); +const chalk = require('../utils/colors'); + +/** + * Data Retention Service + * + * Manages data retention by: + * 1. Keeping all data points within the retention period + * 2. For data older than retention period, minimizing data points + * by keeping only important ones (min, max, and strategic samples) + */ +class DataRetentionService { + /** + * Get data retention settings + */ + async getRetentionSettings() { + try { + const prisma = getPrisma(); + const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + return settings?.dataRetentionDays || 30; + } catch (error) { + console.error(chalk.red('Error getting retention settings:'), error.message); + return 30; // Default to 30 days + } + } + + /** + * Process data retention for a specific target + * Optimized strategy: + * - Last 30 days: Keep all raw data (for 1H, 24H, 7D, 30D graphs) + * - 31-90 days: Aggregate to hourly buckets (keep 1 point per hour) + * - 90+ days: Aggregate to daily buckets (keep 1 point per day) + * - Statistics table always maintained for uptime calculations + */ + async processRetentionForTarget(targetId) { + try { + const prisma = getPrisma(); + const now = new Date(); + + // Define retention periods + const keepRawDays = 30; // Keep all raw data for last 30 days + const keepHourlyDays = 90; // Keep hourly aggregations for 31-90 days + + const rawCutoff = new Date(now); + rawCutoff.setDate(rawCutoff.getDate() - keepRawDays); + + const hourlyCutoff = new Date(now); + hourlyCutoff.setDate(hourlyCutoff.getDate() - keepHourlyDays); + + let totalDeleted = 0; + + // Step 1: Process 31-90 days range - aggregate to hourly buckets + const hourlyData = await prisma.pingResult.findMany({ + where: { + targetId: targetId, + timestamp: { + gte: hourlyCutoff, + lt: rawCutoff, + }, + }, + orderBy: { timestamp: 'asc' }, + }); + + if (hourlyData.length > 0) { + // Group by hour + const hourlyBuckets = new Map(); + hourlyData.forEach(row => { + const hourKey = new Date(row.timestamp); + hourKey.setMinutes(0, 0, 0); + const key = hourKey.toISOString(); + + if (!hourlyBuckets.has(key)) { + hourlyBuckets.set(key, []); + } + hourlyBuckets.get(key).push(row); + }); + + // For each hour, keep only representative points (min, max, first, last, status changes) + const idsToKeep = new Set(); + + for (const [hourKey, hourData] of hourlyBuckets.entries()) { + if (hourData.length === 0) continue; + + // Always keep first and last of the hour + idsToKeep.add(hourData[0].id); + idsToKeep.add(hourData[hourData.length - 1].id); + + // Keep min and max response times + const withResponseTime = hourData.filter(d => d.responseTime !== null); + if (withResponseTime.length > 0) { + const minPoint = withResponseTime.reduce((min, d) => + d.responseTime < min.responseTime ? d : min + ); + const maxPoint = withResponseTime.reduce((max, d) => + d.responseTime > max.responseTime ? d : max + ); + idsToKeep.add(minPoint.id); + idsToKeep.add(maxPoint.id); + } + + // Keep status change points + for (let i = 1; i < hourData.length; i++) { + if (hourData[i].success !== hourData[i - 1].success) { + idsToKeep.add(hourData[i - 1].id); + idsToKeep.add(hourData[i].id); + } + } + + // If hour has many points, sample evenly (keep ~5-10 points per hour) + if (hourData.length > 10) { + const sampleRate = Math.max(1, Math.floor(hourData.length / 8)); + for (let i = 0; i < hourData.length; i += sampleRate) { + idsToKeep.add(hourData[i].id); + } + } else { + // Keep all if less than 10 points + hourData.forEach(row => idsToKeep.add(row.id)); + } + } + + // Delete points not in keep set + const idsToDelete = hourlyData + .filter(row => !idsToKeep.has(row.id)) + .map(row => row.id); + + if (idsToDelete.length > 0) { + await prisma.pingResult.deleteMany({ + where: { id: { in: idsToDelete } }, + }); + totalDeleted += idsToDelete.length; + } + } + + // Step 2: Process 90+ days range - aggregate to daily buckets + const dailyData = await prisma.pingResult.findMany({ + where: { + targetId: targetId, + timestamp: { lt: hourlyCutoff }, + }, + orderBy: { timestamp: 'asc' }, + }); + + if (dailyData.length > 0) { + // Group by day + const dailyBuckets = new Map(); + dailyData.forEach(row => { + const dayKey = new Date(row.timestamp); + dayKey.setHours(0, 0, 0, 0); + const key = dayKey.toISOString().split('T')[0]; + + if (!dailyBuckets.has(key)) { + dailyBuckets.set(key, []); + } + dailyBuckets.get(key).push(row); + }); + + // For each day, keep only representative points + const idsToKeep = new Set(); + + for (const [dayKey, dayData] of dailyBuckets.entries()) { + if (dayData.length === 0) continue; + + // Always keep first and last of the day + idsToKeep.add(dayData[0].id); + idsToKeep.add(dayData[dayData.length - 1].id); + + // Keep min and max response times + const withResponseTime = dayData.filter(d => d.responseTime !== null); + if (withResponseTime.length > 0) { + const minPoint = withResponseTime.reduce((min, d) => + d.responseTime < min.responseTime ? d : min + ); + const maxPoint = withResponseTime.reduce((max, d) => + d.responseTime > max.responseTime ? d : max + ); + idsToKeep.add(minPoint.id); + idsToKeep.add(maxPoint.id); + } + + // Keep status change points + for (let i = 1; i < dayData.length; i++) { + if (dayData[i].success !== dayData[i - 1].success) { + idsToKeep.add(dayData[i - 1].id); + idsToKeep.add(dayData[i].id); + } + } + + // Sample evenly - keep ~3-5 points per day for very old data + if (dayData.length > 5) { + const sampleRate = Math.max(1, Math.floor(dayData.length / 4)); + for (let i = 0; i < dayData.length; i += sampleRate) { + idsToKeep.add(dayData[i].id); + } + } else { + // Keep all if less than 5 points + dayData.forEach(row => idsToKeep.add(row.id)); + } + } + + // Delete points not in keep set + const idsToDelete = dailyData + .filter(row => !idsToKeep.has(row.id)) + .map(row => row.id); + + if (idsToDelete.length > 0) { + await prisma.pingResult.deleteMany({ + where: { id: { in: idsToDelete } }, + }); + totalDeleted += idsToDelete.length; + } + } + + if (totalDeleted > 0) { + console.log(chalk.yellow(`⊘ Processed retention for target ${targetId}: deleted ${totalDeleted} old data points`)); + } + + return { processed: hourlyData.length + dailyData.length, deleted: totalDeleted }; + } catch (error) { + console.error(chalk.red(`Error processing retention for target ${targetId}:`), error.message); + return { processed: 0, deleted: 0, error: error.message }; + } + } + + /** + * Process retention for all targets + */ + async processRetentionForAllTargets() { + try { + const prisma = getPrisma(); + const targets = await prisma.target.findMany(); + + let totalProcessed = 0; + let totalDeleted = 0; + + for (const target of targets) { + const result = await this.processRetentionForTarget(target.id); + totalProcessed += result.processed || 0; + totalDeleted += result.deleted || 0; + } + + if (totalDeleted > 0) { + console.log(chalk.green(`βœ“ Data retention complete: processed ${totalProcessed} points, deleted ${totalDeleted} redundant points`)); + } + + return { totalProcessed, totalDeleted }; + } catch (error) { + console.error(chalk.red('Error processing retention for all targets:'), error.message); + throw error; + } + } + + /** + * Clean up data older than retention period (hard delete) + * This is a more aggressive cleanup that removes data entirely + */ + async cleanupOldData() { + try { + const retentionDays = await this.getRetentionSettings(); + const prisma = getPrisma(); + + const cutoffDate = new Date(); + cutoffDate.setDate(cutoffDate.getDate() - retentionDays); + + // Delete all data older than retention period + const result = await prisma.pingResult.deleteMany({ + where: { timestamp: { lt: cutoffDate } }, + }); + + if (result.count > 0) { + console.log(chalk.yellow(`⊘ Cleaned up ${result.count} data points older than ${retentionDays} days`)); + } + + return { deleted: result.count }; + } catch (error) { + console.error(chalk.red('Error cleaning up old data:'), error.message); + throw error; + } + } + + /** + * Limit total ping results per target to optimize database performance + * Keeps the most recent N results per target + */ + async limitPingResultsPerTarget(maxResultsPerTarget = 10000) { + try { + const prisma = getPrisma(); + const targets = await prisma.target.findMany(); + let totalDeleted = 0; + + for (const target of targets) { + // Count total ping results for this target + const count = await prisma.pingResult.count({ + where: { targetId: target.id }, + }); + + if (count > maxResultsPerTarget) { + // Get the oldest results to delete + const toDelete = count - maxResultsPerTarget; + + // Get the timestamp of the Nth oldest result (where N = maxResultsPerTarget) + const oldestToKeep = await prisma.pingResult.findMany({ + where: { targetId: target.id }, + orderBy: { timestamp: 'desc' }, + take: maxResultsPerTarget, + skip: 0, + }); + + if (oldestToKeep.length > 0) { + const cutoffTimestamp = oldestToKeep[oldestToKeep.length - 1].timestamp; + + // Delete all results older than the cutoff + const result = await prisma.pingResult.deleteMany({ + where: { + targetId: target.id, + timestamp: { lt: cutoffTimestamp }, + }, + }); + + totalDeleted += result.count; + } + } + } + + if (totalDeleted > 0) { + console.log(chalk.yellow(`⊘ Limited ping results: deleted ${totalDeleted} old data points`)); + } + + return { deleted: totalDeleted }; + } catch (error) { + console.error(chalk.red('Error limiting ping results:'), error.message); + throw error; + } + } +} + +module.exports = new DataRetentionService(); diff --git a/src/services/eventDetectionService.js b/src/services/eventDetectionService.js new file mode 100644 index 0000000..5b3e4f7 --- /dev/null +++ b/src/services/eventDetectionService.js @@ -0,0 +1,566 @@ +const { getPrisma } = require('../config/prisma'); +const IncidentService = require('./incidentService'); +const chalk = require('../utils/colors'); +const { v4: uuidv4 } = require('uuid'); + +class EventDetectionService { + constructor() { + this.prisma = null; + this.incidentService = null; + this.activeIncidents = new Map(); // Track incidents created by events to avoid duplicates + } + + /** + * Initialize the service + */ + async initialize() { + this.prisma = getPrisma(); + this.incidentService = new IncidentService(this.prisma); + } + + /** + * Evaluate all enabled event rules and create incidents if conditions are met + */ + async evaluateRules(context = {}) { + try { + if (!this.prisma) { + await this.initialize(); + } + + const rules = await this.prisma.eventRule.findMany({ + where: { enabled: true }, + }); + + for (const rule of rules) { + try { + const shouldTrigger = await this.evaluateRule(rule, context); + + if (shouldTrigger) { + await this.triggerRule(rule, context); + } else { + // Check if we should auto-resolve incidents created by this rule + await this.checkAutoResolve(rule, context); + } + } catch (error) { + console.error(chalk.red(`Error evaluating rule ${rule.name}:`), error.message); + } + } + } catch (error) { + console.error(chalk.red('Error evaluating event rules:'), error.message); + } + } + + /** + * Evaluate a single rule to see if it should trigger + */ + async evaluateRule(rule, context) { + const { eventType } = rule; + // Parse conditions from JSON string if needed and attach to rule for use in evaluation methods + if (typeof rule.conditions === 'string') { + try { + rule.conditions = JSON.parse(rule.conditions); + } catch (e) { + console.error(chalk.red(`Error parsing conditions for rule ${rule.name}:`), e.message); + return false; + } + } + + switch (eventType) { + case 'monitor_down': + return await this.evaluateMonitorDown(rule, context); + case 'monitor_up': + return await this.evaluateMonitorUp(rule, context); + case 'multiple_monitors_down': + return await this.evaluateMultipleMonitorsDown(rule, context); + case 'monitor_response_time': + return await this.evaluateResponseTime(rule, context); + case 'uptime_threshold': + return await this.evaluateUptimeThreshold(rule, context); + case 'custom_condition': + return await this.evaluateCustomCondition(rule, context); + default: + console.warn(chalk.yellow(`Unknown event type: ${eventType}`)); + return false; + } + } + + /** + * Evaluate monitor down condition + */ + async evaluateMonitorDown(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { targetId, targetIds, targetGroups } = conditions; + + // If context has a specific target, check if it matches + if (context.targetId) { + // Check if this target is in the list + if (targetIds && Array.isArray(targetIds) && targetIds.includes(context.targetId)) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'down'; + } + // Legacy support for single targetId + if (targetId && context.targetId === targetId) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'down'; + } + if (targetGroups && context.targetGroup) { + if (targetGroups.includes(context.targetGroup)) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'down'; + } + } + } + + // Otherwise check all matching targets + // Prioritize targetIds array (new format) + if (targetIds && Array.isArray(targetIds) && targetIds.length > 0) { + for (const id of targetIds) { + const status = await this.getTargetStatus(id); + if (status === 'down') return true; + } + } + // Legacy support for single targetId + else if (targetId) { + const status = await this.getTargetStatus(targetId); + return status === 'down'; + } + + if (targetGroups && targetGroups.length > 0) { + const targets = await this.prisma.target.findMany({ + where: { group: { in: targetGroups }, enabled: true }, + }); + + for (const target of targets) { + const status = await this.getTargetStatus(target._id); + if (status === 'down') return true; + } + } + + return false; + } + + /** + * Evaluate monitor up condition (for auto-resolve) + */ + async evaluateMonitorUp(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { targetId, targetIds, targetGroups } = conditions; + + if (context.targetId) { + // Check if this target is in the list + if (targetIds && Array.isArray(targetIds) && targetIds.includes(context.targetId)) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'up'; + } + // Legacy support for single targetId + if (targetId && context.targetId === targetId) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'up'; + } + if (targetGroups && context.targetGroup) { + if (targetGroups.includes(context.targetGroup)) { + const status = context.status || await this.getTargetStatus(context.targetId); + return status === 'up'; + } + } + } + + return false; + } + + /** + * Evaluate multiple monitors down condition + */ + async evaluateMultipleMonitorsDown(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { targetIds, targetGroups, count, operator = 'gte' } = conditions; + + let downCount = 0; + const targetsToCheck = []; + + if (targetIds && targetIds.length > 0) { + const targets = await this.prisma.target.findMany({ + where: { id: { in: targetIds }, enabled: true }, + }); + targetsToCheck.push(...targets); + } + + if (targetGroups && targetGroups.length > 0) { + const targets = await this.prisma.target.findMany({ + where: { group: { in: targetGroups }, enabled: true }, + }); + targetsToCheck.push(...targets); + } + + for (const target of targetsToCheck) { + const status = await this.getTargetStatus(target._id); + if (status === 'down') { + downCount++; + } + } + + if (operator === 'gte') { + return downCount >= count; + } else if (operator === 'eq') { + return downCount === count; + } else if (operator === 'gt') { + return downCount > count; + } + + return false; + } + + /** + * Evaluate response time condition + */ + async evaluateResponseTime(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { targetId, threshold, operator = 'gt' } = conditions; + + if (!context.targetId || context.targetId !== targetId) { + return false; + } + + const responseTime = context.responseTime || await this.getLatestResponseTime(targetId); + if (responseTime === null) return false; + + if (operator === 'gt') { + return responseTime > threshold; + } else if (operator === 'gte') { + return responseTime >= threshold; + } else if (operator === 'lt') { + return responseTime < threshold; + } else if (operator === 'lte') { + return responseTime <= threshold; + } + + return false; + } + + /** + * Evaluate uptime threshold condition + */ + async evaluateUptimeThreshold(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { targetId, threshold, period = '24h' } = conditions; + + if (!targetId) return false; + + const uptime = await this.getUptimePercentage(targetId, period); + if (uptime === null) return false; + + return uptime < threshold; + } + + /** + * Evaluate custom condition (JavaScript expression) + */ + async evaluateCustomCondition(rule, context) { + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return false; + } + } + const { expression } = conditions; + + if (!expression) return false; + + try { + // Create a safe evaluation context + const evalContext = { + targetId: context.targetId, + status: context.status, + responseTime: context.responseTime, + target: context.target, + getTargetStatus: async (id) => await this.getTargetStatus(id), + getLatestResponseTime: async (id) => await this.getLatestResponseTime(id), + getUptimePercentage: async (id, period) => await this.getUptimePercentage(id, period), + }; + + // Evaluate the expression (in a limited way - be careful with this) + // Note: Using eval is dangerous, but for admin-controlled rules it's acceptable + const result = await eval(`(async () => { ${expression} })()`); + return Boolean(result); + } catch (error) { + console.error(chalk.red(`Error evaluating custom condition for rule ${rule.name}:`), error.message); + return false; + } + } + + /** + * Trigger a rule and create an incident + */ + async triggerRule(rule, context) { + try { + // Check if we already created an incident for this rule + const incidentKey = `${rule._id}_${this.getContextKey(context)}`; + if (this.activeIncidents.has(incidentKey)) { + return; // Already created + } + + // Check cooldown period + if (rule.cooldownMinutes) { + const lastTrigger = this.getLastTriggerTime(rule._id); + if (lastTrigger && (Date.now() - lastTrigger) < (rule.cooldownMinutes * 60 * 1000)) { + return; // Still in cooldown + } + } + + // Build incident data from rule template + const incidentData = { + title: this.interpolateTemplate(rule.incidentTitle, context), + description: this.interpolateTemplate(rule.incidentDescription, context), + status: rule.incidentStatus || 'investigating', + severity: rule.incidentSeverity || 'major', + affectedServices: await this.getAffectedServices(rule, context), + }; + + const result = await this.incidentService.createIncident(incidentData); + + if (result.success) { + // Track this incident + this.activeIncidents.set(incidentKey, { + incidentId: result.incidentId, + ruleId: rule._id, + createdAt: Date.now(), + }); + + // Store last trigger time + this.setLastTriggerTime(rule._id, Date.now()); + + console.log(chalk.green(`βœ“ Event rule "${rule.name}" triggered, incident created: ${result.incidentId}`)); + } + } catch (error) { + console.error(chalk.red(`Error triggering rule ${rule.name}:`), error.message); + } + } + + /** + * Check if we should auto-resolve incidents created by a rule + */ + async checkAutoResolve(rule, context) { + if (!rule.autoResolve) return; + + const incidentKey = `${rule._id}_${this.getContextKey(context)}`; + const activeIncident = this.activeIncidents.get(incidentKey); + + if (!activeIncident) return; + + // Check if condition is now false (e.g., monitor is back up) + const conditionMet = await this.evaluateRule(rule, context); + + if (!conditionMet) { + // Condition is no longer met, resolve the incident + try { + const incident = await this.incidentService.getIncidentById(activeIncident.incidentId); + if (incident && incident.status !== 'resolved') { + await this.incidentService.updateIncident(activeIncident.incidentId, { + status: 'resolved', + updateMessage: rule.autoResolveMessage || 'Service restored - automatically resolved by event detection system', + }); + + // Remove from active incidents + this.activeIncidents.delete(incidentKey); + + console.log(chalk.green(`βœ“ Auto-resolved incident ${activeIncident.incidentId} for rule "${rule.name}"`)); + } + } catch (error) { + console.error(chalk.red(`Error auto-resolving incident:`), error.message); + } + } + } + + /** + * Get target status + */ + async getTargetStatus(targetId) { + const monitorService = require('./monitorService'); + return monitorService.getTargetStatus(targetId); + } + + /** + * Get latest response time for a target + */ + async getLatestResponseTime(targetId) { + try { + const result = await this.prisma.pingResult.findFirst({ + where: { targetId }, + orderBy: { timestamp: 'desc' }, + }); + + return result?.responseTime || null; + } catch (error) { + return null; + } + } + + /** + * Get uptime percentage for a target over a period + */ + async getUptimePercentage(targetId, period = '24h') { + try { + const hours = this.parsePeriod(period); + const since = new Date(Date.now() - hours * 60 * 60 * 1000); + + const results = await this.prisma.pingResult.findMany({ + where: { targetId, timestamp: { gte: since } }, + }); + + if (results.length === 0) return null; + + const successful = results.filter(r => r.success).length; + return (successful / results.length) * 100; + } catch (error) { + return null; + } + } + + /** + * Parse period string (e.g., "24h", "7d") to hours + */ + parsePeriod(period) { + const match = period.match(/^(\d+)([hd])$/); + if (!match) return 24; // Default to 24 hours + + const value = parseInt(match[1]); + const unit = match[2]; + + return unit === 'd' ? value * 24 : value; + } + + /** + * Get affected services for an incident + */ + async getAffectedServices(rule, context) { + const services = []; + + if (context.target) { + services.push(context.target.name); + } else if (context.targetId) { + const target = await this.prisma.target.findUnique({ where: { id: context.targetId } }); + if (target) { + services.push(target.name); + } + } + + let conditions = rule.conditions; + if (typeof conditions === 'string') { + try { + conditions = JSON.parse(conditions); + } catch (e) { + return services; + } + } + + if (conditions.targetIds) { + for (const id of conditions.targetIds) { + const target = await this.prisma.target.findUnique({ where: { id } }); + if (target && !services.includes(target.name)) { + services.push(target.name); + } + } + } + + return services; + } + + /** + * Interpolate template string with context variables + */ + interpolateTemplate(template, context) { + if (!template) return ''; + + let result = template; + + // Replace {{variable}} with context values + result = result.replace(/\{\{target\.name\}\}/g, context.target?.name || 'Unknown'); + result = result.replace(/\{\{target\.host\}\}/g, context.target?.host || 'Unknown'); + result = result.replace(/\{\{status\}\}/g, context.status || 'unknown'); + result = result.replace(/\{\{responseTime\}\}/g, context.responseTime || 'N/A'); + + return result; + } + + /** + * Get context key for tracking incidents + */ + getContextKey(context) { + if (context.targetId) { + return context.targetId; + } + return 'default'; + } + + /** + * Get last trigger time for a rule + */ + getLastTriggerTime(ruleId) { + const key = `lastTrigger_${ruleId}`; + return this[key] || null; + } + + /** + * Set last trigger time for a rule + */ + setLastTriggerTime(ruleId, timestamp) { + const key = `lastTrigger_${ruleId}`; + this[key] = timestamp; + } + + /** + * Clean up resolved incidents from tracking + */ + async cleanupResolvedIncidents() { + try { + for (const [key, incident] of this.activeIncidents.entries()) { + const incidentData = await this.incidentService.getIncidentById(incident.incidentId); + if (incidentData && incidentData.status === 'resolved') { + this.activeIncidents.delete(key); + } + } + } catch (error) { + // Silently fail + } + } +} + +module.exports = new EventDetectionService(); + diff --git a/src/services/faviconService.js b/src/services/faviconService.js new file mode 100644 index 0000000..8c76a9d --- /dev/null +++ b/src/services/faviconService.js @@ -0,0 +1,307 @@ +const axios = require('axios'); + +class FaviconService { + /** + * Get favicon for a URL + * Tries multiple methods to find the favicon + * @param {string} url - The URL to get favicon from (e.g., https://example.com) + * @returns {Promise} - Base64 encoded favicon data or null if not found + */ + async getFavicon(url, options = {}) { + if (!url) return null; + + try { + // Normalize URL + const urlObj = new URL(url); + const baseUrl = `${urlObj.protocol}//${urlObj.host}`; + + // Method 1: Try /favicon.ico + const faviconUrl = `${baseUrl}/favicon.ico`; + const faviconData = await this.fetchFaviconAsBase64(faviconUrl); + if (faviconData) { + return faviconData; + } + + // Method 2: Try fetching HTML and looking for favicon link tag + const htmlFavicon = await this.getFaviconFromHtml(baseUrl, options); + if (htmlFavicon) { + return htmlFavicon; + } + + // Method 3: Use Google's favicon service as fallback + const googleFavicon = await this.getFaviconFromGoogle(baseUrl); + if (googleFavicon) { + return googleFavicon; + } + + return null; + } catch (error) { + console.error(`Error getting favicon for ${url}:`, error.message); + return null; + } + } + + /** + * Fetch favicon file and convert to base64 + */ + async fetchFaviconAsBase64(url) { + try { + const response = await axios.get(url, { + timeout: 5000, + responseType: 'arraybuffer', + validateStatus: (status) => status < 400, + maxRedirects: 5, + }); + + if (response.status === 200 && response.data && response.data.length > 0) { + const base64 = Buffer.from(response.data).toString('base64'); + const mimeType = this.getMimeType(response.headers['content-type']); + return `data:${mimeType};base64,${base64}`; + } + return null; + } catch (error) { + return null; + } + } + + /** + * Parse HTML and extract favicon link + */ + async getFaviconFromHtml(baseUrl, options = {}) { + try { + const axiosConfig = { + timeout: options.timeout || 5000, + validateStatus: (status) => status < 400, + maxRedirects: options.maxRedirects || 5, + }; + + // Handle SSL/TLS options + if (options.ignoreSsl === true) { + const httpsAgent = require('https').Agent({ rejectUnauthorized: false }); + const httpAgent = require('http').Agent({ rejectUnauthorized: false }); + axiosConfig.httpsAgent = httpsAgent; + axiosConfig.httpAgent = httpAgent; + } + + // Handle authentication + if (options.auth) { + if (options.auth.type === 'basic') { + axiosConfig.auth = { + username: options.auth.username, + password: options.auth.password, + }; + } else if (options.auth.type === 'bearer') { + axiosConfig.headers = { + 'Authorization': `Bearer ${options.auth.token}`, + }; + } + } + + const response = await axios.get(baseUrl, axiosConfig); + + if (response.status !== 200 || !response.data) { + return null; + } + + const html = response.data; + + // Extract all link tags with rel containing icon + const linkMatches = html.matchAll(/]*>/gi); + const faviconLinks = []; + + for (const linkMatch of linkMatches) { + const linkTag = linkMatch[0]; + const relMatch = linkTag.match(/rel=["']([^"']+)["']/i); + if (relMatch && /icon/i.test(relMatch[1])) { + const hrefMatch = linkTag.match(/href=["']([^"']+)["']/i); + if (hrefMatch) { + faviconLinks.push({ + rel: relMatch[1].toLowerCase(), + href: hrefMatch[1], + priority: this.getFaviconPriority(relMatch[1]) + }); + } + } + } + + // Sort by priority (higher priority first) + faviconLinks.sort((a, b) => b.priority - a.priority); + + // Try each favicon in priority order + for (const link of faviconLinks) { + const iconUrl = this.resolveUrl(link.href, baseUrl); + const faviconData = await this.fetchFaviconAsBase64(iconUrl); + if (faviconData) { + return faviconData; + } + } + + return null; + } catch (error) { + return null; + } + } + + /** + * Get favicon URL from HTML (returns URL string instead of base64) + * Useful for storing just the URL + */ + async getFaviconUrlFromHtml(baseUrl, options = {}) { + try { + const axiosConfig = { + timeout: options.timeout || 5000, + validateStatus: (status) => status < 400, + maxRedirects: options.maxRedirects || 5, + }; + + // Handle SSL/TLS options + if (options.ignoreSsl === true) { + const httpsAgent = require('https').Agent({ rejectUnauthorized: false }); + const httpAgent = require('http').Agent({ rejectUnauthorized: false }); + axiosConfig.httpsAgent = httpsAgent; + axiosConfig.httpAgent = httpAgent; + } + + // Handle authentication + if (options.auth) { + if (options.auth.type === 'basic') { + axiosConfig.auth = { + username: options.auth.username, + password: options.auth.password, + }; + } else if (options.auth.type === 'bearer') { + axiosConfig.headers = { + 'Authorization': `Bearer ${options.auth.token}`, + }; + } + } + + const response = await axios.get(baseUrl, axiosConfig); + + if (response.status !== 200 || !response.data) { + return null; + } + + const html = response.data; + + // Extract all link tags with rel containing icon + const linkMatches = html.matchAll(/]*>/gi); + const faviconLinks = []; + + for (const linkMatch of linkMatches) { + const linkTag = linkMatch[0]; + const relMatch = linkTag.match(/rel=["']([^"']+)["']/i); + if (relMatch && /icon/i.test(relMatch[1])) { + const hrefMatch = linkTag.match(/href=["']([^"']+)["']/i); + if (hrefMatch) { + faviconLinks.push({ + rel: relMatch[1].toLowerCase(), + href: hrefMatch[1], + priority: this.getFaviconPriority(relMatch[1]) + }); + } + } + } + + // Sort by priority (higher priority first) + faviconLinks.sort((a, b) => b.priority - a.priority); + + // Return the highest priority favicon URL + if (faviconLinks.length > 0) { + return this.resolveUrl(faviconLinks[0].href, baseUrl); + } + + return null; + } catch (error) { + return null; + } + } + + /** + * Use Google's favicon service as fallback + */ + async getFaviconFromGoogle(baseUrl) { + try { + const urlObj = new URL(baseUrl); + const domain = urlObj.host; + const googleFaviconUrl = `https://www.google.com/s2/favicons?sz=64&domain=${domain}`; + + const response = await axios.get(googleFaviconUrl, { + timeout: 5000, + responseType: 'arraybuffer', + validateStatus: (status) => status < 400, + maxRedirects: 5, + }); + + if (response.status === 200 && response.data && response.data.length > 0) { + const base64 = Buffer.from(response.data).toString('base64'); + return `data:image/png;base64,${base64}`; + } + + return null; + } catch (error) { + return null; + } + } + + /** + * Resolve relative URLs to absolute + */ + resolveUrl(url, baseUrl) { + // Remove query strings and fragments for matching + const cleanUrl = url.split('?')[0].split('#')[0]; + + if (cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://')) { + return url; // Return original with query string if present + } + + try { + const urlObj = new URL(baseUrl); + if (cleanUrl.startsWith('/')) { + return `${urlObj.protocol}//${urlObj.host}${url}`; + } + + // Handle relative paths + const basePath = urlObj.pathname || '/'; + const baseDir = basePath.substring(0, basePath.lastIndexOf('/') + 1); + return `${urlObj.protocol}//${urlObj.host}${baseDir}${url}`; + } catch (error) { + // If URL parsing fails, try simple string concatenation + if (cleanUrl.startsWith('/')) { + return baseUrl.replace(/\/$/, '') + url; + } + return baseUrl.replace(/\/$/, '') + '/' + url; + } + } + + /** + * Get MIME type from content-type header + */ + getMimeType(contentType) { + if (!contentType) return 'image/x-icon'; + + const type = contentType.split(';')[0].trim(); + if (type.includes('svg')) return 'image/svg+xml'; + if (type.includes('png')) return 'image/png'; + if (type.includes('jpeg') || type.includes('jpg')) return 'image/jpeg'; + if (type.includes('gif')) return 'image/gif'; + if (type.includes('webp')) return 'image/webp'; + + return 'image/x-icon'; + } + + /** + * Get priority for favicon rel types (higher = better) + */ + getFaviconPriority(rel) { + const relLower = rel.toLowerCase(); + if (relLower.includes('apple-touch-icon')) return 5; + if (relLower.includes('icon') && relLower.includes('mask')) return 4; + if (relLower === 'icon') return 3; + if (relLower.includes('shortcut') && relLower.includes('icon')) return 2; + if (relLower.includes('icon')) return 1; + return 0; + } +} + +module.exports = new FaviconService(); diff --git a/src/services/gatewayService.js b/src/services/gatewayService.js new file mode 100644 index 0000000..b8185c4 --- /dev/null +++ b/src/services/gatewayService.js @@ -0,0 +1,85 @@ +const { gateway4async, gateway6async } = require('default-gateway'); +const chalk = require('../utils/colors'); + +class GatewayService { + constructor() { + this.gateway4 = null; + this.gateway6 = null; + this.interface4 = null; + this.interface6 = null; + } + + /** + * Detect the default IPv4 gateway + */ + async detectGateway4() { + try { + const result = await gateway4async(); + if (result && result.gateway) { + this.gateway4 = result.gateway; + this.interface4 = result.interface; + console.log( + chalk.green('βœ“ Detected IPv4 gateway:'), + `${this.gateway4} (${this.interface4})` + ); + return this.gateway4; + } + } catch (error) { + console.warn(chalk.yellow('⚠ Could not detect IPv4 gateway:'), error.message); + } + return null; + } + + /** + * Detect the default IPv6 gateway + */ + async detectGateway6() { + try { + const result = await gateway6async(); + if (result && result.gateway) { + this.gateway6 = result.gateway; + this.interface6 = result.interface; + console.log( + chalk.green('βœ“ Detected IPv6 gateway:'), + `${this.gateway6} (${this.interface6})` + ); + return this.gateway6; + } + } catch (error) { + console.warn(chalk.yellow('⚠ Could not detect IPv6 gateway:'), error.message); + } + return null; + } + + /** + * Detect both IPv4 and IPv6 gateways + */ + async detectAllGateways() { + await Promise.all([this.detectGateway4(), this.detectGateway6()]); + return { + gateway4: this.gateway4, + gateway6: this.gateway6, + interface4: this.interface4, + interface6: this.interface6, + }; + } + + /** + * Get the primary gateway (IPv4 preferably) + */ + getPrimaryGateway() { + return this.gateway4 || this.gateway6 || null; + } + + /** + * Get all detected gateways + */ + getAllGateways() { + const gateways = []; + if (this.gateway4) gateways.push({ ip: this.gateway4, version: 4, interface: this.interface4 }); + if (this.gateway6) gateways.push({ ip: this.gateway6, version: 6, interface: this.interface6 }); + return gateways; + } +} + +module.exports = new GatewayService(); diff --git a/src/services/incidentService.js b/src/services/incidentService.js new file mode 100644 index 0000000..c5395a2 --- /dev/null +++ b/src/services/incidentService.js @@ -0,0 +1,262 @@ +const chalk = require('../utils/colors'); + +class IncidentService { + constructor(prisma) { + this.prisma = prisma; + } + + async createIncident(data) { + try { + // Ensure isScheduled is a boolean, not a string or date + const isScheduled = (data.isScheduled === true || data.isScheduled === 'true') && data.scheduledStart; + const initialStatus = isScheduled && new Date(data.scheduledStart) > new Date() + ? 'scheduled' + : (data.status || 'investigating'); + + const incident = await this.prisma.incident.create({ + data: { + title: data.title, + description: data.description, + status: initialStatus, // investigating, identified, monitoring, resolved, scheduled + severity: data.severity || 'major', // minor, major, critical + affectedServices: data.affectedServices || [], + isScheduled: Boolean(isScheduled), + scheduledStart: data.scheduledStart ? new Date(data.scheduledStart) : null, + scheduledEnd: data.scheduledEnd ? new Date(data.scheduledEnd) : null, + updates: [ + { + message: data.description, + timestamp: new Date().toISOString(), + status: initialStatus, + }, + ], + resolvedAt: data.status === 'resolved' ? new Date() : null, + }, + }); + + // Send external notifications (non-blocking) + setImmediate(async () => { + try { + const notificationService = require('./notificationService'); + await notificationService.notifyIncident(incident, false); + } catch (error) { + // Silently fail - notifications are not critical + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow('Notification error for incident:'), error.message); + } + } + }); + + return { success: true, incidentId: incident.id, incident }; + } catch (error) { + console.error(chalk.red('Error creating incident:'), error.message); + throw error; + } + } + + async getIncidents(filters = {}) { + try { + const where = {}; + if (filters.status) where.status = filters.status; + if (filters.severity) where.severity = filters.severity; + + const incidents = await this.prisma.incident.findMany({ + where, + orderBy: { createdAt: 'desc' }, + }); + + return incidents; + } catch (error) { + console.error(chalk.red('Error fetching incidents:'), error.message); + throw error; + } + } + + async getIncidentById(incidentId) { + try { + const incident = await this.prisma.incident.findUnique({ + where: { id: incidentId }, + }); + + return incident; + } catch (error) { + console.error(chalk.red('Error fetching incident:'), error.message); + throw error; + } + } + + async updateIncident(incidentId, data) { + try { + const updateData = {}; + + if (data.title !== undefined) updateData.title = data.title; + if (data.description !== undefined) updateData.description = data.description; + if (data.status !== undefined) updateData.status = data.status; + if (data.severity !== undefined) updateData.severity = data.severity; + if (data.affectedServices !== undefined) updateData.affectedServices = data.affectedServices; + if (data.isScheduled !== undefined) updateData.isScheduled = Boolean(data.isScheduled === true || data.isScheduled === 'true'); + if (data.scheduledStart !== undefined) updateData.scheduledStart = data.scheduledStart ? new Date(data.scheduledStart) : null; + if (data.scheduledEnd !== undefined) updateData.scheduledEnd = data.scheduledEnd ? new Date(data.scheduledEnd) : null; + + if (data.status === 'resolved') { + updateData.resolvedAt = new Date(); + } + + // Add update to the updates array + if (data.updateMessage) { + const existingIncident = await this.prisma.incident.findUnique({ + where: { id: incidentId }, + }); + + if (existingIncident) { + const updates = existingIncident.updates || []; + updates.push({ + message: data.updateMessage, + timestamp: new Date().toISOString(), + status: data.status || 'update', + }); + updateData.updates = updates; + } + } + + const result = await this.prisma.incident.update({ + where: { id: incidentId }, + data: updateData, + }); + + if (result) { + // Send external notifications (non-blocking) + setImmediate(async () => { + try { + const updatedIncident = await this.getIncidentById(incidentId); + if (updatedIncident) { + const notificationService = require('./notificationService'); + await notificationService.notifyIncident(updatedIncident, true); + } + } catch (error) { + // Silently fail - notifications are not critical + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow('Notification error for incident update:'), error.message); + } + } + }); + } + + return true; + } catch (error) { + if (error.code === 'P2025') { + // Record not found + return false; + } + console.error(chalk.red('Error updating incident:'), error.message); + throw error; + } + } + + async deleteIncident(incidentId) { + try { + await this.prisma.incident.delete({ + where: { id: incidentId }, + }); + return true; + } catch (error) { + if (error.code === 'P2025') { + // Record not found + return false; + } + console.error(chalk.red('Error deleting incident:'), error.message); + throw error; + } + } + + async getPublicIncidents() { + try { + // Return active incidents for the public status page + const incidents = await this.prisma.incident.findMany({ + where: { status: { not: 'resolved' } }, + orderBy: { createdAt: 'desc' }, + }); + + return incidents; + } catch (error) { + console.error(chalk.red('Error fetching public incidents:'), error.message); + throw error; + } + } + + /** + * Process scheduled incidents - activate them when start time arrives, resolve when end time passes + */ + async processScheduledIncidents() { + try { + const now = new Date(); + + // Find scheduled incidents that need to be activated (start time has passed, status is still 'scheduled') + const scheduledToActivate = await this.prisma.incident.findMany({ + where: { + isScheduled: true, + status: 'scheduled', + scheduledStart: { lte: now }, + }, + }); + + for (const incident of scheduledToActivate) { + // Activate the incident + await this.prisma.incident.update({ + where: { id: incident.id }, + data: { + status: 'investigating', + updates: [ + ...(incident.updates || []), + { + message: 'Scheduled maintenance window has started', + timestamp: now.toISOString(), + status: 'investigating', + }, + ], + }, + }); + console.log(chalk.green(`βœ“ Activated scheduled incident: ${incident.title}`)); + } + + // Find active scheduled incidents that should be resolved (end time has passed) + const scheduledToResolve = await this.prisma.incident.findMany({ + where: { + isScheduled: true, + status: { not: 'resolved' }, + scheduledEnd: { lte: now }, + }, + }); + + for (const incident of scheduledToResolve) { + // Resolve the incident + await this.prisma.incident.update({ + where: { id: incident.id }, + data: { + status: 'resolved', + resolvedAt: now, + updates: [ + ...(incident.updates || []), + { + message: 'Scheduled maintenance window has ended', + timestamp: now.toISOString(), + status: 'resolved', + }, + ], + }, + }); + console.log(chalk.green(`βœ“ Resolved scheduled incident: ${incident.title}`)); + } + + return { + activated: scheduledToActivate.length, + resolved: scheduledToResolve.length, + }; + } catch (error) { + console.error(chalk.red('Error processing scheduled incidents:'), error.message); + throw error; + } + } +} + +module.exports = IncidentService; diff --git a/src/services/monitorService.js b/src/services/monitorService.js new file mode 100644 index 0000000..d9b2ebd --- /dev/null +++ b/src/services/monitorService.js @@ -0,0 +1,683 @@ +const { getPrisma } = require('../config/prisma'); +const pingService = require('./pingService'); +const chalk = require('../utils/colors'); + +class MonitorService { + constructor() { + this.intervals = new Map(); + this.targetStatus = new Map(); // Track current status of targets + this.debugLogging = false; // Cache debug logging setting + this.debugLoggingChecked = false; // Track if we've checked the setting + this.lastAlertTime = new Map(); // Prevent alert spam + this.failureCount = new Map(); // Track consecutive failures for retry logic + this.downTimestamp = new Map(); // Track when monitor went down + this.notificationSent = new Map(); // Track if notification was sent for current down state + this.notificationTimers = new Map(); // Delay monitor notifications until the outage is sustained + this.notificationScheduling = new Map(); + this.monitorGeneration = new Map(); // Ignore results from monitors that were restarted + this.inFlight = new Map(); // Prevent overlapping pings without blocking restarted monitors + this.monitorTargets = new Map(); + this.notificationDelayMinutes = 5; + this.notificationDelayVersion = 0; + this.lastNotificationSentAt = new Map(); + } + + /** + * Start monitoring all enabled targets (non-blocking) + */ + startMonitoring() { + // Run in background to avoid blocking webserver startup + setImmediate(async () => { + try { + // Prime the delay before the first failures can be recorded. + try { + const notificationService = require('./notificationService'); + this.setNotificationDelayMinutes(await notificationService.getMonitorDownDelayMinutes()); + } catch (error) { + // Keep the safe five-minute default if settings are unavailable. + } + const prisma = getPrisma(); + const targets = await prisma.target.findMany({ where: { enabled: true } }); + + console.log(chalk.green(`βœ“ Starting monitor for ${targets.length} targets`)); + + // Set up monitoring intervals for all targets immediately + for (const target of targets) { + this.startTargetMonitor(target); + } + + // Ping all targets in background to get current status (non-blocking) + if (targets.length > 0) { + console.log(chalk.blue('β†ͺ Pinging all monitors to get current status (background)...')); + // Don't await - let it run in background + Promise.allSettled(targets.map(target => this.pingTarget(target, this.monitorGeneration.get((target.id || target._id).toString())))) + .then(() => { + console.log(chalk.green('βœ“ Initial ping complete, status updated')); + }) + .catch((error) => { + console.error(chalk.yellow('Some initial pings failed:'), error.message); + }); + } + } catch (error) { + console.error(chalk.red('Error starting monitoring:'), error.message); + } + }); + } + + /** + * Start monitoring a single target + */ + startTargetMonitor(target) { + // Support both Prisma's 'id' and legacy '_id' + const targetIdStr = (target.id || target._id).toString(); + const generation = (this.monitorGeneration.get(targetIdStr) || 0) + 1; + this.monitorGeneration.set(targetIdStr, generation); + this.monitorTargets.set(targetIdStr, target); + + // Clear existing interval if any + if (this.intervals.has(targetIdStr)) { + clearInterval(this.intervals.get(targetIdStr)); + // A restarted generation must not inherit a timer whose callback still + // carries the previous generation token. Keep the outage timestamp so a + // restart does not manufacture a fresh outage, then let the next ping + // schedule against the active delay. + this.clearNotificationTimer(targetIdStr); + this.notificationScheduling.delete(targetIdStr); + } + + // Status should already be set from initial ping in startMonitoring() + // If not, initialize to 'unknown' + if (!this.targetStatus.has(targetIdStr)) { + this.targetStatus.set(targetIdStr, 'unknown'); + } + + // Set up interval (initial ping already done in startMonitoring()) + const interval = setInterval(() => { + const currentTarget = this.monitorTargets.get(targetIdStr) || target; + this.pingTarget(currentTarget, generation); + }, (target.interval || 60) * 1000); + + this.intervals.set(targetIdStr, interval); + console.log(chalk.blue(`β†ͺ Monitoring ${target.name} every ${target.interval || 60}s`)); + } + + /** + * Replace the target metadata used by an active monitor without resetting + * its status, retry counters, or sustained-outage timer. Public visibility, + * labels, icons, and notification metadata can change while a service is + * down; those changes should not restart the outage clock. + */ + updateTargetReference(target) { + const targetId = target.id || target._id; + if (targetId === undefined || targetId === null) return; + const targetIdStr = targetId.toString(); + if (this.monitorTargets.has(targetIdStr)) { + this.monitorTargets.set(targetIdStr, target); + } + } + + /** + * Ping a target and store result (non-blocking) + */ + async pingTarget(target, expectedGeneration = null) { + const targetId = target.id || target._id; + const targetIdStr = targetId.toString(); + // Give direct/manual pings the same generation protection as interval + // pings. This also means a monitor started while a direct ping is in + // flight can invalidate that result safely. + if (!this.monitorGeneration.has(targetIdStr)) { + this.monitorGeneration.set(targetIdStr, 0); + } + // Calls made by an interval carry an explicit generation. Direct calls + // (for example a startup ping or an admin test) inherit the current one + // so a result cannot update a monitor after it has been restarted. + const pingGeneration = expectedGeneration ?? this.monitorGeneration.get(targetIdStr); + if (this.monitorGeneration.get(targetIdStr) !== pingGeneration) return; + const activePing = this.inFlight.get(targetIdStr); + if (activePing && activePing.generation === pingGeneration) return; + const pingToken = {}; + this.inFlight.set(targetIdStr, { generation: pingGeneration, token: pingToken }); + + try { + // Support both Prisma's 'id' and legacy '_id' + + // Check debug logging setting (cache it, check every 60 seconds) + if (!this.debugLoggingChecked || Date.now() - (this.debugLoggingLastCheck || 0) > 60000) { + try { + const prisma = getPrisma(); + const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } }); + this.debugLogging = settings?.debugLogging === true; + this.debugLoggingChecked = true; + this.debugLoggingLastCheck = Date.now(); + } catch (err) { + // If we can't check, default to false + this.debugLogging = false; + } + } + + // Ping is now non-blocking via worker threads + const result = await pingService.ping(target); + if (pingGeneration !== null && this.monitorGeneration.get(targetIdStr) !== pingGeneration) return; + + // Debug logging + if (this.debugLogging) { + const timestamp = new Date().toISOString(); + const status = result.success ? chalk.green('βœ“ UP') : chalk.red('βœ— DOWN'); + const responseTime = result.responseTime ? `${Math.round(result.responseTime)}ms` : 'N/A'; + const protocol = result.protocol || target.protocol || 'UNKNOWN'; + console.log(chalk.cyan(`[${timestamp}]`) + ` ${status} ${chalk.yellow(target.name)} (${target.host}:${target.port || 'default'}) - ${protocol} - ${responseTime}`); + if (result.error) { + console.log(chalk.gray(` Error: ${result.error}`)); + } + if (result.statusCode) { + console.log(chalk.gray(` Status Code: ${result.statusCode}`)); + } + } + + // Get current in-memory status (synchronous, fast) + const currentStatus = this.targetStatus.get(targetIdStr); + + // Determine status based on ping result and upside down mode + let pingSuccess = result.success; + if (target.upsideDown === true) { + pingSuccess = !pingSuccess; // Invert the status + } + + // Handle retry logic + const maxRetries = target.retries || 0; + let newStatus = 'unknown'; + let downtimeDuration = null; // Capture downtime duration for notification + let wasNotificationSent = false; + + if (pingSuccess) { + // Success - reset failure counter + this.failureCount.set(targetIdStr, 0); + newStatus = 'up'; + // Calculate downtime duration before clearing the timestamp + const downTime = this.downTimestamp.get(targetIdStr); + downtimeDuration = downTime ? Date.now() - downTime : null; + wasNotificationSent = this.notificationSent.get(targetIdStr) === true; + // Clear down timestamp and notification flag when coming back up + this.downTimestamp.delete(targetIdStr); + this.clearNotificationTimer(targetIdStr); + this.notificationSent.delete(targetIdStr); + } else { + // Failure - increment counter + const currentFailures = (this.failureCount.get(targetIdStr) || 0) + 1; + this.failureCount.set(targetIdStr, currentFailures); + + // Only mark as down if we've exceeded retry threshold + if (currentFailures > maxRetries) { + newStatus = 'down'; + // Track when monitor went down (only set once) + if (!this.downTimestamp.has(targetIdStr)) { + this.downTimestamp.set(targetIdStr, Date.now()); + } + this.scheduleDownNotification(target, targetIdStr, result.responseTime, pingGeneration); + } else { + // Still retrying, keep current status or mark as unknown + newStatus = currentStatus || 'unknown'; + } + } + + // Always update status immediately (in-memory, fast) + this.targetStatus.set(targetIdStr, newStatus); + + // Defer database operations to next tick to avoid blocking + setImmediate(async () => { + try { + // The monitor may have been disabled or restarted while the ping + // result was waiting for the event loop. Do not persist or emit + // status events from that stale generation. + if (this.monitorGeneration.get(targetIdStr) !== pingGeneration) return; + const prisma = getPrisma(); + const timestamp = new Date(); + + // Store ping result in database (non-blocking) + prisma.pingResult.create({ + data: { + targetId: targetId, + success: result.success, + responseTime: result.responseTime || null, + timestamp, + statusCode: result.statusCode || null, + error: result.error || null, + protocol: result.protocol || null, + }, + }).then(() => { + // Debug logging for successful DB write + if (this.debugLogging) { + console.log(chalk.gray(` β†’ Ping result saved to database`)); + } + }).catch(err => { + // Log DB errors to help diagnose issues + console.error(chalk.red(`βœ— DB write error for ${target.name}:`), err.message); + console.error(chalk.gray(' Error details:'), err); + }); + + // Update statistics (non-blocking) + this.updateStatistics(target, result).then(() => { + // Debug logging for successful statistics update + if (this.debugLogging) { + console.log(chalk.gray(` β†’ Statistics updated`)); + } + }).catch((err) => { + // Log statistics errors to help diagnose issues + console.error(chalk.red(`βœ— Statistics update error for ${target.name}:`), err.message); + console.error(chalk.gray(' Error details:'), err); + }); + + // Handle status changes + if (newStatus !== currentStatus && currentStatus !== 'unknown') { + if (newStatus === 'up') { + // Use downtime duration calculated before timestamp was deleted (captured in closure) + this.handleTargetUp(target, result.responseTime, downtimeDuration, wasNotificationSent).catch(err => { + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Alert error for ${target.name}:`), err.message); + } + }); + } + + // Evaluate event detection rules (non-blocking) + setImmediate(async () => { + try { + const eventDetectionService = require('./eventDetectionService'); + await eventDetectionService.evaluateRules({ + targetId: targetIdStr, + target: target, + status: newStatus, + responseTime: result.responseTime, + targetGroup: target.group, + }); + } catch (error) { + // Silently fail - event detection is not critical + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Event detection error for ${target.name}:`), error.message); + } + } + }); + } + } catch (error) { + // Silently handle errors to avoid blocking + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Error processing result for ${target.name}:`), error.message); + } + } + }); + } catch (error) { + console.error(chalk.red(`Error pinging ${target.name}:`), error.message); + } finally { + // A newer generation may already be pinging this target. Do not let an + // older worker completion clear the newer request's in-flight marker. + if (this.inFlight.get(targetIdStr)?.token === pingToken) { + this.inFlight.delete(targetIdStr); + } + } + } + + getNotificationDelayMs() { + return Math.max(1, this.notificationDelayMinutes || 5) * 60 * 1000; + } + + setNotificationDelayMinutes(value, options = {}) { + const parsed = Number.parseInt(value, 10); + const nextDelay = Number.isFinite(parsed) ? Math.min(1440, Math.max(1, parsed)) : 5; + const changed = nextDelay !== this.notificationDelayMinutes; + this.notificationDelayMinutes = nextDelay; + if (changed) { + this.notificationDelayVersion += 1; + if (options.reschedule !== false) this.rescheduleNotificationTimers(); + } + } + + getNotificationState(targetId) { + const id = targetId.toString ? targetId.toString() : String(targetId); + const downSince = this.downTimestamp.get(id) || null; + const downDurationMs = downSince ? Math.max(0, Date.now() - downSince) : 0; + return { + downSince: downSince ? new Date(downSince).toISOString() : null, + downDurationMs, + notificationDelayMinutes: this.notificationDelayMinutes, + notificationEligible: Boolean(downSince && downDurationMs >= this.getNotificationDelayMs()), + notificationSent: this.notificationSent.get(id) === true, + lastNotificationSentAt: this.lastNotificationSentAt.get(id) || null, + }; + } + + clearNotificationTimer(targetId) { + const timer = this.notificationTimers.get(targetId); + if (timer) clearTimeout(timer); + this.notificationTimers.delete(targetId); + } + + async scheduleDownNotification(target, targetIdStr, responseTime = null, expectedGeneration = null) { + if (expectedGeneration !== null && this.monitorGeneration.get(targetIdStr) !== expectedGeneration) return; + if (this.notificationSent.get(targetIdStr) || this.notificationTimers.has(targetIdStr) || this.notificationScheduling.has(targetIdStr)) return; + const schedulingGeneration = expectedGeneration ?? this.monitorGeneration.get(targetIdStr) ?? null; + this.notificationScheduling.set(targetIdStr, schedulingGeneration); + const delayVersionAtStart = this.notificationDelayVersion; + try { + let delayMinutes = this.notificationDelayMinutes; + try { + const notificationService = require('./notificationService'); + if (typeof notificationService.getMonitorDownDelayMinutes === 'function') { + delayMinutes = await notificationService.getMonitorDownDelayMinutes(); + } + } catch (error) { + // Keep scheduling with the safe in-memory default when the settings + // store is temporarily unavailable. The next outage check can pick + // up the persisted value once the database is healthy again. + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Notification settings lookup failed for ${target.name}:`), error.message); + } + } + // A settings update may have happened while the database lookup was in + // flight. Do not let an older lookup overwrite the newly selected global + // delay; use the current in-memory value in that case. + if (this.notificationDelayVersion === delayVersionAtStart) { + this.setNotificationDelayMinutes(delayMinutes, { reschedule: false }); + } + const downSince = this.downTimestamp.get(targetIdStr); + if (!downSince || this.notificationSent.get(targetIdStr)) return; + if ((this.monitorGeneration.get(targetIdStr) ?? null) !== schedulingGeneration) return; + const remaining = Math.max(0, downSince + this.getNotificationDelayMs() - Date.now()); + const timer = setTimeout(() => { + this.notificationTimers.delete(targetIdStr); + if ((this.monitorGeneration.get(targetIdStr) ?? null) !== schedulingGeneration) return; + if (this.targetStatus.get(targetIdStr) !== 'down' || !this.downTimestamp.has(targetIdStr) || this.notificationSent.get(targetIdStr)) return; + this.notificationSent.set(targetIdStr, true); + this.lastNotificationSentAt.set(targetIdStr, new Date().toISOString()); + const currentTarget = this.monitorTargets.get(targetIdStr) || target; + this.handleTargetDown(currentTarget, responseTime).catch(err => { + if (process.env.NODE_ENV === 'development') console.error(chalk.yellow(`Alert error for ${target.name}:`), err.message); + }); + }, remaining); + this.notificationTimers.set(targetIdStr, timer); + } catch (error) { + if (process.env.NODE_ENV === 'development') console.error(chalk.yellow(`Notification scheduling error for ${target.name}:`), error.message); + } finally { + if (this.notificationScheduling.get(targetIdStr) === schedulingGeneration) { + this.notificationScheduling.delete(targetIdStr); + } + } + } + + rescheduleNotificationTimers() { + for (const [targetIdStr, target] of this.monitorTargets.entries()) { + if (this.downTimestamp.has(targetIdStr) && !this.notificationSent.get(targetIdStr)) { + this.clearNotificationTimer(targetIdStr); + this.scheduleDownNotification(target, targetIdStr, null, this.monitorGeneration.get(targetIdStr) ?? null); + } + } + } + + /** + * Handle target going down + */ + async handleTargetDown(target, responseTime = null) { + const prisma = getPrisma(); + const targetId = target.id || target._id; + const targetIdStr = targetId.toString(); + const now = Date.now(); + const lastAlertTime = this.lastAlertTime.get(targetIdStr) || 0; + const alertCooldown = (process.env.ALERT_COOLDOWN || 300) * 1000; // 5 minutes default + + // Create alert + await prisma.alert.create({ + data: { + targetId: targetId, + type: 'down', + timestamp: new Date(), + message: `${target.name} is DOWN (${target.host} - ${target.protocol})`, + }, + }); + + // Log alert if cooldown passed + if (now - lastAlertTime > alertCooldown) { + this.lastAlertTime.set(targetIdStr, now); + console.log(chalk.red(`βœ— ${target.name} is DOWN`)); + } + + // Send external notifications (non-blocking) + setImmediate(async () => { + try { + const notificationService = require('./notificationService'); + await notificationService.notifyMonitorStatus(target, 'down', responseTime); + } catch (error) { + // Silently fail - notifications are not critical + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Notification error for ${target.name}:`), error.message); + } + } + }); + } + + /** + * Handle target coming back up + */ + async handleTargetUp(target, responseTime = null, downtimeDuration = null, notificationWasSent = null) { + const prisma = getPrisma(); + const targetId = target.id || target._id; + const shouldNotify = notificationWasSent === null + ? this.notificationSent.get(targetId.toString()) === true + : notificationWasSent === true; + + // Create alert + await prisma.alert.create({ + data: { + targetId: targetId, + type: 'up', + timestamp: new Date(), + message: `${target.name} is UP (${target.host} - ${target.protocol})`, + }, + }); + + // Log recovery + console.log(chalk.green(`βœ“ ${target.name} is UP`)); + + // A recovery notification is paired with a previously emitted outage + // notification. Short or otherwise unnotified outages stay silent while + // the internal alert history still records the state transition. + if (!shouldNotify) { + return { skipped: true, reason: 'Outage shorter than notification delay' }; + } + + // Send external notifications (non-blocking) + setImmediate(async () => { + try { + const notificationService = require('./notificationService'); + await notificationService.notifyMonitorStatus(target, 'up', responseTime, downtimeDuration); + } catch (error) { + // Silently fail - notifications are not critical + if (process.env.NODE_ENV === 'development') { + console.error(chalk.yellow(`Notification error for ${target.name}:`), error.message); + } + } + }); + } + + /** + * Update statistics for target + */ + async updateStatistics(target, pingResult) { + try { + const prisma = getPrisma(); + const targetId = target.id || target._id; + const today = new Date(); + today.setHours(0, 0, 0, 0); + + // Use upsert for atomic update or insert + const stats = await prisma.statistic.findUnique({ + where: { + targetId_date: { + targetId: targetId, + date: today, + }, + }, + }); + + if (stats) { + // Update existing stats + const newTotalPings = stats.totalPings + 1; + const newSuccessfulPings = pingResult.success ? stats.successfulPings + 1 : stats.successfulPings; + const newFailedPings = !pingResult.success ? stats.failedPings + 1 : stats.failedPings; + + await prisma.statistic.update({ + where: { + targetId_date: { + targetId: targetId, + date: today, + }, + }, + data: { + totalPings: newTotalPings, + successfulPings: newSuccessfulPings, + failedPings: newFailedPings, + uptime: (newSuccessfulPings / newTotalPings) * 100, + lastResponseTime: pingResult.responseTime || 0, + avgResponseTime: + (stats.avgResponseTime * stats.totalPings + (pingResult.responseTime || 0)) / newTotalPings, + }, + }); + } else { + // Create new stats + await prisma.statistic.create({ + data: { + targetId: targetId, + date: today, + totalPings: 1, + successfulPings: pingResult.success ? 1 : 0, + failedPings: pingResult.success ? 0 : 1, + uptime: pingResult.success ? 100 : 0, + lastResponseTime: pingResult.responseTime || 0, + avgResponseTime: pingResult.responseTime || 0, + }, + }); + } + } catch (error) { + // Handle unique constraint violation (race condition) - retry + if (error.code === 'P2002') { + try { + const prisma = getPrisma(); + const targetId = target.id || target._id; + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const existingStats = await prisma.statistic.findUnique({ + where: { + targetId_date: { + targetId: targetId, + date: today, + }, + }, + }); + + if (existingStats) { + const newTotalPings = existingStats.totalPings + 1; + const newSuccessfulPings = pingResult.success ? existingStats.successfulPings + 1 : existingStats.successfulPings; + const newFailedPings = !pingResult.success ? existingStats.failedPings + 1 : existingStats.failedPings; + + await prisma.statistic.update({ + where: { + targetId_date: { + targetId: targetId, + date: today, + }, + }, + data: { + totalPings: newTotalPings, + successfulPings: newSuccessfulPings, + failedPings: newFailedPings, + uptime: (newSuccessfulPings / newTotalPings) * 100, + lastResponseTime: pingResult.responseTime || 0, + avgResponseTime: + (existingStats.avgResponseTime * existingStats.totalPings + (pingResult.responseTime || 0)) / newTotalPings, + }, + }); + } + } catch (retryError) { + // Silently ignore retry errors + } + } + // Silently ignore other statistics errors to avoid log spam + // They're not critical for core functionality + } + } + + /** + * Stop monitoring a target + */ + stopTargetMonitor(targetId) { + const targetIdStr = targetId.toString ? targetId.toString() : targetId; + // Invalidate any ping that is still awaiting a worker response. This is + // important when a monitor is disabled or its settings are replaced. + this.monitorGeneration.set(targetIdStr, (this.monitorGeneration.get(targetIdStr) || 0) + 1); + if (this.intervals.has(targetIdStr)) { + clearInterval(this.intervals.get(targetIdStr)); + this.intervals.delete(targetIdStr); + console.log(chalk.yellow(`⊘ Stopped monitoring ${targetIdStr}`)); + } + this.targetStatus.delete(targetIdStr); + this.lastAlertTime.delete(targetIdStr); + this.failureCount.delete(targetIdStr); + this.downTimestamp.delete(targetIdStr); + this.notificationSent.delete(targetIdStr); + this.lastNotificationSentAt.delete(targetIdStr); + this.clearNotificationTimer(targetIdStr); + this.notificationScheduling.delete(targetIdStr); + this.monitorTargets.delete(targetIdStr); + this.inFlight.delete(targetIdStr); + } + + /** + * Stop all monitoring + */ + stopAllMonitoring() { + for (const [targetId, interval] of this.intervals.entries()) { + clearInterval(interval); + } + this.intervals.clear(); + this.targetStatus.clear(); + this.lastAlertTime.clear(); + this.failureCount.clear(); + this.downTimestamp.clear(); + this.notificationSent.clear(); + this.lastNotificationSentAt.clear(); + for (const timer of this.notificationTimers.values()) clearTimeout(timer); + this.notificationTimers.clear(); + this.notificationScheduling.clear(); + this.monitorTargets.clear(); + this.inFlight.clear(); + // Keep generation numbers monotonic so a ping from before a full stop + // cannot be mistaken for a ping from a newly started monitor that reuses + // the same id. + for (const [targetId, generation] of this.monitorGeneration.entries()) { + this.monitorGeneration.set(targetId, generation + 1); + } + console.log(chalk.yellow('⊘ Stopped all monitoring')); + } + + /** + * Get target status + */ + getTargetStatus(targetId) { + return this.targetStatus.get(targetId.toString ? targetId.toString() : targetId) || 'unknown'; + } + + /** + * Set target status (for manual updates like test endpoints) + */ + setTargetStatus(targetId, status) { + const targetIdStr = targetId.toString ? targetId.toString() : targetId; + this.targetStatus.set(targetIdStr, status); + } + + /** + * Get all monitoring intervals + */ + getActiveMonitors() { + return Array.from(this.intervals.keys()); + } +} + +module.exports = new MonitorService(); diff --git a/src/services/notificationService.js b/src/services/notificationService.js new file mode 100644 index 0000000..ba2d779 --- /dev/null +++ b/src/services/notificationService.js @@ -0,0 +1,394 @@ +const axios = require('axios'); +const chalk = require('../utils/colors'); +const { getPrisma } = require('../config/prisma'); + +class NotificationService { + constructor() { + this.settings = null; + this.settingsChecked = false; + this.settingsLastCheck = 0; + this.settingsCacheTTL = 60000; // 1 minute cache + } + + /** + * Get notification settings from database (with caching) + */ + async getSettings() { + const now = Date.now(); + + // Return cached settings if still valid + if (this.settings && (now - this.settingsLastCheck) < this.settingsCacheTTL) { + return this.settings; + } + + try { + const prisma = getPrisma(); + const settingsDoc = await prisma.notificationSettings.findUnique({ where: { id: 'settings' } }); + + if (settingsDoc) { + // Prisma stores JSON fields as objects, no need to parse + const discord = settingsDoc.discord || null; + const events = settingsDoc.events || null; + + this.settings = { + enabled: settingsDoc.enabled !== false, + monitorDownDelayMinutes: this.normalizeDelay(settingsDoc.monitorDownDelayMinutes), + discord: { + enabled: discord?.enabled === true, + webhookUrl: discord?.webhookUrl || null, + username: discord?.username || 'LocalPing', + avatarUrl: discord?.avatarUrl || null, + }, + events: { + monitorDown: events?.monitorDown !== false, + monitorUp: events?.monitorUp !== false, + incidentCreated: events?.incidentCreated !== false, + incidentUpdated: events?.incidentUpdated !== false, + }, + }; + } else { + // Default settings + this.settings = { + enabled: false, + monitorDownDelayMinutes: 5, + discord: { + enabled: false, + webhookUrl: null, + username: 'LocalPing', + avatarUrl: null, + }, + events: { + monitorDown: true, + monitorUp: true, + incidentCreated: true, + incidentUpdated: true, + }, + }; + } + + this.settingsLastCheck = now; + return this.settings; + } catch (error) { + console.error(chalk.red('Error loading notification settings:'), error.message); + // Return default settings on error + return { + enabled: false, + monitorDownDelayMinutes: 5, + discord: { enabled: false, webhookUrl: null, username: 'LocalPing', avatarUrl: null }, + events: { monitorDown: true, monitorUp: true, incidentCreated: true, incidentUpdated: true }, + }; + } + } + + normalizeDelay(value) { + const parsed = Number.parseInt(value, 10); + if (!Number.isFinite(parsed)) return 5; + return Math.min(1440, Math.max(1, parsed)); + } + + async getMonitorDownDelayMinutes() { + const settings = await this.getSettings(); + return this.normalizeDelay(settings.monitorDownDelayMinutes); + } + + /** + * Invalidate settings cache + */ + invalidateCache() { + this.settings = null; + this.settingsChecked = false; + this.settingsLastCheck = 0; + } + + /** + * Get avatar URL for Discord webhook + * Returns the configured avatar URL or constructs a default URL using the ms-icon + */ + getAvatarUrl(configuredAvatarUrl) { + // If avatar is configured, use it + if (configuredAvatarUrl && configuredAvatarUrl.trim() && configuredAvatarUrl.includes('http')) { + return configuredAvatarUrl; + } + + // Otherwise, construct default URL using environment variable or default + // Use PUBLIC_URL, API_URL, or construct from PORT + let baseUrl = process.env.PUBLIC_URL || process.env.API_URL; + + if (!baseUrl) { + // Construct from host and port if available + const host = process.env.HOST || 'localhost'; + const port = process.env.API_PORT || process.env.PORT || 8000; + const protocol = process.env.PROTOCOL || (port === 443 ? 'https' : 'http'); + baseUrl = `${protocol}://${host}${port !== 80 && port !== 443 ? `:${port}` : ''}`; + } + + // Ensure baseUrl doesn't end with a slash + baseUrl = baseUrl.replace(/\/$/, ''); + + return `${baseUrl}/ms-icon-310x310.png`; + } + + /** + * Send notification to Discord webhook + */ + async sendDiscordNotification(webhookUrl, payload) { + try { + const response = await axios.post(webhookUrl, payload, { + headers: { + 'Content-Type': 'application/json', + }, + timeout: 10000, // 10 second timeout + }); + + return { success: true, response: response.data }; + } catch (error) { + console.error(chalk.red('Discord webhook error:'), error.message); + if (error.response) { + console.error(chalk.gray(' Response status:'), error.response.status); + console.error(chalk.gray(' Response data:'), error.response.data); + } + return { success: false, error: error.message }; + } + } + + /** + * Format Discord embed for monitor status change + */ + formatMonitorEmbed(target, status, responseTime = null, downtimeDuration = null) { + const isUp = status === 'up'; + const color = isUp ? 0x10b981 : 0xef4444; // Green or Red + const title = isUp ? 'βœ“ Monitor Online' : 'βœ— Monitor Offline'; + let description = isUp + ? `${target.name} is back online` + : `${target.name} is currently offline`; + + // Add downtime duration to description if available + if (isUp && downtimeDuration !== null) { + const seconds = Math.floor(downtimeDuration / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + let durationStr = ''; + if (days > 0) { + durationStr = `${days} day${days > 1 ? 's' : ''}, ${hours % 24} hour${(hours % 24) !== 1 ? 's' : ''}`; + } else if (hours > 0) { + durationStr = `${hours} hour${hours > 1 ? 's' : ''}, ${minutes % 60} minute${(minutes % 60) !== 1 ? 's' : ''}`; + } else if (minutes > 0) { + durationStr = `${minutes} minute${minutes > 1 ? 's' : ''}, ${seconds % 60} second${(seconds % 60) !== 1 ? 's' : ''}`; + } else { + durationStr = `${seconds} second${seconds !== 1 ? 's' : ''}`; + } + + description += ` (was down for ${durationStr})`; + } + + const embed = { + title, + description, + color, + fields: [ + { + name: 'Monitor', + value: target.name, + inline: true, + }, + { + name: 'Host', + value: `${target.host}${target.port ? `:${target.port}` : ''}`, + inline: true, + }, + { + name: 'Protocol', + value: target.protocol || 'ICMP', + inline: true, + }, + ], + timestamp: new Date().toISOString(), + }; + + if (responseTime !== null) { + embed.fields.push({ + name: 'Response Time', + value: `${Math.round(responseTime)}ms`, + inline: true, + }); + } + + if (target.group) { + embed.fields.push({ + name: 'Group', + value: target.group, + inline: true, + }); + } + + return embed; + } + + /** + * Format Discord embed for incident + */ + formatIncidentEmbed(incident, isUpdate = false) { + const severityColors = { + minor: 0x3b82f6, // Blue + major: 0xf59e0b, // Yellow/Orange + critical: 0xef4444, // Red + }; + + const statusEmojis = { + investigating: 'πŸ”', + identified: '⚠️', + monitoring: 'πŸ‘οΈ', + resolved: 'βœ…', + }; + + const color = severityColors[incident.severity] || 0x6b7280; + const emoji = statusEmojis[incident.status] || 'πŸ“’'; + const title = isUpdate + ? `${emoji} Incident Updated: ${incident.title}` + : `🚨 New Incident: ${incident.title}`; + + const embed = { + title, + description: incident.description, + color, + fields: [ + { + name: 'Severity', + value: incident.severity.toUpperCase(), + inline: true, + }, + { + name: 'Status', + value: incident.status.toUpperCase(), + inline: true, + }, + ], + timestamp: new Date().toISOString(), + }; + + if (incident.affectedServices && incident.affectedServices.length > 0) { + embed.fields.push({ + name: 'Affected Services', + value: incident.affectedServices.join(', '), + inline: false, + }); + } + + return embed; + } + + /** + * Notify about monitor status change + */ + async notifyMonitorStatus(target, status, responseTime = null, downtimeDuration = null) { + const settings = await this.getSettings(); + + if (!settings.enabled) { + return { success: false, reason: 'Notifications disabled' }; + } + + const eventType = status === 'up' ? 'monitorUp' : 'monitorDown'; + if (!settings.events[eventType]) { + return { success: false, reason: `Event ${eventType} disabled` }; + } + + const results = []; + + // Send Discord notification if enabled + if (settings.discord.enabled && settings.discord.webhookUrl) { + const embed = this.formatMonitorEmbed(target, status, responseTime, downtimeDuration); + const payload = { + username: settings.discord.username, + embeds: [embed], + avatar_url: this.getAvatarUrl(settings.discord.avatarUrl), + }; + + // Add @everyone for important monitors going down + if (status === 'down' && target.important === true) { + payload.content = '@everyone'; + } + + const result = await this.sendDiscordNotification(settings.discord.webhookUrl, payload); + results.push({ provider: 'discord', ...result }); + } + + return { + success: results.some(r => r.success), + results, + }; + } + + /** + * Notify about incident + */ + async notifyIncident(incident, isUpdate = false) { + const settings = await this.getSettings(); + + if (!settings.enabled) { + return { success: false, reason: 'Notifications disabled' }; + } + + const eventType = isUpdate ? 'incidentUpdated' : 'incidentCreated'; + if (!settings.events[eventType]) { + return { success: false, reason: `Event ${eventType} disabled` }; + } + + const results = []; + + // Send Discord notification if enabled + if (settings.discord.enabled && settings.discord.webhookUrl) { + const embed = this.formatIncidentEmbed(incident, isUpdate); + const payload = { + username: settings.discord.username, + embeds: [embed], + avatar_url: this.getAvatarUrl(settings.discord.avatarUrl), + }; + + const result = await this.sendDiscordNotification(settings.discord.webhookUrl, payload); + results.push({ provider: 'discord', ...result }); + } + + return { + success: results.some(r => r.success), + results, + }; + } + + /** + * Test notification (for testing webhook configuration) + */ + async testNotification(provider = 'discord') { + const settings = await this.getSettings(); + + if (!settings.enabled) { + return { success: false, error: 'Notifications are disabled' }; + } + + if (provider === 'discord') { + if (!settings.discord.enabled || !settings.discord.webhookUrl) { + return { success: false, error: 'Discord notifications are not configured' }; + } + + const payload = { + username: settings.discord.username, + embeds: [ + { + title: 'πŸ§ͺ Test Notification', + description: 'This is a test notification from LocalPing. If you receive this, your webhook is configured correctly!', + color: 0x06b6d4, // Cyan + timestamp: new Date().toISOString(), + }, + ], + avatar_url: this.getAvatarUrl(settings.discord.avatarUrl), + }; + + return await this.sendDiscordNotification(settings.discord.webhookUrl, payload); + } + + return { success: false, error: `Unknown provider: ${provider}` }; + } +} + +module.exports = new NotificationService(); diff --git a/src/services/pingService.js b/src/services/pingService.js new file mode 100644 index 0000000..362f647 --- /dev/null +++ b/src/services/pingService.js @@ -0,0 +1,321 @@ +const workerPool = require('./workers/workerPool'); +const { exec } = require('child_process'); +const { promisify } = require('util'); +const axios = require('axios'); +const tcpPing = require('tcp-ping'); +const dgram = require('dgram'); + +const execAsync = promisify(exec); + +class PingService { + constructor() { + this.timeout = 5000; // 5 seconds default timeout + this.useWorkers = true; // Use worker threads by default + } + + /** + * Ping a target using the specified protocol (multithreaded via worker pool) + * @param {Object} target - Target object {host, port, protocol, timeout, httpMethod, statusCodes, ...} + * @returns {Promise} Result {success, responseTime, error} + */ + async ping(target) { + if (this.useWorkers) { + // Use worker pool for non-blocking multithreaded pings + return await workerPool.execute(target); + } + + // Fallback to direct execution (shouldn't be used in production) + return await this.pingDirect(target); + } + + /** + * Direct ping (fallback method, not recommended for production) + * @private + */ + async pingDirect(target) { + const start = Date.now(); + try { + switch (target.protocol?.toUpperCase()) { + case 'ICMP': + return await this.pingICMP(target.host, start); + case 'TCP': + return await this.pingTCP(target.host, target.port || 80, start); + case 'UDP': + return await this.pingUDP(target.host, target.port || 53, start); + case 'HTTP': + return await this.pingHTTP(`http://${target.host}:${target.port || 80}${target.path || '/'}`, start, target); + case 'HTTPS': + return await this.pingHTTP(`https://${target.host}:${target.port || 443}${target.path || '/'}`, start, target); + default: + return { + success: false, + responseTime: 0, + error: 'Unknown protocol: ' + target.protocol, + }; + } + } catch (error) { + return { + success: false, + responseTime: Date.now() - start, + error: error.message, + }; + } + } + + /** + * ICMP Ping using system ping command + * Requires running with elevated privileges + */ + async pingICMP(host, start) { + try { + // Using -c 1 for Linux/Mac, -n 1 for Windows + const isWindows = process.platform === 'win32'; + const cmd = isWindows ? `ping -n 1 -w ${this.timeout} ${host}` : `ping -c 1 -W ${this.timeout / 1000} ${host}`; + + const { stdout } = await execAsync(cmd, { timeout: this.timeout + 1000 }); + + const responseTime = Date.now() - start; + return { + success: true, + responseTime, + protocol: 'ICMP', + }; + } catch (error) { + return { + success: false, + responseTime: Date.now() - start, + error: 'ICMP ping failed: ' + error.message, + protocol: 'ICMP', + }; + } + } + + /** + * TCP Ping to a specific port + */ + async pingTCP(host, port, start) { + return new Promise((resolve) => { + const startTime = Date.now(); + + tcpPing.probe(host, port, (err, available) => { + const responseTime = Date.now() - startTime; + + if (err || !available) { + resolve({ + success: false, + responseTime, + error: err ? err.message : 'Connection refused', + protocol: 'TCP', + }); + } else { + resolve({ + success: true, + responseTime, + protocol: 'TCP', + }); + } + }); + }); + } + + /** + * UDP Ping (simple datagram send/receive) + */ + async pingUDP(host, port, start) { + return new Promise((resolve) => { + const client = dgram.createSocket('udp4'); + const message = Buffer.from('ping'); + let resolved = false; // Track if we've already resolved + + const timeoutHandle = setTimeout(() => { + if (!resolved) { + resolved = true; + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP ping timeout', + protocol: 'UDP', + }); + } + }, this.timeout); + + client.send(message, 0, message.length, port, host, (err) => { + if (err && !resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP send failed: ' + err.message, + protocol: 'UDP', + }); + } + }); + + client.on('message', () => { + if (!resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); // Close immediately before resolve + resolve({ + success: true, + responseTime: Date.now() - start, + protocol: 'UDP', + }); + } + }); + + client.on('error', (err) => { + if (!resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP error: ' + err.message, + protocol: 'UDP', + }); + } + }); + }); + } + + /** + * HTTP/HTTPS Ping with advanced options + */ + async pingHTTP(url, start, target = {}) { + try { + // Get timeout from target config or use default + const timeout = (target.timeout || 30) * 1000; + + // Build axios config + const axiosConfig = { + timeout, + validateStatus: () => true, // Don't throw on any status code + maxRedirects: target.maxRedirects !== undefined ? target.maxRedirects : 5, + method: (target.httpMethod || 'GET').toUpperCase(), + }; + + // Handle SSL/TLS options + if (target.ignoreSsl === true || target.ignoreSsl === 1) { + const httpsAgent = require('https').Agent({ rejectUnauthorized: false }); + const httpAgent = require('http').Agent({ rejectUnauthorized: false }); + axiosConfig.httpsAgent = httpsAgent; + axiosConfig.httpAgent = httpAgent; + } + + // Handle authentication + let auth = target.auth; + if (auth && typeof auth === 'string') { + try { + auth = JSON.parse(auth); + } catch (e) { + auth = null; + } + } + + if (auth) { + if (auth.type === 'basic') { + axiosConfig.auth = { + username: auth.username, + password: auth.password, + }; + } else if (auth.type === 'bearer') { + axiosConfig.headers = { + 'Authorization': `Bearer ${auth.token}`, + }; + } + } + + const response = await axios(url, axiosConfig); + + const responseTime = Date.now() - start; + + // Check if status code is in accepted list + let success = false; + const statusCodes = target.statusCodes || '200-299'; + + if (this.isStatusCodeAccepted(response.status, statusCodes)) { + success = true; + } + + return { + success, + responseTime, + statusCode: response.status, + protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP', + }; + } catch (error) { + return { + success: false, + responseTime: Date.now() - start, + error: error.message, + protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP', + }; + } + } + + /** + * Check if a status code is in the accepted list + * Supports ranges like "200-299" and individual codes like "200,201,404" + */ + isStatusCodeAccepted(statusCode, statusCodes) { + if (!statusCodes) return statusCode >= 200 && statusCode < 300; + + const parts = statusCodes.split(',').map(s => s.trim()); + + for (const part of parts) { + if (part.includes('-')) { + // Range like "200-299" + const [start, end] = part.split('-').map(s => parseInt(s.trim())); + if (statusCode >= start && statusCode <= end) { + return true; + } + } else { + // Individual code like "200" + if (parseInt(part) === statusCode) { + return true; + } + } + } + + return false; + } + + /** + * Batch ping multiple targets (optimized with worker pool) + */ + async pingBatch(targets) { + if (this.useWorkers) { + // Use worker pool batch execution for optimal performance + return await workerPool.executeBatch(targets); + } + // Fallback + const results = await Promise.all(targets.map((target) => this.pingDirect(target))); + return results; + } + + /** + * Shutdown worker pool (call during graceful shutdown) + */ + async shutdown() { + if (this.useWorkers) { + await workerPool.shutdown(); + } + } + + /** + * Get worker pool statistics + */ + getPoolStats() { + if (this.useWorkers) { + return workerPool.getStats(); + } + return null; + } +} + +module.exports = new PingService(); diff --git a/src/services/sqliteService.js b/src/services/sqliteService.js new file mode 100644 index 0000000..5058fd4 --- /dev/null +++ b/src/services/sqliteService.js @@ -0,0 +1,322 @@ +const Database = require('better-sqlite3'); +const path = require('path'); +const fs = require('fs'); + +const chalk = require('../utils/colors'); + +let db = null; + +// Initialize SQLite database +function initializeDatabase() { + const dbDir = path.join(process.cwd(), 'data'); + const dbPath = path.join(dbDir, 'localping.db'); + + // Ensure data directory exists + if (!fs.existsSync(dbDir)) { + fs.mkdirSync(dbDir, { recursive: true }); + } + + db = new Database(dbPath); + + // Enable foreign keys + db.pragma('foreign_keys = ON'); + + createTables(); + + console.log(chalk.green('βœ“ SQLite database initialized at:'), dbPath); + + return db; +} + +// Create tables if they don't exist +function createTables() { + // Check if ping_results table exists and has unique constraint + try { + const tableInfo = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='ping_results'").get(); + if (tableInfo && tableInfo.sql && tableInfo.sql.includes('UNIQUE(targetId, timestamp)')) { + // Migration: Remove unique constraint by recreating table + console.log(chalk.yellow('⊘ Migrating ping_results table to remove unique constraint...')); + db.exec(` + CREATE TABLE ping_results_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + targetId TEXT NOT NULL, + success BOOLEAN NOT NULL, + responseTime INTEGER, + timestamp DATETIME NOT NULL, + statusCode INTEGER, + error TEXT + ); + INSERT INTO ping_results_new SELECT * FROM ping_results; + DROP TABLE ping_results; + ALTER TABLE ping_results_new RENAME TO ping_results; + CREATE INDEX IF NOT EXISTS idx_ping_results_targetId ON ping_results(targetId); + CREATE INDEX IF NOT EXISTS idx_ping_results_timestamp ON ping_results(timestamp); + `); + console.log(chalk.green('βœ“ Migration complete')); + } + } catch (error) { + // Table doesn't exist or migration not needed, continue + } + + // Ping results table + db.exec(` + CREATE TABLE IF NOT EXISTS ping_results ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + targetId TEXT NOT NULL, + success BOOLEAN NOT NULL, + responseTime INTEGER, + timestamp DATETIME NOT NULL, + statusCode INTEGER, + error TEXT + ) + `); + + // Daily statistics table + db.exec(` + CREATE TABLE IF NOT EXISTS daily_stats ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + targetId TEXT NOT NULL, + date DATE NOT NULL, + totalPings INTEGER DEFAULT 0, + successfulPings INTEGER DEFAULT 0, + avgResponseTime REAL DEFAULT 0, + minResponseTime INTEGER, + maxResponseTime INTEGER, + UNIQUE(targetId, date) + ) + `); + + // Create indices for faster queries + db.exec(` + CREATE INDEX IF NOT EXISTS idx_ping_results_targetId ON ping_results(targetId); + CREATE INDEX IF NOT EXISTS idx_ping_results_timestamp ON ping_results(timestamp); + CREATE INDEX IF NOT EXISTS idx_daily_stats_targetId ON daily_stats(targetId); + CREATE INDEX IF NOT EXISTS idx_daily_stats_date ON daily_stats(date); + `); +} + +// Get database instance +function getDatabase() { + if (!db) { + initializeDatabase(); + } + return db; +} + +// Store ping result +function storePingResult(targetId, result, timestamp = null) { + const database = getDatabase(); + + try { + // Use provided timestamp or current time with millisecond precision + const pingTimestamp = timestamp || new Date().toISOString(); + + const stmt = database.prepare(` + INSERT INTO ping_results (targetId, success, responseTime, statusCode, error, timestamp) + VALUES (?, ?, ?, ?, ?, ?) + `); + + stmt.run( + targetId, + result.success ? 1 : 0, + result.responseTime || null, + result.statusCode || null, + result.error || null, + pingTimestamp + ); + } catch (error) { + console.error(chalk.red('Error storing ping result:'), error.message); + } +} + +// Get ping results for a target +function getPingResults(targetId, options = {}) { + const database = getDatabase(); + const { limit = 100, offset = 0, days = null } = options; + + try { + let query = 'SELECT * FROM ping_results WHERE targetId = ?'; + const params = [targetId]; + + if (days) { + const startDate = new Date(); + startDate.setDate(startDate.getDate() - days); + query += ' AND timestamp >= ?'; + params.push(startDate.toISOString()); + } + + query += ' ORDER BY timestamp DESC LIMIT ? OFFSET ?'; + params.push(limit, offset); + + const stmt = database.prepare(query); + const results = stmt.all(...params); + + return results.map(r => ({ + ...r, + success: r.success === 1, + timestamp: new Date(r.timestamp) + })); + } catch (error) { + console.error(chalk.red('Error fetching ping results:'), error.message); + return []; + } +} + +// Get daily statistics for a target +function getDailyStats(targetId, options = {}) { + const database = getDatabase(); + const { limit = 30, offset = 0 } = options; + + try { + const stmt = database.prepare(` + SELECT * FROM daily_stats + WHERE targetId = ? + ORDER BY date DESC + LIMIT ? OFFSET ? + `); + + return stmt.all(targetId, limit, offset); + } catch (error) { + console.error(chalk.red('Error fetching daily stats:'), error.message); + return []; + } +} + +// Update or create daily statistics +function updateDailyStats(targetId) { + const database = getDatabase(); + + try { + const today = new Date().toISOString().split('T')[0]; + + // Get today's ping results + const stmt = database.prepare(` + SELECT + COUNT(*) as totalPings, + SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successfulPings, + AVG(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as avgResponseTime, + MIN(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as minResponseTime, + MAX(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as maxResponseTime + FROM ping_results + WHERE targetId = ? AND DATE(timestamp) = ? + `); + + const stats = stmt.get(targetId, today); + + // Insert or update daily stats + const insertStmt = database.prepare(` + INSERT INTO daily_stats (targetId, date, totalPings, successfulPings, avgResponseTime, minResponseTime, maxResponseTime) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(targetId, date) DO UPDATE SET + totalPings = excluded.totalPings, + successfulPings = excluded.successfulPings, + avgResponseTime = excluded.avgResponseTime, + minResponseTime = excluded.minResponseTime, + maxResponseTime = excluded.maxResponseTime + `); + + insertStmt.run( + targetId, + today, + stats.totalPings || 0, + stats.successfulPings || 0, + stats.avgResponseTime || 0, + stats.minResponseTime || null, + stats.maxResponseTime || null + ); + } catch (error) { + console.error(chalk.red('Error updating daily stats:'), error.message); + } +} + +// Get uptime percentage for a target +function getUptimePercentage(targetId, days = 30) { + const database = getDatabase(); + + try { + const stmt = database.prepare(` + SELECT + COUNT(*) as totalPings, + SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successfulPings + FROM ping_results + WHERE targetId = ? AND timestamp >= datetime('now', '-' || ? || ' days') + `); + + const result = stmt.get(targetId, days); + + if (result.totalPings === 0) { + return 100; + } + + return ((result.successfulPings / result.totalPings) * 100).toFixed(2); + } catch (error) { + console.error(chalk.red('Error calculating uptime:'), error.message); + return 0; + } +} + +// Clean old ping results (keep only last 90 days) +function cleanupOldData() { + const database = getDatabase(); + + try { + const stmt = database.prepare(` + DELETE FROM ping_results + WHERE timestamp < datetime('now', '-90 days') + `); + + const changes = stmt.run().changes; + + if (changes > 0) { + console.log(chalk.yellow(`⊘ Cleaned up ${changes} old ping records`)); + } + } catch (error) { + console.error(chalk.red('Error cleaning up old data:'), error.message); + } +} + +// Clear all ping data +function clearAllPingData() { + const database = getDatabase(); + + try { + // Clear ping_results table + const pingStmt = database.prepare('DELETE FROM ping_results'); + const pingChanges = pingStmt.run().changes; + + // Clear daily_stats table + const statsStmt = database.prepare('DELETE FROM daily_stats'); + const statsChanges = statsStmt.run().changes; + + console.log(chalk.yellow(`⊘ Cleared ${pingChanges} ping records and ${statsChanges} daily stats`)); + + return { + pingRecordsDeleted: pingChanges, + dailyStatsDeleted: statsChanges + }; + } catch (error) { + console.error(chalk.red('Error clearing ping data:'), error.message); + throw error; + } +} + +// Close database connection +function closeDatabase() { + if (db) { + db.close(); + db = null; + } +} + +module.exports = { + initializeDatabase, + getDatabase, + storePingResult, + getPingResults, + getDailyStats, + updateDailyStats, + getUptimePercentage, + cleanupOldData, + clearAllPingData, + closeDatabase, +}; diff --git a/src/services/workers/pingWorker.js b/src/services/workers/pingWorker.js new file mode 100644 index 0000000..3fd814a --- /dev/null +++ b/src/services/workers/pingWorker.js @@ -0,0 +1,259 @@ +const { parentPort } = require('worker_threads'); +const { exec } = require('child_process'); +const { promisify } = require('util'); +const axios = require('axios'); +const tcpPing = require('tcp-ping'); +const dgram = require('dgram'); + +const execAsync = promisify(exec); + +/** + * Ping worker - handles ping operations in a separate thread + */ +class PingWorker { + constructor() { + this.timeout = 5000; // 5 seconds default timeout + } + + async pingICMP(host, timeout) { + try { + const isWindows = process.platform === 'win32'; + const cmd = isWindows + ? `ping -n 1 -w ${timeout} ${host}` + : `ping -c 1 -W ${timeout / 1000} ${host}`; + + const { stdout } = await execAsync(cmd, { timeout: timeout + 1000 }); + return { success: true, protocol: 'ICMP' }; + } catch (error) { + return { + success: false, + error: 'ICMP ping failed: ' + error.message, + protocol: 'ICMP' + }; + } + } + + async pingTCP(host, port) { + return new Promise((resolve) => { + const startTime = Date.now(); + tcpPing.probe(host, port, (err, available) => { + const responseTime = Date.now() - startTime; + if (err || !available) { + resolve({ + success: false, + responseTime, + error: err ? err.message : 'Connection refused', + protocol: 'TCP', + }); + } else { + resolve({ + success: true, + responseTime, + protocol: 'TCP', + }); + } + }); + }); + } + + async pingUDP(host, port, timeout) { + return new Promise((resolve) => { + const start = Date.now(); + const client = dgram.createSocket('udp4'); + const message = Buffer.from('ping'); + let resolved = false; + + const timeoutHandle = setTimeout(() => { + if (!resolved) { + resolved = true; + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP ping timeout', + protocol: 'UDP', + }); + } + }, timeout); + + client.send(message, 0, message.length, port, host, (err) => { + if (err && !resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP send failed: ' + err.message, + protocol: 'UDP', + }); + } + }); + + client.on('message', () => { + if (!resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); + resolve({ + success: true, + responseTime: Date.now() - start, + protocol: 'UDP', + }); + } + }); + + client.on('error', (err) => { + if (!resolved) { + resolved = true; + clearTimeout(timeoutHandle); + client.close(); + resolve({ + success: false, + responseTime: Date.now() - start, + error: 'UDP error: ' + err.message, + protocol: 'UDP', + }); + } + }); + }); + } + + async pingHTTP(url, target = {}) { + try { + const timeout = (target.timeout || 30) * 1000; + const axiosConfig = { + timeout, + validateStatus: () => true, + maxRedirects: target.maxRedirects !== undefined ? target.maxRedirects : 5, + method: (target.httpMethod || 'GET').toUpperCase(), + }; + + if (target.ignoreSsl === true || target.ignoreSsl === 1) { + const httpsAgent = require('https').Agent({ rejectUnauthorized: false }); + const httpAgent = require('http').Agent({ rejectUnauthorized: false }); + axiosConfig.httpsAgent = httpsAgent; + axiosConfig.httpAgent = httpAgent; + } + + let auth = target.auth; + if (auth && typeof auth === 'string') { + try { + auth = JSON.parse(auth); + } catch (e) { + auth = null; + } + } + + if (auth) { + if (auth.type === 'basic') { + axiosConfig.auth = { + username: auth.username, + password: auth.password, + }; + } else if (auth.type === 'bearer') { + axiosConfig.headers = { + 'Authorization': `Bearer ${auth.token}`, + }; + } + } + + const response = await axios(url, axiosConfig); + const statusCodes = target.statusCodes || '200-299'; + const success = this.isStatusCodeAccepted(response.status, statusCodes); + + return { + success, + statusCode: response.status, + protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP', + }; + } catch (error) { + return { + success: false, + error: error.message, + protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP', + }; + } + } + + isStatusCodeAccepted(statusCode, statusCodes) { + if (!statusCodes) return statusCode >= 200 && statusCode < 300; + const parts = statusCodes.split(',').map(s => s.trim()); + for (const part of parts) { + if (part.includes('-')) { + const [start, end] = part.split('-').map(s => parseInt(s.trim())); + if (statusCode >= start && statusCode <= end) { + return true; + } + } else { + if (parseInt(part) === statusCode) { + return true; + } + } + } + return false; + } + + async executePing(target) { + const start = Date.now(); + const timeout = target.timeout ? target.timeout * 1000 : this.timeout; + + try { + let result; + switch (target.protocol?.toUpperCase()) { + case 'ICMP': + result = await this.pingICMP(target.host, timeout); + break; + case 'TCP': + result = await this.pingTCP(target.host, target.port || 80); + break; + case 'UDP': + result = await this.pingUDP(target.host, target.port || 53, timeout); + break; + case 'HTTP': + result = await this.pingHTTP(`http://${target.host}:${target.port || 80}${target.path || '/'}`, target); + break; + case 'HTTPS': + result = await this.pingHTTP(`https://${target.host}:${target.port || 443}${target.path || '/'}`, target); + break; + default: + result = { + success: false, + error: 'Unknown protocol: ' + target.protocol, + }; + } + + result.responseTime = result.responseTime || (Date.now() - start); + return result; + } catch (error) { + return { + success: false, + responseTime: Date.now() - start, + error: error.message, + }; + } + } +} + +// Handle messages from main thread +const worker = new PingWorker(); + +parentPort.on('message', async (message) => { + try { + const result = await worker.executePing(message.target); + parentPort.postMessage({ + id: message.id, + result, + }); + } catch (error) { + parentPort.postMessage({ + id: message.id, + result: { + success: false, + responseTime: 0, + error: error.message, + }, + }); + } +}); + diff --git a/src/services/workers/workerPool.js b/src/services/workers/workerPool.js new file mode 100644 index 0000000..7e175b9 --- /dev/null +++ b/src/services/workers/workerPool.js @@ -0,0 +1,284 @@ +const { Worker } = require('worker_threads'); +const path = require('path'); + +/** + * Worker Pool Manager - manages a pool of worker threads for ping operations + */ +class WorkerPool { + constructor(size = 4) { + this.size = size; + this.workers = []; + this.queue = []; + this.activeTasks = new Map(); + this.taskIdCounter = 0; + this.initialized = false; + } + + /** + * Initialize the worker pool + */ + initialize() { + if (this.initialized) return; + + const workerPath = path.join(__dirname, 'pingWorker.js'); + const fs = require('fs'); + + // Verify worker file exists + if (!fs.existsSync(workerPath)) { + console.error(`Worker file not found: ${workerPath}`); + throw new Error(`Worker file not found: ${workerPath}`); + } + + for (let i = 0; i < this.size; i++) { + let worker; + try { + worker = new Worker(workerPath); + } catch (error) { + console.error(`Failed to create worker ${i}:`, error); + throw error; + } + + worker.on('message', (message) => { + const { id, result } = message; + const task = this.activeTasks.get(id); + + if (task) { + task.resolve(result); + this.activeTasks.delete(id); + } + + // Mark worker as not busy + const workerInfo = this.workers.find(w => w.worker === worker); + if (workerInfo) { + workerInfo.busy = false; + } + + this.processQueue(); + }); + + worker.on('error', (error) => { + console.error(`Worker error:`, error); + // Remove failed worker and create a new one + const index = this.workers.indexOf(worker); + if (index > -1) { + this.workers.splice(index, 1); + this.createWorker(); + } + }); + + worker.on('exit', (code) => { + if (code !== 0) { + console.error(`Worker exited with code ${code}`); + const index = this.workers.indexOf(worker); + if (index > -1) { + this.workers.splice(index, 1); + this.createWorker(); + } + } + }); + + this.workers.push({ + worker, + busy: false, + }); + } + + this.initialized = true; + } + + /** + * Create a new worker to replace a failed one + */ + createWorker() { + const workerPath = path.join(__dirname, 'pingWorker.js'); + const worker = new Worker(workerPath); + + worker.on('message', (message) => { + const { id, result } = message; + const task = this.activeTasks.get(id); + + if (task) { + task.resolve(result); + this.activeTasks.delete(id); + } + + // Mark worker as not busy + const workerInfo = this.workers.find(w => w.worker === worker); + if (workerInfo) { + workerInfo.busy = false; + } + + this.processQueue(); + }); + + worker.on('error', (error) => { + console.error(`Worker error:`, error); + const index = this.workers.findIndex(w => w.worker === worker); + if (index > -1) { + this.workers[index].worker.terminate(); + this.workers.splice(index, 1); + } + }); + + worker.on('exit', (code) => { + if (code !== 0) { + const index = this.workers.findIndex(w => w.worker === worker); + if (index > -1) { + this.workers.splice(index, 1); + } + } + }); + + this.workers.push({ + worker, + busy: false, + }); + } + + /** + * Get an available worker + */ + getAvailableWorker() { + return this.workers.find(w => !w.busy); + } + + /** + * Process the queue of pending tasks + */ + processQueue() { + if (this.queue.length === 0) return; + + const availableWorker = this.getAvailableWorker(); + if (!availableWorker) return; + + const task = this.queue.shift(); + + // Check if task has already timed out + if (!this.activeTasks.has(task.id)) { + // Task was removed due to timeout, skip it + this.processQueue(); + return; + } + + availableWorker.busy = true; + + availableWorker.worker.postMessage({ + id: task.id, + target: task.target, + }); + } + + /** + * Execute a ping task using the worker pool + */ + async execute(target) { + if (!this.initialized) { + this.initialize(); + } + + // Get timeout from target config or use default (60 seconds) + const timeout = (target.timeout || 60) * 1000; + + return new Promise((resolve, reject) => { + const taskId = ++this.taskIdCounter; + + // Set up timeout for the task + let assignedWorker = null; + const timeoutHandle = setTimeout(() => { + const task = this.activeTasks.get(taskId); + if (task) { + this.activeTasks.delete(taskId); + + // Remove from queue if it's still queued + const queueIndex = this.queue.findIndex(t => t.id === taskId); + if (queueIndex !== -1) { + this.queue.splice(queueIndex, 1); + } + + // Mark assigned worker as not busy if it was assigned + if (assignedWorker) { + assignedWorker.busy = false; + } + + task.reject(new Error(`Ping timeout after ${timeout}ms`)); + this.processQueue(); + } + }, timeout); + + const task = { + id: taskId, + target, + timeoutHandle, + resolve: (result) => { + clearTimeout(timeoutHandle); + resolve(result); + }, + reject: (error) => { + clearTimeout(timeoutHandle); + reject(error); + }, + }; + + const availableWorker = this.getAvailableWorker(); + + if (availableWorker) { + availableWorker.busy = true; + assignedWorker = availableWorker; + this.activeTasks.set(taskId, task); + + availableWorker.worker.postMessage({ + id: taskId, + target, + }); + } else { + // No available worker, add to queue + this.queue.push(task); + // Store task in activeTasks so timeout can remove it from queue + this.activeTasks.set(taskId, task); + } + }); + } + + /** + * Execute multiple pings concurrently + */ + async executeBatch(targets) { + const promises = targets.map(target => this.execute(target)); + return Promise.all(promises); + } + + /** + * Shutdown all workers + */ + async shutdown() { + const shutdownPromises = this.workers.map(({ worker }) => { + return worker.terminate(); + }); + + await Promise.all(shutdownPromises); + this.workers = []; + this.queue = []; + this.activeTasks.clear(); + this.initialized = false; + } + + /** + * Get pool statistics + */ + getStats() { + return { + totalWorkers: this.workers.length, + busyWorkers: this.workers.filter(w => w.busy).length, + queueLength: this.queue.length, + activeTasks: this.activeTasks.size, + }; + } +} + +// Create a singleton instance +// Use optimal pool size based on CPU cores, but cap at 8 to avoid overhead +const optimalSize = Math.min(Math.max(require('os').cpus().length, 2), 8); +const workerPool = new WorkerPool(optimalSize); + +module.exports = workerPool; + diff --git a/src/site/brand/icon-180.png b/src/site/brand/icon-180.png new file mode 100644 index 0000000..d64b064 Binary files /dev/null and b/src/site/brand/icon-180.png differ diff --git a/src/site/brand/icon-192.png b/src/site/brand/icon-192.png new file mode 100644 index 0000000..a53990e Binary files /dev/null and b/src/site/brand/icon-192.png differ diff --git a/src/site/brand/icon-32.png b/src/site/brand/icon-32.png new file mode 100644 index 0000000..785035b Binary files /dev/null and b/src/site/brand/icon-32.png differ diff --git a/src/site/brand/icon-512.png b/src/site/brand/icon-512.png new file mode 100644 index 0000000..48e0d4a Binary files /dev/null and b/src/site/brand/icon-512.png differ diff --git a/src/site/brand/icon.svg b/src/site/brand/icon.svg new file mode 100644 index 0000000..d33cffd --- /dev/null +++ b/src/site/brand/icon.svg @@ -0,0 +1 @@ + diff --git a/src/site/index.html b/src/site/index.html new file mode 100644 index 0000000..5c3ad06 --- /dev/null +++ b/src/site/index.html @@ -0,0 +1,37 @@ + + + + + +Status + + + + + + + + + +
    + Status + +
    +
    + + + + + diff --git a/src/site/site.css b/src/site/site.css new file mode 100644 index 0000000..b92eb03 --- /dev/null +++ b/src/site/site.css @@ -0,0 +1,64 @@ +:root{--bg:#0b0d12;--panel:#12151c;--panel2:#171b24;--line:#232836;--text:#e8ebf2;--muted:#8a93a6;--acc:#6ea8ff;--ok:#3ddc97;--warn:#f5b942;--bad:#ff5d6c;--r:14px;color-scheme:dark} +*{box-sizing:border-box} +html{-webkit-text-size-adjust:100%} +body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;min-height:100vh;display:flex;flex-direction:column} +a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline} +.skip{position:absolute;left:-999px}.skip:focus{left:8px;top:8px;background:#000;padding:8px;z-index:9} +.wrap{max-width:1040px;margin:0 auto;padding:0 20px} +.top{position:sticky;top:0;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 20px;background:rgba(11,13,18,.85);backdrop-filter:blur(10px);border-bottom:1px solid var(--line)} +.brand{font-weight:700;font-size:17px;color:var(--text);display:flex;align-items:center;gap:9px;white-space:nowrap}.brand:hover{text-decoration:none} +.muted{color:var(--muted)} +.dot{width:10px;height:10px;border-radius:50%;background:var(--muted);box-shadow:0 0 0 0 transparent} +.dot.operational{background:var(--ok);box-shadow:0 0 10px var(--ok)}.dot.degraded{background:var(--warn);box-shadow:0 0 10px var(--warn)}.dot.down{background:var(--bad);box-shadow:0 0 10px var(--bad)} +nav{display:flex;gap:2px;overflow-x:auto;scrollbar-width:none}nav::-webkit-scrollbar{display:none} +nav a{color:var(--muted);padding:7px 12px;border-radius:9px;font-weight:500;white-space:nowrap} +nav a:hover{color:var(--text);background:var(--panel);text-decoration:none}nav a.on{color:var(--text);background:var(--panel2)} +main{flex:1;padding:28px 0 56px;outline:none} +h1{font-size:clamp(26px,4vw,38px);line-height:1.15;margin:0 0 8px;letter-spacing:-.02em} +h2{font-size:18px;margin:34px 0 12px} +.lead{color:var(--muted);max-width:60ch;margin:0 0 22px} +.banner{display:flex;align-items:center;gap:14px;padding:18px 20px;border-radius:var(--r);border:1px solid var(--line);background:var(--panel)} +.banner .big{font-size:20px;font-weight:650}.banner small{color:var(--muted)} +.banner.operational{border-color:#1f4d3a;background:linear-gradient(90deg,#10231c,var(--panel))} +.banner.degraded{border-color:#5a4513;background:linear-gradient(90deg,#261f0e,var(--panel))} +.banner.down{border-color:#5c1f27;background:linear-gradient(90deg,#2a1216,var(--panel))} +.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin:14px 0} +.stat{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:14px 16px} +.stat b{display:block;font-size:24px;letter-spacing:-.02em}.stat span{color:var(--muted);font-size:13px} +.list{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);overflow:hidden} +.row{display:grid;grid-template-columns:minmax(0,1.3fr) auto minmax(0,1fr) 64px;gap:14px;align-items:center;padding:12px 16px;border-top:1px solid var(--line)} +.row:first-child{border-top:0} +.svc{display:flex;align-items:center;gap:11px;min-width:0} +.svc img{width:24px;height:24px;border-radius:6px;object-fit:contain;background:var(--panel2);flex:none} +.svc .ph{width:24px;height:24px;border-radius:6px;background:var(--panel2);flex:none} +.svc span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:550} +.pill{font-size:12px;font-weight:600;padding:3px 9px;border-radius:99px;border:1px solid var(--line);white-space:nowrap} +.pill.up{color:var(--ok);border-color:#1f4d3a;background:#10231c}.pill.down{color:var(--bad);border-color:#5c1f27;background:#2a1216}.pill.unknown{color:var(--muted)} +.bars{display:flex;gap:2px;height:22px;align-items:stretch} +.bars i{flex:1;border-radius:2px;background:var(--line);min-width:2px} +.bars i.b1{background:var(--ok)}.bars i.b2{background:var(--warn)}.bars i.b3{background:var(--bad)} +.pc{text-align:right;color:var(--muted);font-variant-numeric:tabular-nums;font-size:13px} +.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:18px 20px;margin-bottom:12px} +.card h3{margin:0 0 4px;font-size:16px}.card time,.meta{color:var(--muted);font-size:13px} +.card p{margin:8px 0 0;white-space:pre-wrap} +.tag{display:inline-block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;padding:2px 8px;border-radius:6px;margin-right:6px;background:var(--panel2);color:var(--muted)} +.tag.critical,.tag.major{color:var(--bad)}.tag.minor{color:var(--warn)}.tag.resolved{color:var(--ok)}.tag.scheduled{color:var(--acc)} +.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px} +input,textarea,select,button{font:inherit;color:var(--text);background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:9px 12px} +textarea{width:100%;min-height:90px;resize:vertical;font-family:ui-monospace,Menlo,monospace;font-size:13px} +input{width:100%}button{cursor:pointer;background:var(--acc);color:#07101f;border:0;font-weight:650}button.ghost{background:var(--panel2);color:var(--text);border:1px solid var(--line)} +.btns{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0} +.out{font-family:ui-monospace,Menlo,monospace;font-size:13px;word-break:break-all;background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:10px;min-height:40px;margin-top:8px} +.stale{background:#261f0e;border:1px solid #5a4513;color:var(--warn);padding:10px 14px;border-radius:10px;margin-bottom:14px} +.skeleton{height:220px;border-radius:var(--r);background:linear-gradient(90deg,var(--panel),var(--panel2),var(--panel));background-size:200% 100%;animation:sh 1.2s infinite} +@keyframes sh{to{background-position:-200% 0}} +.foot{border-top:1px solid var(--line);padding:22px 0;color:var(--muted);font-size:13px} +.foot .wrap{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap} +@media(max-width:680px){ + .top{padding:10px 14px;flex-wrap:wrap}.wrap{padding:0 14px} + .row{grid-template-columns:1fr auto;row-gap:8px}.row .bars{grid-column:1/-1;order:3}.row .pc{order:2;display:none} +} +@media(prefers-reduced-motion:reduce){*{animation:none!important}} +.svc{position:relative}.info{flex:none;width:18px;height:18px;padding:0;border-radius:50%;background:var(--panel2);color:var(--muted);border:1px solid var(--line);font:italic 700 11px/1 Georgia,serif;display:inline-grid;place-items:center} +.info:hover,.info[aria-expanded=true]{color:var(--acc);border-color:var(--acc)} +.tip{position:absolute;left:0;top:100%;margin-top:6px;z-index:6;width:min(320px,80vw);background:#1b2030;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:13px;line-height:1.45;box-shadow:0 8px 30px rgba(0,0,0,.5)} diff --git a/src/site/site.js b/src/site/site.js new file mode 100644 index 0000000..02462c4 --- /dev/null +++ b/src/site/site.js @@ -0,0 +1,125 @@ +const $ = (s, r = document) => r.querySelector(s); +const main = $('#main'); +const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +const LABEL = { operational: 'All systems operational', degraded: 'Some services are down', down: 'Major outage', unknown: 'Status unknown' }; +const ago = (d) => { const s = (Date.now() - new Date(d)) / 1e3; return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : new Date(d).toLocaleDateString(); }; +const fmt = (d) => new Date(d).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }); + +let summary = null, lastOk = 0; +async function load() { + try { + const r = await fetch('/api/site/summary'); + if (!r.ok) throw 0; + summary = await r.json(); lastOk = Date.now(); + localStorage.setItem('summary', JSON.stringify(summary)); + } catch { if (!summary) try { summary = JSON.parse(localStorage.getItem('summary')); } catch {} } + $('#brand-dot').className = 'dot ' + (summary?.overall || ''); + return summary; +} +const stale = () => (!lastOk || Date.now() - lastOk > 120e3) ? '
    Live data is unavailable right now. Showing the last known state.
    ' : ''; + +const icon = (s) => s.icon ? `` : '
    '; +const row = (s) => `
    +
    ${icon(s)}${s.url ? `${esc(s.name)}` : esc(s.name)}${s.description ? `` : ''}
    + ${s.status === 'up' ? 'Operational' : s.status === 'down' ? 'Down' : 'Unknown'} +
    ${s.bars.map((b) => ``).join('')}
    +
    ${s.up30 == null ? '–' : s.up30.toFixed(1) + '%'}
    `; +const TIERS = [['featured', 'Popular services'], ['normal', 'Other services'], ['background', 'Infrastructure & background services']]; +const groups = (list) => TIERS.map(([t, h]) => { const l = list.filter((s) => (s.tier || 'normal') === t); return l.length ? `

    ${h}

    ${l.map(row).join('')}
    ` : ''; }).join(''); + +function banner(d) { + return ``; +} +const incCard = (i) => `

    ${i.scheduled ? 'scheduled' : esc(i.severity)}${esc(i.status)}${esc(i.title)}

    +
    ${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' Β· resolved ' + fmt(i.resolvedAt) : ''}
    ${i.description ? `

    ${esc(i.description)}

    ` : ''}
    `; + +const views = { + async '/'() { + const d = await load(); const news = await (await fetch('/api/site/news').catch(() => null))?.json?.().catch(() => null); + const active = d?.incidents.filter((i) => i.status !== 'resolved' && (!i.scheduled || new Date(i.start) <= Date.now() + 864e5)) || []; + return `
    ${stale()}

    Service status

    Live health, incidents and news.

    + ${d ? banner(d) : ''} + ${active.length ? `

    Active & upcoming

    ${active.map(incCard).join('')}` : ''} + ${groups(d?.services || [])} +

    Bars show the last 24 hours. Percentage is 30-day uptime. Full status & history β†’

    + ${news?.posts?.length ? `

    Latest news

    ${news.posts.slice(0, 2).map(post).join('')}All news β†’` : ''}
    `; + }, + async '/status'() { + const d = await load(); if (!d) return `
    ${stale()}

    Status

    `; + const avg = d.services.filter((s) => s.up30 != null); + const u = avg.length ? (avg.reduce((a, s) => a + s.up30, 0) / avg.length).toFixed(2) : '–'; + const rts = d.services.filter((s) => s.rt); const rt = rts.length ? Math.round(rts.reduce((a, s) => a + s.rt, 0) / rts.length) : '–'; + return `
    ${stale()}

    Status

    Checked every minute from a monitor on a separate host.

    ${banner(d)} +
    ${d.up}/${d.total}services up
    ${u}%avg 30-day uptime
    ${rt}${rt === '–' ? '' : ' ms'}avg response (24h)
    + ${groups(d.services)} +

    Incident history

    ${d.incidents.length ? d.incidents.map(incCard).join('') : '

    No incidents recorded.

    '}
    `; + }, + async '/news'() { + const r = await fetch('/api/site/news').then((x) => x.json()).catch(() => null); + return `

    News

    Announcements, changes and maintenance notes. RSS feed

    ${r?.posts?.length ? r.posts.map(post).join('') : '

    Nothing yet.

    '}
    `; + }, + async '/tools'() { return toolsView(); }, + async '/about'() { + return `

    About

    Edit this page in src/site/site.js (or point SITE_DIR at your own theme).

    +
    `; + }, +}; +const post = (p) => `

    ${esc(p.title)}

    ${esc(p.content)}

    `; + +// ---- Tools: small, client-side only ---- +const tools = [ + { id: 'ip', name: 'My IP address', desc: 'The address the internet sees for you.', run: async (o) => { const r = await fetch('/api/site/tools/ip').then((x) => x.json()); o.textContent = r.ip; } }, + { id: 'dns', name: 'DNS lookup', desc: 'Resolve a hostname via Cloudflare DNS-over-HTTPS.', input: 'Status', + run: async (o, v) => { const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(v)}&type=A`, { headers: { accept: 'application/dns-json' } }).then((x) => x.json()); o.textContent = (r.Answer || []).map((a) => a.data).join('\n') || 'No records'; } }, + { id: 'b64', name: 'Base64', desc: 'Encode or decode text.', area: true, + run: (o, v, m) => { try { o.textContent = m === 'dec' ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : btoa(String.fromCharCode(...new TextEncoder().encode(v))); } catch { o.textContent = 'Invalid input'; } }, modes: [['enc', 'Encode'], ['dec', 'Decode']] }, + { id: 'hash', name: 'SHA-256', desc: 'Hash text in your browser.', area: true, modes: [['go', 'Hash']], + run: async (o, v) => { const h = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(v)); o.textContent = [...new Uint8Array(h)].map((b) => b.toString(16).padStart(2, '0')).join(''); } }, + { id: 'pw', name: 'Password generator', desc: 'Random 20-character password.', modes: [['go', 'Generate']], + run: (o) => { const c = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_'; const a = crypto.getRandomValues(new Uint32Array(20)); o.textContent = [...a].map((n) => c[n % c.length]).join(''); } }, + { id: 'time', name: 'Unix time', desc: 'Convert between timestamps and dates.', input: String(Math.floor(Date.now() / 1e3)), modes: [['go', 'Convert']], + run: (o, v) => { const n = Number(v); o.textContent = isNaN(n) ? new Date(v).getTime() / 1e3 + ' (unix)' : new Date(n * (n < 1e12 ? 1e3 : 1)).toISOString(); } }, +]; +function toolsView() { + setTimeout(() => tools.forEach((t) => { + const el = $('#t-' + t.id); if (!el) return; const out = $('.out', el), inp = $('input,textarea', el); + const go = async (m) => { out.textContent = '…'; try { await t.run(out, inp?.value ?? '', m); } catch { out.textContent = 'Failed'; } }; + el.querySelectorAll('button[data-m]').forEach((b) => b.addEventListener('click', () => go(b.dataset.m))); + if (!t.modes) go(); + })); + return `

    Tools

    Small utilities. Everything except the IP check runs in your browser.

    ${tools.map((t) => `

    ${t.name}

    ${t.desc}
    + ${t.area ? '' : t.input ? `` : ''} + ${t.modes ? `
    ${t.modes.map(([m, l]) => ``).join('')}
    ` : ''}
    `).join('')}
    `; +} + +// ---- router ---- +async function render(path, push) { + const p = views[path] ? path : '/'; + if (push) history.pushState({}, '', path); + document.querySelectorAll('#nav a').forEach((a) => a.classList.toggle('on', a.getAttribute('href') === p)); + const titles = { '/': 'Overview', '/status': 'Status', '/news': 'News', '/tools': 'Tools', '/about': 'About' }; + document.title = (p === '/' ? '' : titles[p] + ' Β· ') + 'Status'; + main.innerHTML = await views[p](); + if (push) window.scrollTo(0, 0); +} +document.addEventListener('click', (e) => { + const a = e.target.closest('a[data-link]'); if (!a || e.metaKey || e.ctrlKey) return; + e.preventDefault(); render(a.getAttribute('href'), true); +}); +addEventListener('popstate', () => render(location.pathname)); +document.addEventListener('click', (e) => { + const b = e.target.closest('.info'); document.querySelectorAll('.tip').forEach((t) => t.remove()); + document.querySelectorAll('.info[aria-expanded=true]').forEach((x) => x !== b && x.setAttribute('aria-expanded', 'false')); + if (!b) return; + if (b.getAttribute('aria-expanded') === 'true') return b.setAttribute('aria-expanded', 'false'); + b.setAttribute('aria-expanded', 'true'); + const t = document.createElement('div'); t.className = 'tip'; t.setAttribute('role', 'tooltip'); t.textContent = b.dataset.info; b.parentElement.appendChild(t); +}); +document.addEventListener('keydown', (e) => { if (e.key === 'Escape') document.querySelectorAll('.tip').forEach((t) => t.remove()); }); +$('#yr').textContent = new Date().getFullYear(); +render(location.pathname.replace(/\/$/, '') || '/'); +setInterval(() => { if (!document.hidden && ['/', '/status'].includes(location.pathname)) render(location.pathname); }, 60e3); +// Broken icon -> neutral placeholder +document.addEventListener('error', (e) => { const i = e.target; if (i.tagName === 'IMG' && i.closest('.svc')) { const d = document.createElement('div'); d.className = 'ph'; i.replaceWith(d); } }, true); +// Branding from Admin β†’ Site +fetch('/api/site/brand').then((r) => r.json()).then((b) => { const n = document.getElementById('brand-name'); if (n && b.name) n.textContent = b.name; if (b.accent) document.documentElement.style.setProperty('--acc', b.accent); }).catch(() => {}); diff --git a/src/utils/colors.js b/src/utils/colors.js new file mode 100644 index 0000000..acde331 --- /dev/null +++ b/src/utils/colors.js @@ -0,0 +1,11 @@ +// Simple color output utility (alternative to chalk for compatibility) +module.exports = { + green: (str) => `\x1b[32m${str}\x1b[39m`, + cyan: (str) => `\x1b[36m${str}\x1b[39m`, + yellow: (str) => `\x1b[33m${str}\x1b[39m`, + red: (str) => `\x1b[31m${str}\x1b[39m`, + blue: (str) => `\x1b[34m${str}\x1b[39m`, + magenta: (str) => `\x1b[35m${str}\x1b[39m`, + gray: (str) => `\x1b[90m${str}\x1b[39m`, + bold: (str) => `\x1b[1m${str}\x1b[22m`, +}; diff --git a/src/views/admin/index.ejs b/src/views/admin/index.ejs new file mode 100644 index 0000000..17fa676 --- /dev/null +++ b/src/views/admin/index.ejs @@ -0,0 +1,2213 @@ + + + + + + LocalPing - Admin Panel + + + + + + + + + + + +
    +
    +
    +
    + + LocalPing Admin +
    + +
    +
    + +
    + +
    + +
    +
    + +
    +
    +
    +

    Monitors

    +
    +
    + + +
    +
    +
    + +
    +
    + + +
    + + + +
    + +

    Select a monitor to view details and edit settings

    +
    +
    +
    +
    + + +
    +
    +
    +

    Incidents

    + +
    +
    + +
    +
    +
    + + +
    +
    +
    +

    Event Detection Rules

    + +
    +
    + +
    +
    +
    + + +
    +
    +
    +

    Blog Posts

    + +
    +
    + +
    +
    +
    + + +
    +
    +

    Public Visibility

    +

    Configure which monitors and application links should be visible on the public status page. Private monitors will only be visible in the admin dashboard.

    + +
    +

    + Monitor Visibility +

    +
    + +
    +
    +
    +
    + + +
    +
    +

    Backup & Restore

    + + +
    +

    + Export Data +

    +

    Export your data as a JSON backup file. You can choose to export everything or select specific data types.

    + +
    +
    + +
    + +
    + + + + + + + + +
    + +
    + +
    +
    +
    + + +
    +

    + Import Data +

    +

    Import data from a previously exported backup file. Existing data will be skipped unless you enable overwrite mode.

    + +
    +
    + +

    When enabled, existing items with the same ID will be updated. Otherwise, they will be skipped.

    +
    + +
    + + +

    Select a JSON backup file to import

    +
    + +
    + +
    +
    +
    +
    +
    + + +
    +
    +

    Settings

    + + +
    +

    + Public UI Customization +

    +
    +
    + + +

    Main heading displayed on the public status page

    +
    +
    + + +

    Subtitle text displayed below the title

    +
    +
    + + +

    Custom CSS rules that will be applied only to the public status page

    +
    +
    + + +
    +
    +
    + + +
    +

    + Admin Settings +

    +
    +
    + + +
    +
    + +
    + + days + +
    +

    How long admin sessions remain active before requiring login again. Default: 30 days.

    +
    +
    + +
    + + days + +
    +

    How long to keep full historic data. Data older than this will be minimized (keeping only important data points). Default: 30 days.

    +
    +
    + +
    + + +
    +

    When enabled, detailed ping statistics will be logged to the server console. Useful for troubleshooting ping issues.

    +
    +
    + +

    Clear all historic ping data. This will not affect incidents or blog posts.

    +
    +

    Database Size

    +

    Loading...

    +
    + +
    +
    +
    + + +
    +

    + Notification Settings +

    +
    + +
    + +

    Enable external notifications (Discord webhooks, etc.)

    +
    + +
    + +
    + + minutes +
    +

    A monitor must stay down for this many whole minutes before down or recovery notifications are sent. Incident notifications are unaffected.

    +
    + + +
    +

    + Discord Webhook +

    +
    +
    + +
    +
    + + +

    Discord webhook URL. Create one in your Discord server settings.

    +
    +
    +
    + + +

    Bot username for Discord messages

    +
    +
    + + +

    Optional avatar image URL

    +
    +
    +
    + +

    Send a test notification to verify your webhook configuration

    +
    +
    +
    + + +
    +

    + Event Notifications +

    +

    Choose which events should trigger notifications

    +
    + + + + +
    +
    + + +
    + +
    +
    +
    + + +
    +
    +

    About

    +

    LocalPing - Homelab Dashboard & System Monitor

    +

    Version 1.0.0

    +

    + + GitHub Project + +

    +
    +
    +
    +
    +
    + + +
    +
    +
    +

    Create New Post

    + +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    + +
    +
    + + +
    +
    + +
    +

    Preview will appear here...

    +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + + +
    +
    +
    +

    Create New Incident

    + +
    +
    +
    +
    +
    + + +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    +
    + +

    Enable to schedule this incident for a future maintenance window

    +
    + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + + +
    +
    +
    +

    Create New Event Rule

    + +
    +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + + +

    Available variables: {{target.name}}, {{target.host}}, {{status}}, {{responseTime}}

    +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    +
    + + +
    + +
    + + +

    Prevent duplicate incidents within this time period

    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + + +
    + + +
    +
    +
    +

    + Clone Monitor +

    + +
    +
    +
    +

    + This will create a new monitor with the same settings as "". The new monitor will be disabled by default and will not include any historical data. +

    +

    + Are you sure you want to clone this monitor? +

    +
    + + +
    +
    +
    +
    +
    + + +
    +
    +
    +

    + Reset Monitor Data +

    + +
    +
    +
    +
    +

    + Warning +

    +

    + This will permanently delete all ping data for "". This includes: +

    +
      +
    • All ping results and response times
    • +
    • All statistics and uptime history
    • +
    +
    +

    + Monitor settings will NOT be affected. Only the historical ping data will be cleared. +

    +

    + Are you sure you want to reset this monitor's data? +

    +
    + + +
    +
    +
    +
    +
    + + +
    +
    +
    +

    + Clear All Ping Data +

    + +
    +
    +
    +
    +

    + Warning +

    +

    + This action will permanently delete all historic ping data. This includes: +

    +
      +
    • All ping results and response times
    • +
    • All statistics and uptime history
    • +
    • All daily statistics
    • +
    +

    + Incidents and blog posts will NOT be affected. +

    +
    +

    + Are you sure you want to proceed? This action cannot be undone. +

    +
    + + +
    +
    +
    +
    +
    + + + + diff --git a/src/views/admin/login.ejs b/src/views/admin/login.ejs new file mode 100644 index 0000000..04102a0 --- /dev/null +++ b/src/views/admin/login.ejs @@ -0,0 +1,144 @@ + + + + + + Admin Login - LocalPing + + + + +
    +
    + +
    +

    LocalPing

    +

    Admin Panel

    +
    + + +
    +

    Admin Login

    + + + +
    +
    + + +
    + +
    + + +
    + + +
    + +
    +

    + Forgot your password? Reset setup +

    +
    +
    + + +

    + LocalPing β€’ Homelab Dashboard & System Monitor +

    +
    +
    + + + + diff --git a/src/views/admin/site.html b/src/views/admin/site.html new file mode 100644 index 0000000..31f17a6 --- /dev/null +++ b/src/views/admin/site.html @@ -0,0 +1,21 @@ +Site settings Β· LocalPing + +
    ← Admin
    +

    Public site

    +

    Branding & app icon

    Used for the header, favicon and when installed as an app (PWA). PNG/WebP/JPEG/SVG, max 2 MB, square works best.

    +
    +
    +

    Services: explainers, tiers & links

    Tier decides placement (featured = shown first). Untick β€œLink” for private services so no link to them is shown publicly.

    +
    ServiceTierLinkExplainer (shown in β“˜)
    + diff --git a/src/views/layout.ejs b/src/views/layout.ejs new file mode 100644 index 0000000..d69e00e --- /dev/null +++ b/src/views/layout.ejs @@ -0,0 +1,37 @@ + + + + + + <%= typeof title !== 'undefined' ? title : 'LocalPing' %> + + + + + + + + + + + + + + + + + + <%- body %> + + diff --git a/src/views/public/index.ejs b/src/views/public/index.ejs new file mode 100644 index 0000000..37d6a47 --- /dev/null +++ b/src/views/public/index.ejs @@ -0,0 +1,1151 @@ + + + + + + <%= typeof title !== 'undefined' ? title : 'LocalPing' %> Β· LocalPing + + + + + + + + + + <% if (typeof customCSS !== 'undefined' && customCSS) { %> + + <% } %> + + +
    + +
    +
    +
    +
    + +

    <%= typeof title !== 'undefined' ? title : 'Homelab' %>

    +
    +
    +

    βœ“ Operational

    +

    -

    +
    +
    + + + +
    +
    + + +
    +
    + +
    + +
    + + +
    +
    +

    Apps

    +

    Loading...

    +
    + + +
    +
    Loading apps...
    +
    +
    +
    + + +
    + +
    +
    +
    + All systems are operational. No incidents reported. +
    +
    + + + + +
    +

    Services Status

    + Loading... +
    + + +
    +
    +
    Loading services...
    +
    +
    + + +
    +

    Incident History

    +

    View all reported incidents and their status

    +
    + +
    +
    +
    Loading incident history...
    +
    +
    +
    + + +
    +
    +

    Homelab Updates & Changelog

    +

    Latest updates and changes to the homelab infrastructure

    +
    + +
    +
    Loading posts...
    +
    +
    + +
    + +
    +
    +
    + + + +
    + + + + + + + diff --git a/src/views/setup/wizard.ejs b/src/views/setup/wizard.ejs new file mode 100644 index 0000000..25a3fe8 --- /dev/null +++ b/src/views/setup/wizard.ejs @@ -0,0 +1,185 @@ + + + + + + LocalPing Setup + + + + +
    +
    + +
    +

    LocalPing

    +

    Initial Setup Wizard

    +
    + + +
    + <% if (error) { %> +
    +

    Error: <%= error %>

    +
    + <% } %> + +
    + +
    +

    Admin Credentials

    + +
    + + +

    Used to log in to the admin panel

    +
    + +
    + + +
    + +
    + + +
    +
    + + +
    +

    Network Configuration

    + +
    + + +

    + <% if (detectedGateway) { %> + βœ“ Auto-detected: <%= detectedGateway %> (you can change this) + <% } else { %> + Enter your network gateway IP address + <% } %> +

    +
    +
    + + +
    +

    + Default monitors will be created for: +

    +
      +
    • βœ“ Gateway monitoring (ICMP ping)
    • +
    • βœ“ Cloudflare DNS at 1.1.1.1 (ICMP ping)
    • +
    +
    + + +
    + +
    + +

    + By completing setup, you agree that LocalPing will monitor your network +

    +
    +
    + + +

    + LocalPing β€’ Homelab Dashboard & System Monitor +

    +
    +
    + + + + diff --git a/test-api.js b/test-api.js new file mode 100755 index 0000000..ee94335 --- /dev/null +++ b/test-api.js @@ -0,0 +1,606 @@ +#!/usr/bin/env node +/** + * API Test Suite for LocalPing + * + * Tests CRUD operations on: + * - Monitors/Targets (via /api/* - requires API key) + * - Incidents (via /admin/api/* - requires session auth) + * - Blog Posts (via /admin/api/* - requires session auth) + * - Admin Settings (via /admin/api/* - requires session auth) + * + * Uses credentials from .env file for admin authentication. + * + * Usage: node test-api.js [baseUrl] [apiKey] + * Example: node test-api.js http://localhost:8000 your-api-key + */ + +const axios = require('axios'); +const fs = require('fs'); +const path = require('path'); + +// Simple color functions +const colors = { + blue: (s) => `\x1b[34m${s}\x1b[0m`, + green: (s) => `\x1b[32m${s}\x1b[0m`, + red: (s) => `\x1b[31m${s}\x1b[0m`, + yellow: (s) => `\x1b[33m${s}\x1b[0m`, + cyan: (s) => `\x1b[36m${s}\x1b[0m`, + white: (s) => s, +}; + +// Load .env file +function loadEnv() { + const envPath = path.join(process.cwd(), '.env'); + const env = {}; + if (fs.existsSync(envPath)) { + const content = fs.readFileSync(envPath, 'utf8'); + content.split('\n').forEach(line => { + const match = line.match(/^([^#=]+)=(.*)$/); + if (match) { + env[match[1].trim()] = match[2].trim(); + } + }); + } + return env; +} + +const env = loadEnv(); + +// Configuration +const BASE_URL = process.argv[2] || 'http://localhost:8000'; +const API_KEY = process.argv[3] || env.ADMIN_API_KEY || 'test-key'; +const ADMIN_USERNAME = env.ADMIN_USERNAME; +const ADMIN_PASSWORD = env.ADMIN_PASSWORD; + +// Test results +let passed = 0; +let failed = 0; +const errors = []; + +// Helper functions +function log(message, type = 'info') { + const colorMap = { + info: colors.blue, + success: colors.green, + error: colors.red, + warning: colors.yellow, + test: colors.cyan, + }; + const colorFn = colorMap[type] || colors.white; + console.log(colorFn(message)); +} + +function test(name, fn) { + return async () => { + try { + log(`\nπŸ§ͺ Testing: ${name}`, 'test'); + await fn(); + passed++; + log(`βœ… PASSED: ${name}`, 'success'); + } catch (error) { + failed++; + const errorMsg = error.response + ? `Status ${error.response.status}: ${error.response.data?.error || error.message}` + : error.message; + errors.push({ test: name, error: errorMsg }); + log(`❌ FAILED: ${name} - ${errorMsg}`, 'error'); + if (error.response?.data && error.response.status !== 401) { + console.log('Response:', JSON.stringify(error.response.data, null, 2)); + } + } + }; +} + +// Cookie storage for session +let sessionCookie = null; + +// API client for /api/* routes (uses API key) +const api = axios.create({ + baseURL: BASE_URL, + headers: { + 'X-API-Key': API_KEY, + 'Content-Type': 'application/json', + }, + validateStatus: () => true, +}); + +// Admin API client for /admin/api/* routes (uses session cookies) +const adminApi = axios.create({ + baseURL: BASE_URL, + headers: { + 'Content-Type': 'application/json', + }, + validateStatus: () => true, + withCredentials: true, +}); + +// Add cookie to admin requests +adminApi.interceptors.request.use(config => { + if (sessionCookie) { + config.headers.Cookie = sessionCookie; + } + return config; +}); + +// Extract cookie from admin responses +adminApi.interceptors.response.use(response => { + const setCookie = response.headers['set-cookie']; + if (setCookie && setCookie.length > 0) { + // Extract session cookie (usually the first one) + const cookie = setCookie.find(c => c.startsWith('connect.sid')) || setCookie[0]; + if (cookie) { + sessionCookie = cookie.split(';')[0]; // Get just the cookie name=value part + } + } + return response; +}); + +// Login to admin +async function loginAdmin() { + if (!ADMIN_USERNAME || !ADMIN_PASSWORD) { + throw new Error('ADMIN_USERNAME and ADMIN_PASSWORD must be set in .env file'); + } + + log('πŸ” Logging in to admin...', 'info'); + const response = await adminApi.post('/admin/login', { + username: ADMIN_USERNAME, + password: ADMIN_PASSWORD, + }); + + if (response.status !== 200 || !response.data.success) { + throw new Error(`Login failed: ${JSON.stringify(response.data)}`); + } + + // Extract cookie from response + const setCookie = response.headers['set-cookie']; + if (setCookie && setCookie.length > 0) { + const cookie = setCookie.find(c => c.startsWith('connect.sid')) || setCookie[0]; + if (cookie) { + sessionCookie = cookie.split(';')[0]; + log(` βœ… Logged in successfully`, 'success'); + return true; + } + } + + throw new Error('Login succeeded but no session cookie received'); +} + +// Test data storage +const testData = { + targetId: null, + incidentId: null, + postId: null, + notificationDelayMinutes: 5, +}; + +// ==================== TARGETS/MONITORS TESTS ==================== + +const testTargets = { + create: test('Create Target', async () => { + const target = { + name: `test-target-${Date.now()}`, + host: 'example.com', + protocol: 'HTTPS', + port: 443, + interval: 60, + enabled: true, + publicVisible: true, + publicShowDetails: false, + publicShowStatus: true, + publicShowAppLink: true, + important: false, + }; + + const response = await api.post('/api/targets', target); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to create target: ${JSON.stringify(response.data)}`); + } + testData.targetId = response.data.targetId; + log(` Created target with ID: ${testData.targetId}`); + }), + + getAll: test('Get All Targets', async () => { + const response = await api.get('/api/targets'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get targets: ${JSON.stringify(response.data)}`); + } + if (!Array.isArray(response.data.targets)) { + throw new Error('Targets is not an array'); + } + log(` Found ${response.data.targets.length} targets`); + }), + + getOne: test('Get Target by ID', async () => { + if (!testData.targetId) { + throw new Error('No target ID available (create test must run first)'); + } + const response = await api.get(`/api/targets/${testData.targetId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get target: ${JSON.stringify(response.data)}`); + } + if (response.data.target._id !== testData.targetId) { + throw new Error('Target ID mismatch'); + } + log(` Retrieved target: ${response.data.target.name}`); + }), + + update: test('Update Target', async () => { + if (!testData.targetId) { + throw new Error('No target ID available'); + } + const updates = { + name: `updated-target-${Date.now()}`, + interval: 120, + publicShowDetails: true, + publicVisible: false, + publicShowStatus: false, + }; + const response = await api.put(`/api/targets/${testData.targetId}`, updates); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to update target: ${JSON.stringify(response.data)}`); + } + const verify = await api.get(`/api/targets/${testData.targetId}`); + if (verify.status !== 200 || verify.data.target.publicVisible !== false || verify.data.target.publicShowStatus !== false) { + throw new Error(`Target visibility settings were not persisted: ${JSON.stringify(verify.data)}`); + } + log(` Updated target: ${updates.name}`); + }), + + getStatistics: test('Get Target Statistics', async () => { + if (!testData.targetId) { + throw new Error('No target ID available'); + } + const response = await api.get(`/api/targets/${testData.targetId}/statistics?days=30`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get statistics: ${JSON.stringify(response.data)}`); + } + log(` Retrieved statistics (${response.data.statistics?.length || 0} data points)`); + }), + + delete: test('Delete Target', async () => { + if (!testData.targetId) { + throw new Error('No target ID available'); + } + const response = await api.delete(`/api/targets/${testData.targetId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to delete target: ${JSON.stringify(response.data)}`); + } + log(` Deleted target: ${testData.targetId}`); + testData.targetId = null; + }), +}; + +// ==================== INCIDENTS TESTS ==================== + +const testIncidents = { + create: test('Create Incident', async () => { + const incident = { + title: `Test Incident ${Date.now()}`, + description: 'This is a test incident created by the API test suite', + severity: 'major', + status: 'investigating', + }; + + const response = await adminApi.post('/admin/api/incidents', incident); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to create incident: ${JSON.stringify(response.data)}`); + } + testData.incidentId = response.data.incident?._id || response.data.incidentId; + log(` Created incident with ID: ${testData.incidentId}`); + }), + + getAll: test('Get All Incidents', async () => { + const response = await adminApi.get('/admin/api/incidents'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get incidents: ${JSON.stringify(response.data)}`); + } + if (!Array.isArray(response.data.incidents)) { + throw new Error('Incidents is not an array'); + } + log(` Found ${response.data.incidents.length} incidents`); + }), + + getOne: test('Get Incident by ID', async () => { + if (!testData.incidentId) { + throw new Error('No incident ID available'); + } + const response = await adminApi.get(`/admin/api/incidents/${testData.incidentId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get incident: ${JSON.stringify(response.data)}`); + } + if (response.data.incident._id !== testData.incidentId) { + throw new Error('Incident ID mismatch'); + } + log(` Retrieved incident: ${response.data.incident.title}`); + }), + + update: test('Update Incident', async () => { + if (!testData.incidentId) { + throw new Error('No incident ID available'); + } + const updates = { + status: 'resolved', + description: 'Updated description', + }; + const response = await adminApi.put(`/admin/api/incidents/${testData.incidentId}`, updates); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to update incident: ${JSON.stringify(response.data)}`); + } + log(` Updated incident status to: ${updates.status}`); + }), + + delete: test('Delete Incident', async () => { + if (!testData.incidentId) { + throw new Error('No incident ID available'); + } + const response = await adminApi.delete(`/admin/api/incidents/${testData.incidentId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to delete incident: ${JSON.stringify(response.data)}`); + } + log(` Deleted incident: ${testData.incidentId}`); + testData.incidentId = null; + }), +}; + +// ==================== BLOG POSTS TESTS ==================== + +const testPosts = { + create: test('Create Blog Post', async () => { + const post = { + title: `Test Post ${Date.now()}`, + content: 'This is a test blog post created by the API test suite.\n\nIt has multiple paragraphs.', + published: true, + }; + + const response = await adminApi.post('/admin/api/posts', post); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to create post: ${JSON.stringify(response.data)}`); + } + testData.postId = response.data.post?._id || response.data.postId; + log(` Created post with ID: ${testData.postId}`); + }), + + getAll: test('Get All Posts', async () => { + const response = await adminApi.get('/admin/api/posts'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get posts: ${JSON.stringify(response.data)}`); + } + if (!Array.isArray(response.data.posts)) { + throw new Error('Posts is not an array'); + } + log(` Found ${response.data.posts.length} posts`); + }), + + getOne: test('Get Post by ID', async () => { + if (!testData.postId) { + throw new Error('No post ID available'); + } + const response = await adminApi.get(`/admin/api/posts/${testData.postId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get post: ${JSON.stringify(response.data)}`); + } + if (response.data.post._id !== testData.postId) { + throw new Error('Post ID mismatch'); + } + log(` Retrieved post: ${response.data.post.title}`); + }), + + update: test('Update Post', async () => { + if (!testData.postId) { + throw new Error('No post ID available'); + } + const updates = { + title: `Updated Post ${Date.now()}`, + content: 'Updated content', + published: false, + }; + const response = await adminApi.put(`/admin/api/posts/${testData.postId}`, updates); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to update post: ${JSON.stringify(response.data)}`); + } + log(` Updated post: ${updates.title}`); + }), + + delete: test('Delete Post', async () => { + if (!testData.postId) { + throw new Error('No post ID available'); + } + const response = await adminApi.delete(`/admin/api/posts/${testData.postId}`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to delete post: ${JSON.stringify(response.data)}`); + } + log(` Deleted post: ${testData.postId}`); + testData.postId = null; + }), +}; + +// ==================== OTHER API TESTS ==================== + +const testOther = { + healthCheck: test('Health Check', async () => { + const response = await api.get('/health'); + if (response.status !== 200) { + throw new Error(`Health check failed: ${response.status}`); + } + log(` Health check passed: ${response.data.status}`); + }), + + getAlerts: test('Get Alerts', async () => { + const response = await api.get('/api/alerts'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get alerts: ${JSON.stringify(response.data)}`); + } + if (!Array.isArray(response.data.alerts)) { + throw new Error('Alerts is not an array'); + } + log(` Found ${response.data.alerts.length} alerts`); + }), + + getPublicStatus: test('Get Public Status (no auth)', async () => { + const response = await axios.get(`${BASE_URL}/api/status`); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get public status: ${JSON.stringify(response.data)}`); + } + log(` Public status: ${response.data.status?.overallStatus || 'unknown'}`); + }), + + getPublicPages: test('Get Public Apps, Uptime, and Blog Pages', async () => { + for (const page of ['/', '/uptime', '/blog']) { + const response = await axios.get(`${BASE_URL}${page}`); + if (response.status !== 200 || !response.data.includes('LocalPing')) { + throw new Error(`Public page ${page} failed: ${response.status}`); + } + } + log(' Public routes returned the shared shell'); + }), + + getNotificationSettings: test('Get Notification Settings', async () => { + const response = await adminApi.get('/admin/api/notification-settings'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get notification settings: ${JSON.stringify(response.data)}`); + } + const delay = response.data.settings?.monitorDownDelayMinutes; + if (!Number.isInteger(delay) || delay < 1 || delay > 1440) { + throw new Error(`Invalid monitor notification delay: ${delay}`); + } + testData.notificationDelayMinutes = delay; + log(` Current outage notification delay: ${delay} minute(s)`); + }), + + updateNotificationSettings: test('Update Notification Settings', async () => { + const delay = testData.notificationDelayMinutes || 5; + const response = await adminApi.put('/admin/api/notification-settings', { + monitorDownDelayMinutes: delay, + }); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to update notification settings: ${JSON.stringify(response.data)}`); + } + log(` Notification delay accepted: ${delay} minute(s)`); + }), + + getSettings: test('Get Admin Settings', async () => { + const response = await adminApi.get('/admin/api/admin-settings'); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to get settings: ${JSON.stringify(response.data)}`); + } + log(` Retrieved admin settings`); + }), + + updateSettings: test('Update Admin Settings', async () => { + const settings = { + sessionDurationDays: 30, + dataRetentionDays: 60, + }; + const response = await adminApi.put('/admin/api/admin-settings', settings); + if (response.status !== 200 || !response.data.success) { + throw new Error(`Failed to update settings: ${JSON.stringify(response.data)}`); + } + log(` Updated settings`); + }), + + invalidApiKey: test('Test Invalid API Key', async () => { + const response = await axios.get(`${BASE_URL}/api/targets`, { + headers: { 'X-API-Key': 'invalid-key' }, + validateStatus: () => true, + }); + // API might return 200 with empty data or 401/403 + if (response.status === 200 && response.data?.success === false) { + log(` Correctly rejected invalid API key (status: ${response.status})`); + } else if (response.status >= 400) { + log(` Correctly rejected invalid API key (status: ${response.status})`); + } else { + log(` API accepted request (may not require auth for GET) - status: ${response.status}`); + } + }), +}; + +// ==================== RUN ALL TESTS ==================== + +async function runAllTests() { + log('\n' + '='.repeat(60), 'info'); + log('πŸš€ Starting API Test Suite', 'info'); + log(`Base URL: ${BASE_URL}`, 'info'); + log(`API Key: ${API_KEY.substring(0, 8)}...`, 'info'); + if (ADMIN_USERNAME) { + log(`Admin Username: ${ADMIN_USERNAME}`, 'info'); + } else { + log(`⚠️ ADMIN_USERNAME not found in .env`, 'warning'); + } + log('='.repeat(60), 'info'); + + // Login to admin first + try { + await loginAdmin(); + } catch (error) { + log(`\n❌ Failed to login to admin: ${error.message}`, 'error'); + log(' Admin API tests will be skipped', 'warning'); + } + + // Test order matters - create before read, read before update, etc. + const testSuites = [ + { name: 'Health & Basic', tests: [testOther.healthCheck, testOther.invalidApiKey] }, + { name: 'Targets/Monitors', tests: [ + testTargets.create, + testTargets.getAll, + testTargets.getOne, + testTargets.getStatistics, + testTargets.update, + testTargets.delete, + ]}, + { name: 'Incidents', tests: [ + testIncidents.create, + testIncidents.getAll, + testIncidents.getOne, + testIncidents.update, + testIncidents.delete, + ]}, + { name: 'Blog Posts', tests: [ + testPosts.create, + testPosts.getAll, + testPosts.getOne, + testPosts.update, + testPosts.delete, + ]}, + { name: 'Other Endpoints', tests: [ + testOther.getAlerts, + testOther.getPublicStatus, + testOther.getPublicPages, + testOther.getSettings, + testOther.updateSettings, + testOther.getNotificationSettings, + testOther.updateNotificationSettings, + ]}, + ]; + + for (const suite of testSuites) { + log(`\nπŸ“¦ Test Suite: ${suite.name}`, 'test'); + for (const testFn of suite.tests) { + await testFn(); + } + } + + // Summary + log('\n' + '='.repeat(60), 'info'); + log('πŸ“Š Test Summary', 'info'); + log('='.repeat(60), 'info'); + log(`βœ… Passed: ${passed}`, 'success'); + log(`❌ Failed: ${failed}`, failed > 0 ? 'error' : 'success'); + log(`πŸ“ˆ Total: ${passed + failed}`, 'info'); + + if (errors.length > 0) { + log('\n❌ Failed Tests:', 'error'); + errors.forEach(({ test, error }) => { + log(` β€’ ${test}: ${error}`, 'error'); + }); + } + + log('\n' + '='.repeat(60), 'info'); + process.exit(failed > 0 ? 1 : 0); +} + +// Run tests +runAllTests().catch(error => { + log(`\nπŸ’₯ Fatal error: ${error.message}`, 'error'); + console.error(error); + process.exit(1); +});