Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

refactor(frontend): Decouple state and componentize UI rendering

sassanixaed0389e77ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8e31e0..0449be1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,82 @@
# Changelog
+## 1.0.3 - 2025-11-07
+
+### Added
+- **Vite build tool (multi-page app) for the frontend**
+ - Initialized npm in `frontend/` with `dev`, `build`, and `preview` scripts.
+ - Introduced `vite.config.js` with `root: 'src'`, `outDir: '../dist'`, `publicDir: 'public'`, a development `/api` proxy, and explicit multi-page HTML inputs.
+ - Restructured frontend: moved sources to `frontend/src/` and static/non-module assets to `frontend/public/`.
+ - _Files: `frontend/package.json`, `frontend/vite.config.js`, `frontend/src/**/*`, `frontend/public/**/*`_
+
+- **Centralized Authentication Service**
+ - New module `authService.js` exposes `initAuth`, `login`, `logout`, `getToken`, `getCurrentUser`, `isAuthenticated`.
+ - Backwards compatibility: attaches a `window.auth` facade so existing code continues to work.
+ - Handles header UI state, user menu/settings dropdown toggling, and dispatches a unified `authStateReady` event.
+ - Robustly hides “Create Account” UI when registration is disabled (with a MutationObserver to keep it hidden after other scripts mutate the DOM).
+ - _Files: `frontend/src/js/services/authService.js`, `frontend/src/*.html` (module includes)_
+
+- **Dedicated API Service**
+ - New `apiService.js` provides a `baseRequest` wrapper that injects the `Authorization` header and normalizes error handling.
+ - Exposes named helpers (e.g., `getWarranties`, `updateWarranty`, `deleteWarranty`, `getStatistics`, `savePreferences`) and a `window.api` shim for non-module scripts.
+ - Safe global `fetch` shim adds the Authorization header for `/api/...` calls when missing.
+ - _Files: `frontend/src/js/services/apiService.js`, `frontend/src/*.html` (module includes)_
+
+ - **Central State Management Store**
+ - Introduced a `store.js` module to act as a single source of truth for application data (warranties, filters, loading states), eliminating scattered global variables.
+ - UI updates are now driven by custom events, creating a predictable data flow.
+ - _Files: `frontend/src/js/store.js`_
+
+- **Component-Based UI Modules**
+ - Created a suite of new, reusable UI component modules to replace HTML string concatenation. Each is responsible for building a specific part of the UI via safe DOM manipulation.
+ - Modules include: `warrantyCard.js`, `tag.js`, `modals.js`, `editModal.js`, `claims.js`, `notes.js`, `paperless.js`, and `ui.js`.
+ - _Files: `frontend/src/js/components/*`_
+
+- **HTML `<template>` for Warranty Cards**
+ - Added a `<template id="warranty-card-template">` to `index.html` to define the warranty card structure, separating markup from rendering logic for improved performance and maintainability.
+ - _Files: `frontend/src/index.html`_
+
+### Enhanced
+- **Dockerfile: multi-stage frontend build + runtime serving**
+ - Added `frontend-build` stage using `node:20-alpine` to run `npm ci && npm run build`.
+ - Final stage copies `frontend/dist/` to `/var/www/html` and includes `frontend/public/` assets in the build.
+ - Unpinned Node digest to resolve `not found` errors on some hosts.
+ - _Files: `Dockerfile`_
+
+- **HTML and asset loading**
+ - Switched all page `<script>` and `<link>` paths to root-relative (e.g., `/script.js`).
+ - Ensured `script.js` is loaded with `defer` across pages to avoid early DOM access issues.
+ - Moved non-module assets (e.g., `i18n.js`, `i18next*.js`, `script.js`, `theme-loader.js`, etc.) to `frontend/public/` so they are served verbatim in production.
+ - _Files: `frontend/src/*.html`, `frontend/public/**/*`_
+
+- **Build stability**
+ - Moved `settings-styles.css` to `public/` to bypass a PostCSS parse error in production builds (no functional/visual changes).
+ - _Files: `frontend/public/settings-styles.css`_
+
+- **Major UI Refactor for Maintainability & Security**
+ - Replaced nearly all `innerHTML` assignments with a robust, component-based rendering approach. This makes the UI easier to debug, maintain, and more secure against XSS vulnerabilities.
+ - **Warranty List:** The main warranty display for grid, list, and table views is now rendered using the `warrantyCard.js` component.
+ - **Edit Modal:** The complex dynamic sections (serial numbers, current document displays for invoices/manuals/photos, and tag selection) are now built with the `editModal.js` component.
+ - **Claims Modal:** The entire claims view, including the header, loading/error states, and claims list, is now rendered by the `claims.js` component.
+ - **Other Modals:** Refactored the rendering logic for the Tag Management, Notes, and Paperless-ngx document browser modals to use their respective new components.
+ - _Files: `frontend/src/script.js`, `frontend/src/js/components/*`_
+
+### Fixed
+- 404s for non-module assets in production by serving them from Vite `public/`.
+- User menu not opening: restored click/close listeners within `authService.js`.
+- Login page “Create Account” visible while registration disabled: force-hidden with strong CSS and observer.
+- Status page edit actions blocked by early `document.body.appendChild(...)`: added `defer` to `script.js` includes.
+- **Security:** Mitigated potential cross-site scripting (XSS) vulnerabilities by removing reliance on building the UI with `innerHTML` from dynamic data.
+- **Performance:** Improved rendering performance by using efficient DOM creation and appending (`<template>` clones, `document.createElement`) instead of causing the browser to re-parse large HTML strings on every update.
+- **Code Quality:** Drastically reduced code complexity and repetition in `script.js` by delegating UI creation to specialized component modules.
+
+### Removed
+- Legacy, scattered auth scripts now replaced by `authService.js`:
+ - `frontend/src/auth.js`, `frontend/src/auth-new.js`, `frontend/src/include-auth-new.js`, `frontend/src/fix-auth-buttons.js`, `frontend/src/fix-auth-buttons-loader.js`, `frontend/src/registration-status.js`.
+ - **Global State Variables**
+ - Eliminated global variables like `let warranties = []` and `let currentFilters = {}` from `script.js`, centralizing all state management within `store.js`.
+- **Hardcoded HTML Strings**
+ - Removed large, multi-line HTML string templates from JavaScript files, which were fragile and difficult to maintain.
+
## 1.0.2 - 2025-10-30
diff --git a/frontend/auth-new.js b/frontend/auth-new.js
deleted file mode 100644
index 15e414b..0000000
--- a/frontend/auth-new.js
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Authentication functionality for Warracker (New UI)
- * Handles user login, logout, and authentication state management for the new UI design
- */
-
-// Authentication state
-let currentUser = null;
-let authToken = null;
-
-// Initialize authentication
-document.addEventListener('DOMContentLoaded', () => {
- console.log('Initializing auth-new.js for new UI');
-
- // Initial check of authentication state
- checkAuthState();
-
- // Set up periodic check of auth state (every 30 seconds)
- setInterval(checkAuthState, 30000);
-
- // Set up logout functionality
- setupLogout();
-});
-
-/**
- * Set up logout functionality
- */
-function setupLogout() {
- // Look for logout button in the new UI
- const logoutButton = document.querySelector('.logout-btn');
-
- if (logoutButton) {
- console.log('Found logout button in new UI');
-
- // Add click event to logout
- logoutButton.addEventListener('click', (e) => {
- e.preventDefault();
- logout();
- });
- }
-}
-
-/**
- * Check if user is authenticated and update UI accordingly
- */
-function checkAuthState() {
- console.log('Checking auth state for new UI');
-
- // Get auth token from localStorage
- authToken = localStorage.getItem('auth_token');
- const userInfo = localStorage.getItem('user_info');
-
- if (authToken && userInfo) {
- try {
- currentUser = JSON.parse(userInfo);
- updateUIForAuthenticatedUser();
- validateToken();
- } catch (error) {
- console.error('Error parsing user info:', error);
- clearAuthData();
- updateUIForUnauthenticatedUser();
- }
- } else {
- updateUIForUnauthenticatedUser();
- }
-}
-
-/**
- * Update UI elements for authenticated user in the new UI
- */
-function updateUIForAuthenticatedUser() {
- console.log('Updating UI for authenticated user');
-
- // Find login/register buttons in the new UI based on the screenshot
- const loginButton = document.querySelector('a[href="login.html"], a.login');
- const registerButton = document.querySelector('a[href="register.html"], a.register');
-
- // Hide login/register buttons if they exist
- if (loginButton) {
- console.log('Hiding login button');
- loginButton.style.display = 'none';
- }
-
- if (registerButton) {
- console.log('Hiding register button');
- registerButton.style.display = 'none';
- }
-
- // Show user info if it exists
- const userDisplay = document.querySelector('.user-display');
- if (userDisplay && currentUser) {
- let displayName = currentUser.username || 'User';
- userDisplay.textContent = displayName;
- userDisplay.style.display = 'inline-block';
- }
-}
-
-/**
- * Update UI elements for unauthenticated user in the new UI
- */
-function updateUIForUnauthenticatedUser() {
- console.log('Updating UI for unauthenticated user');
-
- // Find login/register buttons in the new UI based on the screenshot
- const loginButton = document.querySelector('a[href="login.html"], a.login');
- const registerButton = document.querySelector('a[href="register.html"], a.register');
-
- // Show login/register buttons if they exist
- if (loginButton) {
- console.log('Showing login button');
- loginButton.style.display = 'inline-block';
- }
-
- if (registerButton) {
- console.log('Showing register button');
- registerButton.style.display = 'inline-block';
- }
-
- // Hide user info if it exists
- const userDisplay = document.querySelector('.user-display');
- if (userDisplay) {
- userDisplay.style.display = 'none';
- }
-}
-
-/**
- * Logout user
- */
-async function logout() {
- try {
- console.log('Logging out user');
-
- // Call logout API
- const response = await fetch('/api/auth/logout', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${authToken}`,
- 'Content-Type': 'application/json'
- }
- });
-
- // Clear auth data regardless of API response
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- // Show success message
- console.log('Logged out successfully');
-
- // Reload page to refresh UI
- window.location.reload();
-
- } catch (error) {
- console.error('Logout error:', error);
-
- // Still clear auth data even if API call fails
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- console.log('Logged out with errors');
- }
-}
-
-/**
- * Clear authentication data from localStorage
- */
-function clearAuthData() {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- authToken = null;
- currentUser = null;
-}
-
-/**
- * Validate token with the server
- */
-async function validateToken() {
- if (!authToken) {
- clearAuthData();
- updateUIForUnauthenticatedUser();
- return;
- }
-
- try {
- // Use the full URL to avoid path issues
- const apiUrl = window.location.origin + '/api/auth/validate-token';
-
- const response = await fetch(apiUrl, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${authToken}`
- }
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- console.error('Token validation failed:', errorData.message);
- throw new Error(errorData.message || 'Invalid token');
- }
-
- // Token is valid, update last active time
- const data = await response.json();
- if (data.user) {
- currentUser = data.user;
- localStorage.setItem('user_info', JSON.stringify(currentUser));
- updateUIForAuthenticatedUser();
- }
-
- return true;
- } catch (error) {
- console.error('Token validation error:', error);
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- return false;
- }
-}
-
-// Export authentication functions for use in other scripts
-window.authNew = {
- isAuthenticated: () => !!authToken,
- getCurrentUser: () => currentUser,
- getToken: () => authToken,
- checkAuthState,
- logout
-};
\ No newline at end of file
diff --git a/frontend/auth.js b/frontend/auth.js
deleted file mode 100644
index cd9ac8f..0000000
--- a/frontend/auth.js
+++ /dev/null
@@ -1,364 +0,0 @@
-/**
- * Authentication functionality for Warracker
- * Handles user login, logout, and authentication state management
- */
-
-class AuthManager {
- constructor() {
- this.token = null;
- this.currentUser = null;
- this.onLogoutCallbacks = [];
-
- // Initial state load from localStorage
- this.token = localStorage.getItem('auth_token');
- const userInfoString = localStorage.getItem('user_info');
- if (userInfoString) {
- try {
- this.currentUser = JSON.parse(userInfoString);
- } catch (e) {
- console.error('Auth.js: Corrupt user_info in localStorage. Clearing.');
- this.currentUser = null;
- localStorage.removeItem('user_info');
- // Consider clearing token as well if user_info is corrupt
- // localStorage.removeItem('auth_token');
- // this.token = null;
- }
- }
- console.log('[Auth.js] Initial state:', { token: this.token ? 'present' : 'null', currentUser: this.currentUser });
- }
-
- isAuthenticated() {
- // User is authenticated if both token and currentUser (with an id) are present
- return !!(this.token && this.currentUser && this.currentUser.id);
- }
-
- getCurrentUser() {
- return this.currentUser;
- }
-
- getToken() {
- // Always return the current state of this.token, which should be synced with localStorage
- return this.token;
- }
-
- clearAuthData() {
- console.log('[Auth.js] Clearing auth data.');
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- this.token = null;
- this.currentUser = null;
- this.onLogoutCallbacks.forEach(cb => cb());
- }
-
- onLogout(callback) {
- if (typeof callback === 'function') {
- this.onLogoutCallbacks.push(callback);
- }
- }
-
- async checkAuthState(isInitialLoad = false) {
- console.log('[Auth.js] checkAuthState called. Initial load:', isInitialLoad);
- this.token = localStorage.getItem('auth_token'); // Re-read token, might have changed (e.g. by auth-redirect.js)
- const userInfoString = localStorage.getItem('user_info');
-
- this.currentUser = null; // Reset before check
-
- if (userInfoString) {
- try {
- this.currentUser = JSON.parse(userInfoString);
- } catch (e) {
- console.error('Auth.js: Failed to parse user_info from localStorage during checkAuthState. Clearing auth data.', e);
- this.clearAuthData(); // Clear potentially corrupt data
- this.updateUIBasedOnAuthState(); // Update UI to reflect logged-out state
- return; // Exit early
- }
- }
-
- if (this.token) {
- // If token exists, try to validate it and fetch/confirm user_info
- // This is crucial if user_info was missing or to refresh/validate existing user_info
- console.log('[Auth.js] Token found. Validating and fetching user info...');
- try {
- const response = await fetch('/api/auth/validate-token', {
- headers: { 'Authorization': `Bearer ${this.token}` }
- });
-
- if (response.ok) {
- const data = await response.json();
- if (data.valid && data.user && data.user.id) {
- this.currentUser = data.user;
- localStorage.setItem('user_info', JSON.stringify(this.currentUser)); // Ensure localStorage is up-to-date
- console.log('[Auth.js] Token validated, user_info updated/confirmed:', this.currentUser);
- } else {
- console.warn('[Auth.js] Token validation failed or user data invalid from API. Clearing auth data.');
- this.clearAuthData();
- }
- } else {
- console.warn(`[Auth.js] Token validation API call failed (status: ${response.status}). Clearing auth data.`);
- this.clearAuthData();
- }
- } catch (error) {
- console.error('[Auth.js] Error validating token / fetching user info:', error);
- this.clearAuthData();
- }
- } else {
- // No token, ensure everything is cleared
- if (this.currentUser) { // If there was user_info but no token, clear user_info
- console.log('[Auth.js] No token found, but user_info was present. Clearing user_info.');
- this.clearAuthData();
- }
- }
-
- this.updateUIBasedOnAuthState();
- }
-
- updateUIBasedOnAuthState() {
- const isAuthenticated = this.isAuthenticated();
- this._updateDOMForAuthState(isAuthenticated, this.currentUser);
- this.dispatchAuthStateEvent(isAuthenticated, this.currentUser);
- }
-
- _updateDOMForAuthState(isAuthenticated, user) {
- const authContainer = document.getElementById('authContainer');
- const userMenu = document.getElementById('userMenu');
- const userDisplayName = document.getElementById('userDisplayName');
- const userNameMenu = document.getElementById('userName');
- const userEmailMenu = document.getElementById('userEmail');
- const logoutMenuItem = document.getElementById('logoutMenuItem');
-
- // Select all potential login/register buttons more broadly
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn');
- const genericAuthButtonsContainers = document.querySelectorAll('.auth-buttons');
-
-
- if (isAuthenticated && user) {
- console.log('Auth.js: Updating UI for AUTHENTICATED user:', user);
- if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden'; }
-
- if (userMenu) {
- userMenu.style.display = 'block'; // Or 'flex' based on CSS
- userMenu.style.visibility = 'visible';
- const displayNameText = user.first_name || user.username || 'User';
- const fullNameText = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';
- if (userDisplayName) userDisplayName.textContent = displayNameText;
- if (userNameMenu) userNameMenu.textContent = fullNameText;
- if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;
- }
- loginButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });
- registerButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });
- genericAuthButtonsContainers.forEach(container => {
- if (container.id !== 'authContainer') { // Avoid double-hiding if authContainer also has .auth-buttons
- container.style.display = 'none'; container.style.visibility = 'hidden';
- }
- });
-
- if (logoutMenuItem) {
- logoutMenuItem.style.display = 'flex'; // Assuming it's a flex item
- // Ensure logout listener is attached (can be done once in constructor or DOMContentLoaded)
- }
- } else {
- console.log('Auth.js: Updating UI for UNAUTHENTICATED user.');
- if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }
-
- if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }
-
- // Reset user display names if they exist
- if (userDisplayName) userDisplayName.textContent = 'User';
- if (userNameMenu) userNameMenu.textContent = 'User Name';
- if (userEmailMenu) userEmailMenu.textContent = '[email protected]';
-
- loginButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });
- registerButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });
- genericAuthButtonsContainers.forEach(container => {
- if (container.id !== 'authContainer') {
- container.style.display = 'flex'; // Or 'block'
- container.style.visibility = 'visible';
- }
- });
- if (logoutMenuItem) { logoutMenuItem.style.display = 'none'; }
- }
- }
-
- dispatchAuthStateEvent(isAuthenticated, user) {
- console.log('[Auth.js] Dispatching authStateReady event', { isAuthenticated, user });
- // Ensure this event is dispatched after the current call stack clears
- setTimeout(() => {
- window.dispatchEvent(new CustomEvent('authStateReady', {
- detail: { isAuthenticated, user }
- }));
- }, 0);
- }
-
- async login(username, password) {
- // Assuming showLoading/hideLoading are global or part of another module
- if (typeof showLoading === 'function') showLoading();
- try {
- const response = await fetch('/api/auth/login', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ username, password })
- });
- const data = await response.json();
- if (response.ok) {
- this.token = data.token;
- this.currentUser = data.user;
- localStorage.setItem('auth_token', this.token);
- localStorage.setItem('user_info', JSON.stringify(this.currentUser));
- this.updateUIBasedOnAuthState();
- return data; // Return data for login.js to handle redirect
- } else {
- throw new Error(data.message || 'Login failed');
- }
- } catch (error) {
- this.clearAuthData(); // Ensure state is cleared on login failure
- this.updateUIBasedOnAuthState();
- throw error; // Re-throw for login.js to handle
- } finally {
- if (typeof hideLoading === 'function') hideLoading();
- }
- }
-
- async logout() {
- if (typeof showLoading === 'function') showLoading();
- const currentTokenForApiCall = this.token; // Use current token for API call
-
- this.clearAuthData(); // Clear local state immediately
- this.updateUIBasedOnAuthState(); // Update UI to logged-out state
-
- try {
- if (currentTokenForApiCall) {
- await fetch('/api/auth/logout', {
- method: 'POST',
- headers: { 'Authorization': `Bearer ${currentTokenForApiCall}` }
- });
- console.log('[Auth.js] Logout API call successful.');
- }
- } catch (error) {
- console.error('[Auth.js] Logout API call failed, but user is logged out locally.', error);
- } finally {
- if (typeof hideLoading === 'function') hideLoading();
- // Redirect to login page after all operations
- if (window.location.pathname !== '/login.html') {
- window.location.href = 'login.html';
- }
- }
- }
-
- addAuthHeader(options = {}) {
- const token = this.getToken();
- if (!token) return options;
-
- const headers = options.headers || {};
- return { ...options, headers: { ...headers, 'Authorization': `Bearer ${token}`}};
- }
-}
-
-// Initialize and export
-window.auth = new AuthManager();
-
-// Initial check on DOMContentLoaded
-document.addEventListener('DOMContentLoaded', async () => {
- console.log('[Auth.js] DOMContentLoaded - performing initial async auth state check.');
- await window.auth.checkAuthState(true); // Ensure auth state is processed first
-
- // Setup user menu toggle
- const userMenuBtn_original = document.getElementById('userMenuBtn');
- const userMenuDropdown = document.getElementById('userMenuDropdown');
-
- if (userMenuBtn_original && userMenuDropdown) {
- console.log('[Auth.js] Setting up user menu. Button:', userMenuBtn_original, 'Dropdown:', userMenuDropdown);
-
- // Robust listener attachment: clone the button to remove any prior listeners
- const userMenuBtn = userMenuBtn_original.cloneNode(true);
- userMenuBtn_original.parentNode.replaceChild(userMenuBtn, userMenuBtn_original);
-
- userMenuBtn.addEventListener('click', (e) => {
- e.stopPropagation(); // Prevent click from immediately closing due to document listener
- console.log('[Auth.js] userMenuBtn clicked - DEBUG INFO:', {
- userMenuDropdown: !!userMenuDropdown,
- dropdownClassList: userMenuDropdown ? Array.from(userMenuDropdown.classList) : 'not found',
- hasActiveClass: userMenuDropdown ? userMenuDropdown.classList.contains('active') : 'dropdown not found',
- buttonId: userMenuBtn.id,
- dropdownId: userMenuDropdown ? userMenuDropdown.id : 'not found'
- });
-
- userMenuDropdown.classList.toggle('active');
-
- const isNowActive = userMenuDropdown.classList.contains('active');
- console.log('[Auth.js] User menu toggled via userMenuBtn. Active:', isNowActive);
-
- // Add a temporary debug check to see if it gets closed immediately
- setTimeout(() => {
- const stillActive = userMenuDropdown.classList.contains('active');
- console.log('[Auth.js] User menu status after 100ms:', stillActive);
- if (isNowActive && !stillActive) {
- console.warn('[Auth.js] User menu was closed immediately! Possible global click interference.');
- }
- }, 100);
- });
- console.log('[Auth.js] User menu click listener attached to userMenuBtn.');
- } else {
- console.warn('[Auth.js] User menu button (userMenuBtn) or dropdown (userMenuDropdown) not found. Menu interactivity might be affected.');
- }
-
- // Setup settings gear menu toggle (if elements exist on the current page)
- const settingsBtn_original = document.getElementById('settingsBtn');
- const settingsMenu = document.getElementById('settingsMenu'); // The dropdown menu itself
- if (settingsBtn_original && settingsMenu) {
- const settingsBtn = settingsBtn_original.cloneNode(true);
- settingsBtn_original.parentNode.replaceChild(settingsBtn, settingsBtn_original);
-
- settingsBtn.addEventListener('click', function(e) {
- e.stopPropagation();
- settingsMenu.classList.toggle('active');
- console.log('[Auth.js] Settings menu toggled via settingsBtn.');
- });
- console.log('[Auth.js] Settings menu click listener attached to settingsBtn.');
- }
-
- // Global click listener to close dropdowns - ensure this is added only once
- if (!window._authJsGlobalClickListenerAdded) {
- document.addEventListener('click', (e) => {
- console.log('[Auth.js] Global click detected on:', e.target);
-
- // Re-fetch elements by ID inside the listener to ensure they are current
- const currentDropdown = document.getElementById('userMenuDropdown');
- const currentButton = document.getElementById('userMenuBtn'); // Use the standardized ID
-
- if (currentDropdown && currentButton && currentDropdown.classList.contains('active')) {
- console.log('[Auth.js] User menu is active, checking if click is outside...');
- const isOutsideDropdown = !currentDropdown.contains(e.target);
- const isOutsideButton = !currentButton.contains(e.target);
- console.log('[Auth.js] Click outside dropdown:', isOutsideDropdown, 'outside button:', isOutsideButton);
-
- if (isOutsideDropdown && isOutsideButton) {
- currentDropdown.classList.remove('active');
- console.log('[Auth.js] User menu closed by global click.');
- }
- }
-
- const currentSettingsMenu = document.getElementById('settingsMenu');
- const currentSettingsBtn = document.getElementById('settingsBtn');
- if (currentSettingsMenu && currentSettingsBtn && currentSettingsMenu.classList.contains('active') &&
- !currentSettingsMenu.contains(e.target) && !currentSettingsBtn.contains(e.target)) {
- currentSettingsMenu.classList.remove('active');
- console.log('[Auth.js] Settings menu closed by global click.');
- }
- });
- window._authJsGlobalClickListenerAdded = true;
- console.log('[Auth.js] Global click listener for dropdowns added.');
- }
-
- // Attach logout listener to logout menu item
- const logoutMenuItem_original = document.getElementById('logoutMenuItem');
- if (logoutMenuItem_original) {
- const logoutMenuItem = logoutMenuItem_original.cloneNode(true); // Ensures fresh listener
- logoutMenuItem_original.parentNode.replaceChild(logoutMenuItem, logoutMenuItem_original);
- logoutMenuItem.addEventListener('click', () => {
- console.log('[Auth.js] Logout menu item clicked.');
- window.auth.logout();
- });
- console.log('[Auth.js] Logout menu item listener attached.');
- }
-});
diff --git a/frontend/fix-auth-buttons-loader.js b/frontend/fix-auth-buttons-loader.js
deleted file mode 100644
index 1331153..0000000
--- a/frontend/fix-auth-buttons-loader.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Script to load the fix-auth-buttons.js script on all pages
- * This script should be included in the head of each HTML file
- */
-
-// Log authentication status for debugging
-console.log('fix-auth-buttons-loader.js is running');
-console.log('Auth token exists:', !!localStorage.getItem('auth_token'));
-console.log('User info exists:', !!localStorage.getItem('user_info'));
-
-// Execute immediately to hide buttons as soon as possible
-if (localStorage.getItem('auth_token')) {
- console.log('User is logged in, attempting to hide login/register buttons immediately');
-
- // Hide auth container if it exists
- const authContainer = document.getElementById('authContainer');
- if (authContainer) {
- console.log('Found authContainer, hiding it');
- authContainer.style.display = 'none';
- }
-
- // Hide individual buttons if they exist
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
-
- console.log('Found login buttons:', loginButtons.length);
- console.log('Found register buttons:', registerButtons.length);
-
- loginButtons.forEach(button => button.style.display = 'none');
- registerButtons.forEach(button => button.style.display = 'none');
-
- // Show user menu if it exists
- const userMenu = document.getElementById('userMenu');
- if (userMenu) {
- console.log('Found userMenu, showing it');
- userMenu.style.display = 'block';
- }
-}
-
-// Create a script element to load the actual fix script
-const script = document.createElement('script');
-script.src = 'fix-auth-buttons.js';
-script.async = true;
-
-// Add the script to the document
-document.head.appendChild(script);
-
-console.log('Added fix-auth-buttons.js script to the page');
\ No newline at end of file
diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.js
deleted file mode 100644
index d6eead0..0000000
--- a/frontend/fix-auth-buttons.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Script to fix the login and register buttons in the new UI
- * This script specifically targets the buttons shown in the screenshot
- */
-
-// Log execution
-console.log('fix-auth-buttons.js loaded and executing');
-
-// Function to check if user is authenticated
-function isAuthenticated() {
- const token = localStorage.getItem('auth_token');
- // console.log('Auth token check:', !!token); // Keep console logs minimal here if auth.js is primary
- return !!token;
-}
-
-// Function to find elements by text content
-function getElementsByText(selector, text) {
- const elements = document.querySelectorAll(selector);
- return Array.prototype.filter.call(elements, element => element.textContent.trim() === text);
-}
-
-// Function to hide login and register buttons if user is authenticated
-function updateAuthButtons() {
- // console.log('fix-auth-buttons.js: updateAuthButtons executing...'); // Keep console logs minimal here
- if (isAuthenticated()) {
- // console.log('fix-auth-buttons.js: User is authenticated, hiding login/register buttons');
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
- const authContainer = document.getElementById('authContainer');
- const userMenu = document.getElementById('userMenu'); // Ensure this ID is consistent or use userMenuBtn's parent
-
- loginButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });
- registerButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });
- if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden';}
- if (userMenu) { userMenu.style.display = 'block'; userMenu.style.visibility = 'visible'; }
-
- const userInfo = localStorage.getItem('user_info');
- if (userInfo) {
- try {
- const user = JSON.parse(userInfo);
- const displayName = user.first_name || user.username || 'User';
- const userDisplayName = document.getElementById('userDisplayName');
- if (userDisplayName) userDisplayName.textContent = displayName;
-
- const userNameMenu = document.getElementById('userName');
- if (userNameMenu) {
- userNameMenu.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';
- }
- const userEmailMenu = document.getElementById('userEmail');
- if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;
- } catch (error) { /* console.error('fix-auth-buttons.js: Error parsing user info:', error); */ }
- }
- } else {
- // console.log('fix-auth-buttons.js: User is not authenticated, showing login/register buttons');
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
- const authContainer = document.getElementById('authContainer');
- const userMenu = document.getElementById('userMenu');
-
- loginButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });
- registerButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });
- if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }
- if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }
- }
-}
-
-// Run immediately
-// console.log('Running updateAuthButtons immediately from fix-auth-buttons.js');
-updateAuthButtons();
-
-// Update auth buttons when page loads
-document.addEventListener('DOMContentLoaded', () => {
- // console.log('DOMContentLoaded event triggered in fix-auth-buttons.js, updating auth buttons');
- updateAuthButtons();
- // REMOVE: setupUserMenuDropdown();
-});
\ No newline at end of file
diff --git a/frontend/include-auth-new.js b/frontend/include-auth-new.js
deleted file mode 100644
index 56e55f2..0000000
--- a/frontend/include-auth-new.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * Immediate Authentication State Handler
- *
- * This script runs as soon as possible to hide login/register buttons if a user is logged in
- * It should be included directly in the HTML before any other scripts
- */
-
-console.log('include-auth-new.js: Running immediate auth check');
-
-// Function to update UI based on auth state (extracted for reuse)
-function updateAuthUI() {
- if (localStorage.getItem('auth_token')) {
- console.log('include-auth-new.js: Updating UI for authenticated user');
- // Inject CSS to hide auth buttons and show user menu
- const styleId = 'auth-ui-style';
- let style = document.getElementById(styleId);
- if (!style) {
- style = document.createElement('style');
- style.id = styleId;
- document.head.appendChild(style);
- }
- style.textContent = `
- #authContainer, .auth-buttons, a[href="login.html"], a[href="register.html"],
- .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
- display: none !important;
- visibility: hidden !important;
- }
- #userMenu, .user-menu {
- display: block !important;
- visibility: visible !important;
- }
- `;
-
- // Update user info display elements immediately
- try {
- var userInfoStr = localStorage.getItem('user_info');
- if (userInfoStr) {
- var userInfo = JSON.parse(userInfoStr);
- var displayName = userInfo.username || 'User';
- var userDisplayName = document.getElementById('userDisplayName');
- if (userDisplayName) userDisplayName.textContent = displayName;
- var userName = document.getElementById('userName');
- if (userName) {
- userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
- if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
- }
- var userEmail = document.getElementById('userEmail');
- if (userEmail && userInfo.email) userEmail.textContent = userInfo.email;
- }
- } catch (e) {
- console.error('include-auth-new.js: Error updating user info display:', e);
- }
-
- } else {
- console.log('include-auth-new.js: Updating UI for logged-out user');
- // Inject CSS to show auth buttons and hide user menu
- const styleId = 'auth-ui-style';
- let style = document.getElementById(styleId);
- if (!style) {
- style = document.createElement('style');
- style.id = styleId;
- document.head.appendChild(style);
- }
- style.textContent = `
- #authContainer, .auth-buttons {
- display: flex !important; /* Use flex for container */
- visibility: visible !important;
- }
- a[href="login.html"], a[href="register.html"],
- .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
- display: inline-block !important; /* Use inline-block for buttons */
- visibility: visible !important;
- }
- #userMenu, .user-menu {
- display: none !important;
- visibility: hidden !important;
- }
- `;
- }
-}
-
-// Immediately check auth state and update UI
-updateAuthUI();
-
-// Listen for changes to localStorage and update UI without reloading
-window.addEventListener('storage', function(event) {
- if (event.key === 'auth_token' || event.key === 'user_info') {
- console.log(`include-auth-new.js: Storage event detected for ${event.key}. Updating UI.`);
- updateAuthUI(); // Update UI instead of reloading
- // window.location.reload(); // <-- Keep commented out / Remove permanently
- }
-});
-
-/**
- * Script to include the new authentication script in existing HTML files
- * This script should be included at the end of the body in each HTML file
- */
-
-// Function to load and execute the new authentication script
-function loadAuthNewScript() {
- // Create a script element
- const script = document.createElement('script');
- script.src = 'auth-new.js';
- script.async = true;
-
- // Add the script to the document
- document.body.appendChild(script);
-
- console.log('Added auth-new.js script to the page');
-}
-
-// Function to check if we're using the new UI
-function isNewUI() {
- // Check for elements that are specific to the new UI
- const loginButton = document.querySelector('a[href="login.html"].auth-btn, a.login');
- const registerButton = document.querySelector('a[href="register.html"].auth-btn, a.register');
-
- // If we find these elements, we're using the new UI
- return !!(loginButton || registerButton);
-}
-
-// Load the new authentication script if we're using the new UI
-if (isNewUI()) {
- console.log('Detected new UI, loading auth-new.js');
- loadAuthNewScript();
-} else {
- console.log('Using old UI, not loading auth-new.js');
-}
\ No newline at end of file
diff --git a/frontend/node_modules/.bin/esbuild b/frontend/node_modules/.bin/esbuild
new file mode 100644
index 0000000..63bb6d4
--- /dev/null
+++ b/frontend/node_modules/.bin/esbuild
@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+ *CYGWIN*|*MINGW*|*MSYS*)
+ if command -v cygpath > /dev/null 2>&1; then
+ basedir=`cygpath -w "$basedir"`
+ fi
+ ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+ exec "$basedir/node" "$basedir/../esbuild/bin/esbuild" "$@"
+else
+ exec node "$basedir/../esbuild/bin/esbuild" "$@"
+fi
diff --git a/frontend/node_modules/.bin/esbuild.cmd b/frontend/node_modules/.bin/esbuild.cmd
new file mode 100644
index 0000000..cc920c5
--- /dev/null
+++ b/frontend/node_modules/.bin/esbuild.cmd
@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+ SET "_prog=%dp0%\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esbuild\bin\esbuild" %*
diff --git a/frontend/node_modules/.bin/esbuild.ps1 b/frontend/node_modules/.bin/esbuild.ps1
new file mode 100644
index 0000000..81ffbf9
--- /dev/null
+++ b/frontend/node_modules/.bin/esbuild.ps1
@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+ # Fix case when both the Windows and Linux builds of Node
+ # are installed in the same directory
+ $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args
+ } else {
+ & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args
+ }
+ $ret=$LASTEXITCODE
+} else {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args
+ } else {
+ & "node$exe" "$basedir/../esbuild/bin/esbuild" $args
+ }
+ $ret=$LASTEXITCODE
+}
+exit $ret
diff --git a/frontend/node_modules/.bin/nanoid b/frontend/node_modules/.bin/nanoid
new file mode 100644
index 0000000..46220bd
--- /dev/null
+++ b/frontend/node_modules/.bin/nanoid
@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+ *CYGWIN*|*MINGW*|*MSYS*)
+ if command -v cygpath > /dev/null 2>&1; then
+ basedir=`cygpath -w "$basedir"`
+ fi
+ ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+ exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@"
+else
+ exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@"
+fi
diff --git a/frontend/node_modules/.bin/nanoid.cmd b/frontend/node_modules/.bin/nanoid.cmd
new file mode 100644
index 0000000..9c40107
--- /dev/null
+++ b/frontend/node_modules/.bin/nanoid.cmd
@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+ SET "_prog=%dp0%\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %*
diff --git a/frontend/node_modules/.bin/nanoid.ps1 b/frontend/node_modules/.bin/nanoid.ps1
new file mode 100644
index 0000000..d8a4d7a
--- /dev/null
+++ b/frontend/node_modules/.bin/nanoid.ps1
@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+ # Fix case when both the Windows and Linux builds of Node
+ # are installed in the same directory
+ $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
+ } else {
+ & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
+ }
+ $ret=$LASTEXITCODE
+} else {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
+ } else {
+ & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
+ }
+ $ret=$LASTEXITCODE
+}
+exit $ret
diff --git a/frontend/node_modules/.bin/rollup b/frontend/node_modules/.bin/rollup
new file mode 100644
index 0000000..998fc16
--- /dev/null
+++ b/frontend/node_modules/.bin/rollup
@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+ *CYGWIN*|*MINGW*|*MSYS*)
+ if command -v cygpath > /dev/null 2>&1; then
+ basedir=`cygpath -w "$basedir"`
+ fi
+ ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+ exec "$basedir/node" "$basedir/../rollup/dist/bin/rollup" "$@"
+else
+ exec node "$basedir/../rollup/dist/bin/rollup" "$@"
+fi
diff --git a/frontend/node_modules/.bin/rollup.cmd b/frontend/node_modules/.bin/rollup.cmd
new file mode 100644
index 0000000..b3f110b
--- /dev/null
+++ b/frontend/node_modules/.bin/rollup.cmd
@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+ SET "_prog=%dp0%\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\rollup\dist\bin\rollup" %*
diff --git a/frontend/node_modules/.bin/rollup.ps1 b/frontend/node_modules/.bin/rollup.ps1
new file mode 100644
index 0000000..10f657d
--- /dev/null
+++ b/frontend/node_modules/.bin/rollup.ps1
@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+ # Fix case when both the Windows and Linux builds of Node
+ # are installed in the same directory
+ $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args
+ } else {
+ & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args
+ }
+ $ret=$LASTEXITCODE
+} else {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args
+ } else {
+ & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args
+ }
+ $ret=$LASTEXITCODE
+}
+exit $ret
diff --git a/frontend/node_modules/.bin/vite b/frontend/node_modules/.bin/vite
new file mode 100644
index 0000000..014463f
--- /dev/null
+++ b/frontend/node_modules/.bin/vite
@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+ *CYGWIN*|*MINGW*|*MSYS*)
+ if command -v cygpath > /dev/null 2>&1; then
+ basedir=`cygpath -w "$basedir"`
+ fi
+ ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+ exec "$basedir/node" "$basedir/../vite/bin/vite.js" "$@"
+else
+ exec node "$basedir/../vite/bin/vite.js" "$@"
+fi
diff --git a/frontend/node_modules/.bin/vite.cmd b/frontend/node_modules/.bin/vite.cmd
new file mode 100644
index 0000000..f62e966
--- /dev/null
+++ b/frontend/node_modules/.bin/vite.cmd
@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+ SET "_prog=%dp0%\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\vite\bin\vite.js" %*
diff --git a/frontend/node_modules/.bin/vite.ps1 b/frontend/node_modules/.bin/vite.ps1
new file mode 100644
index 0000000..a7759bc
--- /dev/null
+++ b/frontend/node_modules/.bin/vite.ps1
@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+ # Fix case when both the Windows and Linux builds of Node
+ # are installed in the same directory
+ $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args
+ } else {
+ & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args
+ }
+ $ret=$LASTEXITCODE
+} else {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "node$exe" "$basedir/../vite/bin/vite.js" $args
+ } else {
+ & "node$exe" "$basedir/../vite/bin/vite.js" $args
+ }
+ $ret=$LASTEXITCODE
+}
+exit $ret
diff --git a/frontend/node_modules/.package-lock.json b/frontend/node_modules/.package-lock.json
new file mode 100644
index 0000000..45b53fd
--- /dev/null
+++ b/frontend/node_modules/.package-lock.json
@@ -0,0 +1,1099 @@
+{
+ "name": "frontend",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz",
+ "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz",
+ "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz",
+ "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz",
+ "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz",
+ "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz",
+ "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz",
+ "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz",
+ "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz",
+ "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz",
+ "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz",
+ "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz",
+ "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz",
+ "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz",
+ "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz",
+ "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz",
+ "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz",
+ "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz",
+ "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz",
+ "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz",
+ "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz",
+ "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz",
+ "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz",
+ "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz",
+ "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz",
+ "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz",
+ "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz",
+ "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz",
+ "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz",
+ "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz",
+ "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz",
+ "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz",
+ "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz",
+ "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz",
+ "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz",
+ "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz",
+ "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz",
+ "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz",
+ "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz",
+ "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz",
+ "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz",
+ "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz",
+ "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz",
+ "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz",
+ "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz",
+ "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz",
+ "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.11",
+ "@esbuild/android-arm": "0.25.11",
+ "@esbuild/android-arm64": "0.25.11",
+ "@esbuild/android-x64": "0.25.11",
+ "@esbuild/darwin-arm64": "0.25.11",
+ "@esbuild/darwin-x64": "0.25.11",
+ "@esbuild/freebsd-arm64": "0.25.11",
+ "@esbuild/freebsd-x64": "0.25.11",
+ "@esbuild/linux-arm": "0.25.11",
+ "@esbuild/linux-arm64": "0.25.11",
+ "@esbuild/linux-ia32": "0.25.11",
+ "@esbuild/linux-loong64": "0.25.11",
+ "@esbuild/linux-mips64el": "0.25.11",
+ "@esbuild/linux-ppc64": "0.25.11",
+ "@esbuild/linux-riscv64": "0.25.11",
+ "@esbuild/linux-s390x": "0.25.11",
+ "@esbuild/linux-x64": "0.25.11",
+ "@esbuild/netbsd-arm64": "0.25.11",
+ "@esbuild/netbsd-x64": "0.25.11",
+ "@esbuild/openbsd-arm64": "0.25.11",
+ "@esbuild/openbsd-x64": "0.25.11",
+ "@esbuild/openharmony-arm64": "0.25.11",
+ "@esbuild/sunos-x64": "0.25.11",
+ "@esbuild/win32-arm64": "0.25.11",
+ "@esbuild/win32-ia32": "0.25.11",
+ "@esbuild/win32-x64": "0.25.11"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "ideallyInert": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.6",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz",
+ "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.52.5",
+ "@rollup/rollup-android-arm64": "4.52.5",
+ "@rollup/rollup-darwin-arm64": "4.52.5",
+ "@rollup/rollup-darwin-x64": "4.52.5",
+ "@rollup/rollup-freebsd-arm64": "4.52.5",
+ "@rollup/rollup-freebsd-x64": "4.52.5",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.52.5",
+ "@rollup/rollup-linux-arm-musleabihf": "4.52.5",
+ "@rollup/rollup-linux-arm64-gnu": "4.52.5",
+ "@rollup/rollup-linux-arm64-musl": "4.52.5",
+ "@rollup/rollup-linux-loong64-gnu": "4.52.5",
+ "@rollup/rollup-linux-ppc64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-musl": "4.52.5",
+ "@rollup/rollup-linux-s390x-gnu": "4.52.5",
+ "@rollup/rollup-linux-x64-gnu": "4.52.5",
+ "@rollup/rollup-linux-x64-musl": "4.52.5",
+ "@rollup/rollup-openharmony-arm64": "4.52.5",
+ "@rollup/rollup-win32-arm64-msvc": "4.52.5",
+ "@rollup/rollup-win32-ia32-msvc": "4.52.5",
+ "@rollup/rollup-win32-x64-gnu": "4.52.5",
+ "@rollup/rollup-win32-x64-msvc": "4.52.5",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/vite": {
+ "version": "7.1.12",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz",
+ "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.25.0",
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3",
+ "postcss": "^8.5.6",
+ "rollup": "^4.43.0",
+ "tinyglobby": "^0.2.15"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "lightningcss": "^1.21.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/node_modules/.vite/deps/_metadata.json b/frontend/node_modules/.vite/deps/_metadata.json
new file mode 100644
index 0000000..5362a72
--- /dev/null
+++ b/frontend/node_modules/.vite/deps/_metadata.json
@@ -0,0 +1,8 @@
+{
+ "hash": "32ad9593",
+ "configHash": "6f44e4d2",
+ "lockfileHash": "87309cfc",
+ "browserHash": "44972cb6",
+ "optimized": {},
+ "chunks": {}
+}
\ No newline at end of file
diff --git a/frontend/node_modules/.vite/deps/package.json b/frontend/node_modules/.vite/deps/package.json
new file mode 100644
index 0000000..3dbc1ca
--- /dev/null
+++ b/frontend/node_modules/.vite/deps/package.json
@@ -0,0 +1,3 @@
+{
+ "type": "module"
+}
diff --git a/frontend/node_modules/@esbuild/win32-x64/README.md b/frontend/node_modules/@esbuild/win32-x64/README.md
new file mode 100644
index 0000000..a99ee7c
--- /dev/null
+++ b/frontend/node_modules/@esbuild/win32-x64/README.md
@@ -0,0 +1,3 @@
+# esbuild
+
+This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
diff --git a/frontend/node_modules/@esbuild/win32-x64/esbuild.exe b/frontend/node_modules/@esbuild/win32-x64/esbuild.exe
new file mode 100644
index 0000000..f9e5a14
Binary files /dev/null and b/frontend/node_modules/@esbuild/win32-x64/esbuild.exe differ
diff --git a/frontend/node_modules/@esbuild/win32-x64/package.json b/frontend/node_modules/@esbuild/win32-x64/package.json
new file mode 100644
index 0000000..65b161e
--- /dev/null
+++ b/frontend/node_modules/@esbuild/win32-x64/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@esbuild/win32-x64",
+ "version": "0.25.11",
+ "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/evanw/esbuild.git"
+ },
+ "license": "MIT",
+ "preferUnplugged": true,
+ "engines": {
+ "node": ">=18"
+ },
+ "os": [
+ "win32"
+ ],
+ "cpu": [
+ "x64"
+ ]
+}
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-gnu/README.md b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/README.md
new file mode 100644
index 0000000..e8a624b
--- /dev/null
+++ b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/README.md
@@ -0,0 +1,3 @@
+# `@rollup/rollup-win32-x64-gnu`
+
+This is the **x86_64-pc-windows-gnu** binary for `rollup`
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-gnu/package.json b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/package.json
new file mode 100644
index 0000000..23f0e6b
--- /dev/null
+++ b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@rollup/rollup-win32-x64-gnu",
+ "version": "4.52.5",
+ "os": [
+ "win32"
+ ],
+ "cpu": [
+ "x64"
+ ],
+ "files": [
+ "rollup.win32-x64-gnu.node"
+ ],
+ "description": "Native bindings for Rollup",
+ "author": "Lukas Taegert-Atkinson",
+ "homepage": "https://rollupjs.org/",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/rollup/rollup.git"
+ },
+ "main": "./rollup.win32-x64-gnu.node"
+}
\ No newline at end of file
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-gnu/rollup.win32-x64-gnu.node b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/rollup.win32-x64-gnu.node
new file mode 100644
index 0000000..cc01776
Binary files /dev/null and b/frontend/node_modules/@rollup/rollup-win32-x64-gnu/rollup.win32-x64-gnu.node differ
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-msvc/README.md b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/README.md
new file mode 100644
index 0000000..7382dbc
--- /dev/null
+++ b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/README.md
@@ -0,0 +1,3 @@
+# `@rollup/rollup-win32-x64-msvc`
+
+This is the **x86_64-pc-windows-msvc** binary for `rollup`
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-msvc/package.json b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/package.json
new file mode 100644
index 0000000..1abccfe
--- /dev/null
+++ b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@rollup/rollup-win32-x64-msvc",
+ "version": "4.52.5",
+ "os": [
+ "win32"
+ ],
+ "cpu": [
+ "x64"
+ ],
+ "files": [
+ "rollup.win32-x64-msvc.node"
+ ],
+ "description": "Native bindings for Rollup",
+ "author": "Lukas Taegert-Atkinson",
+ "homepage": "https://rollupjs.org/",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/rollup/rollup.git"
+ },
+ "main": "./rollup.win32-x64-msvc.node"
+}
\ No newline at end of file
diff --git a/frontend/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node
new file mode 100644
index 0000000..de98c26
Binary files /dev/null and b/frontend/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node differ
diff --git a/frontend/node_modules/@types/estree/LICENSE b/frontend/node_modules/@types/estree/LICENSE
new file mode 100644
index 0000000..9e841e7
--- /dev/null
+++ b/frontend/node_modules/@types/estree/LICENSE
@@ -0,0 +1,21 @@
+ MIT License
+
+ Copyright (c) Microsoft Corporation.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/frontend/node_modules/@types/estree/README.md b/frontend/node_modules/@types/estree/README.md
new file mode 100644
index 0000000..3a8c041
--- /dev/null
+++ b/frontend/node_modules/@types/estree/README.md
@@ -0,0 +1,15 @@
+# Installation
+> `npm install --save @types/estree`
+
+# Summary
+This package contains type definitions for estree (https://github.com/estree/estree).
+
+# Details
+Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree.
+
+### Additional Details
+ * Last updated: Fri, 06 Jun 2025 00:04:33 GMT
+ * Dependencies: none
+
+# Credits
+These definitions were written by [RReverser](https://github.com/RReverser).
diff --git a/frontend/node_modules/@types/estree/flow.d.ts b/frontend/node_modules/@types/estree/flow.d.ts
new file mode 100644
index 0000000..9d001a9
--- /dev/null
+++ b/frontend/node_modules/@types/estree/flow.d.ts
@@ -0,0 +1,167 @@
+declare namespace ESTree {
+ interface FlowTypeAnnotation extends Node {}
+
+ interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {}
+
+ interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {}
+
+ interface FlowDeclaration extends Declaration {}
+
+ interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {}
+
+ interface ArrayTypeAnnotation extends FlowTypeAnnotation {
+ elementType: FlowTypeAnnotation;
+ }
+
+ interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
+
+ interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {}
+
+ interface ClassImplements extends Node {
+ id: Identifier;
+ typeParameters?: TypeParameterInstantiation | null;
+ }
+
+ interface ClassProperty {
+ key: Expression;
+ value?: Expression | null;
+ typeAnnotation?: TypeAnnotation | null;
+ computed: boolean;
+ static: boolean;
+ }
+
+ interface DeclareClass extends FlowDeclaration {
+ id: Identifier;
+ typeParameters?: TypeParameterDeclaration | null;
+ body: ObjectTypeAnnotation;
+ extends: InterfaceExtends[];
+ }
+
+ interface DeclareFunction extends FlowDeclaration {
+ id: Identifier;
+ }
+
+ interface DeclareModule extends FlowDeclaration {
+ id: Literal | Identifier;
+ body: BlockStatement;
+ }
+
+ interface DeclareVariable extends FlowDeclaration {
+ id: Identifier;
+ }
+
+ interface FunctionTypeAnnotation extends FlowTypeAnnotation {
+ params: FunctionTypeParam[];
+ returnType: FlowTypeAnnotation;
+ rest?: FunctionTypeParam | null;
+ typeParameters?: TypeParameterDeclaration | null;
+ }
+
+ interface FunctionTypeParam {
+ name: Identifier;
+ typeAnnotation: FlowTypeAnnotation;
+ optional: boolean;
+ }
+
+ interface GenericTypeAnnotation extends FlowTypeAnnotation {
+ id: Identifier | QualifiedTypeIdentifier;
+ typeParameters?: TypeParameterInstantiation | null;
+ }
+
+ interface InterfaceExtends extends Node {
+ id: Identifier | QualifiedTypeIdentifier;
+ typeParameters?: TypeParameterInstantiation | null;
+ }
+
+ interface InterfaceDeclaration extends FlowDeclaration {
+ id: Identifier;
+ typeParameters?: TypeParameterDeclaration | null;
+ extends: InterfaceExtends[];
+ body: ObjectTypeAnnotation;
+ }
+
+ interface IntersectionTypeAnnotation extends FlowTypeAnnotation {
+ types: FlowTypeAnnotation[];
+ }
+
+ interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {}
+
+ interface NullableTypeAnnotation extends FlowTypeAnnotation {
+ typeAnnotation: TypeAnnotation;
+ }
+
+ interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
+
+ interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {}
+
+ interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
+
+ interface StringTypeAnnotation extends FlowBaseTypeAnnotation {}
+
+ interface TupleTypeAnnotation extends FlowTypeAnnotation {
+ types: FlowTypeAnnotation[];
+ }
+
+ interface TypeofTypeAnnotation extends FlowTypeAnnotation {
+ argument: FlowTypeAnnotation;
+ }
+
+ interface TypeAlias extends FlowDeclaration {
+ id: Identifier;
+ typeParameters?: TypeParameterDeclaration | null;
+ right: FlowTypeAnnotation;
+ }
+
+ interface TypeAnnotation extends Node {
+ typeAnnotation: FlowTypeAnnotation;
+ }
+
+ interface TypeCastExpression extends Expression {
+ expression: Expression;
+ typeAnnotation: TypeAnnotation;
+ }
+
+ interface TypeParameterDeclaration extends Node {
+ params: Identifier[];
+ }
+
+ interface TypeParameterInstantiation extends Node {
+ params: FlowTypeAnnotation[];
+ }
+
+ interface ObjectTypeAnnotation extends FlowTypeAnnotation {
+ properties: ObjectTypeProperty[];
+ indexers: ObjectTypeIndexer[];
+ callProperties: ObjectTypeCallProperty[];
+ }
+
+ interface ObjectTypeCallProperty extends Node {
+ value: FunctionTypeAnnotation;
+ static: boolean;
+ }
+
+ interface ObjectTypeIndexer extends Node {
+ id: Identifier;
+ key: FlowTypeAnnotation;
+ value: FlowTypeAnnotation;
+ static: boolean;
+ }
+
+ interface ObjectTypeProperty extends Node {
+ key: Expression;
+ value: FlowTypeAnnotation;
+ optional: boolean;
+ static: boolean;
+ }
+
+ interface QualifiedTypeIdentifier extends Node {
+ qualification: Identifier | QualifiedTypeIdentifier;
+ id: Identifier;
+ }
+
+ interface UnionTypeAnnotation extends FlowTypeAnnotation {
+ types: FlowTypeAnnotation[];
+ }
+
+ interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {}
+}
diff --git a/frontend/node_modules/@types/estree/index.d.ts b/frontend/node_modules/@types/estree/index.d.ts
new file mode 100644
index 0000000..2bc66fb
--- /dev/null
+++ b/frontend/node_modules/@types/estree/index.d.ts
@@ -0,0 +1,694 @@
+// This definition file follows a somewhat unusual format. ESTree allows
+// runtime type checks based on the `type` parameter. In order to explain this
+// to typescript we want to use discriminated union types:
+// https://github.com/Microsoft/TypeScript/pull/9163
+//
+// For ESTree this is a bit tricky because the high level interfaces like
+// Node or Function are pulling double duty. We want to pass common fields down
+// to the interfaces that extend them (like Identifier or
+// ArrowFunctionExpression), but you can't extend a type union or enforce
+// common fields on them. So we've split the high level interfaces into two
+// types, a base type which passes down inherited fields, and a type union of
+// all types which extend the base type. Only the type union is exported, and
+// the union is how other types refer to the collection of inheriting types.
+//
+// This makes the definitions file here somewhat more difficult to maintain,
+// but it has the notable advantage of making ESTree much easier to use as
+// an end user.
+
+export interface BaseNodeWithoutComments {
+ // Every leaf interface that extends BaseNode must specify a type property.
+ // The type property should be a string literal. For example, Identifier
+ // has: `type: "Identifier"`
+ type: string;
+ loc?: SourceLocation | null | undefined;
+ range?: [number, number] | undefined;
+}
+
+export interface BaseNode extends BaseNodeWithoutComments {
+ leadingComments?: Comment[] | undefined;
+ trailingComments?: Comment[] | undefined;
+}
+
+export interface NodeMap {
+ AssignmentProperty: AssignmentProperty;
+ CatchClause: CatchClause;
+ Class: Class;
+ ClassBody: ClassBody;
+ Expression: Expression;
+ Function: Function;
+ Identifier: Identifier;
+ Literal: Literal;
+ MethodDefinition: MethodDefinition;
+ ModuleDeclaration: ModuleDeclaration;
+ ModuleSpecifier: ModuleSpecifier;
+ Pattern: Pattern;
+ PrivateIdentifier: PrivateIdentifier;
+ Program: Program;
+ Property: Property;
+ PropertyDefinition: PropertyDefinition;
+ SpreadElement: SpreadElement;
+ Statement: Statement;
+ Super: Super;
+ SwitchCase: SwitchCase;
+ TemplateElement: TemplateElement;
+ VariableDeclarator: VariableDeclarator;
+}
+
+export type Node = NodeMap[keyof NodeMap];
+
+export interface Comment extends BaseNodeWithoutComments {
+ type: "Line" | "Block";
+ value: string;
+}
+
+export interface SourceLocation {
+ source?: string | null | undefined;
+ start: Position;
+ end: Position;
+}
+
+export interface Position {
+ /** >= 1 */
+ line: number;
+ /** >= 0 */
+ column: number;
+}
+
+export interface Program extends BaseNode {
+ type: "Program";
+ sourceType: "script" | "module";
+ body: Array<Directive | Statement | ModuleDeclaration>;
+ comments?: Comment[] | undefined;
+}
+
+export interface Directive extends BaseNode {
+ type: "ExpressionStatement";
+ expression: Literal;
+ directive: string;
+}
+
+export interface BaseFunction extends BaseNode {
+ params: Pattern[];
+ generator?: boolean | undefined;
+ async?: boolean | undefined;
+ // The body is either BlockStatement or Expression because arrow functions
+ // can have a body that's either. FunctionDeclarations and
+ // FunctionExpressions have only BlockStatement bodies.
+ body: BlockStatement | Expression;
+}
+
+export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
+
+export type Statement =
+ | ExpressionStatement
+ | BlockStatement
+ | StaticBlock
+ | EmptyStatement
+ | DebuggerStatement
+ | WithStatement
+ | ReturnStatement
+ | LabeledStatement
+ | BreakStatement
+ | ContinueStatement
+ | IfStatement
+ | SwitchStatement
+ | ThrowStatement
+ | TryStatement
+ | WhileStatement
+ | DoWhileStatement
+ | ForStatement
+ | ForInStatement
+ | ForOfStatement
+ | Declaration;
+
+export interface BaseStatement extends BaseNode {}
+
+export interface EmptyStatement extends BaseStatement {
+ type: "EmptyStatement";
+}
+
+export interface BlockStatement extends BaseStatement {
+ type: "BlockStatement";
+ body: Statement[];
+ innerComments?: Comment[] | undefined;
+}
+
+export interface StaticBlock extends Omit<BlockStatement, "type"> {
+ type: "StaticBlock";
+}
+
+export interface ExpressionStatement extends BaseStatement {
+ type: "ExpressionStatement";
+ expression: Expression;
+}
+
+export interface IfStatement extends BaseStatement {
+ type: "IfStatement";
+ test: Expression;
+ consequent: Statement;
+ alternate?: Statement | null | undefined;
+}
+
+export interface LabeledStatement extends BaseStatement {
+ type: "LabeledStatement";
+ label: Identifier;
+ body: Statement;
+}
+
+export interface BreakStatement extends BaseStatement {
+ type: "BreakStatement";
+ label?: Identifier | null | undefined;
+}
+
+export interface ContinueStatement extends BaseStatement {
+ type: "ContinueStatement";
+ label?: Identifier | null | undefined;
+}
+
+export interface WithStatement extends BaseStatement {
+ type: "WithStatement";
+ object: Expression;
+ body: Statement;
+}
+
+export interface SwitchStatement extends BaseStatement {
+ type: "SwitchStatement";
+ discriminant: Expression;
+ cases: SwitchCase[];
+}
+
+export interface ReturnStatement extends BaseStatement {
+ type: "ReturnStatement";
+ argument?: Expression | null | undefined;
+}
+
+export interface ThrowStatement extends BaseStatement {
+ type: "ThrowStatement";
+ argument: Expression;
+}
+
+export interface TryStatement extends BaseStatement {
+ type: "TryStatement";
+ block: BlockStatement;
+ handler?: CatchClause | null | undefined;
+ finalizer?: BlockStatement | null | undefined;
+}
+
+export interface WhileStatement extends BaseStatement {
+ type: "WhileStatement";
+ test: Expression;
+ body: Statement;
+}
+
+export interface DoWhileStatement extends BaseStatement {
+ type: "DoWhileStatement";
+ body: Statement;
+ test: Expression;
+}
+
+export interface ForStatement extends BaseStatement {
+ type: "ForStatement";
+ init?: VariableDeclaration | Expression | null | undefined;
+ test?: Expression | null | undefined;
+ update?: Expression | null | undefined;
+ body: Statement;
+}
+
+export interface BaseForXStatement extends BaseStatement {
+ left: VariableDeclaration | Pattern;
+ right: Expression;
+ body: Statement;
+}
+
+export interface ForInStatement extends BaseForXStatement {
+ type: "ForInStatement";
+}
+
+export interface DebuggerStatement extends BaseStatement {
+ type: "DebuggerStatement";
+}
+
+export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
+
+export interface BaseDeclaration extends BaseStatement {}
+
+export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
+ type: "FunctionDeclaration";
+ /** It is null when a function declaration is a part of the `export default function` statement */
+ id: Identifier | null;
+ body: BlockStatement;
+}
+
+export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
+ id: Identifier;
+}
+
+export interface VariableDeclaration extends BaseDeclaration {
+ type: "VariableDeclaration";
+ declarations: VariableDeclarator[];
+ kind: "var" | "let" | "const" | "using" | "await using";
+}
+
+export interface VariableDeclarator extends BaseNode {
+ type: "VariableDeclarator";
+ id: Pattern;
+ init?: Expression | null | undefined;
+}
+
+export interface ExpressionMap {
+ ArrayExpression: ArrayExpression;
+ ArrowFunctionExpression: ArrowFunctionExpression;
+ AssignmentExpression: AssignmentExpression;
+ AwaitExpression: AwaitExpression;
+ BinaryExpression: BinaryExpression;
+ CallExpression: CallExpression;
+ ChainExpression: ChainExpression;
+ ClassExpression: ClassExpression;
+ ConditionalExpression: ConditionalExpression;
+ FunctionExpression: FunctionExpression;
+ Identifier: Identifier;
+ ImportExpression: ImportExpression;
+ Literal: Literal;
+ LogicalExpression: LogicalExpression;
+ MemberExpression: MemberExpression;
+ MetaProperty: MetaProperty;
+ NewExpression: NewExpression;
+ ObjectExpression: ObjectExpression;
+ SequenceExpression: SequenceExpression;
+ TaggedTemplateExpression: TaggedTemplateExpression;
+ TemplateLiteral: TemplateLiteral;
+ ThisExpression: ThisExpression;
+ UnaryExpression: UnaryExpression;
+ UpdateExpression: UpdateExpression;
+ YieldExpression: YieldExpression;
+}
+
+export type Expression = ExpressionMap[keyof ExpressionMap];
+
+export interface BaseExpression extends BaseNode {}
+
+export type ChainElement = SimpleCallExpression | MemberExpression;
+
+export interface ChainExpression extends BaseExpression {
+ type: "ChainExpression";
+ expression: ChainElement;
+}
+
+export interface ThisExpression extends BaseExpression {
+ type: "ThisExpression";
+}
+
+export interface ArrayExpression extends BaseExpression {
+ type: "ArrayExpression";
+ elements: Array<Expression | SpreadElement | null>;
+}
+
+export interface ObjectExpression extends BaseExpression {
+ type: "ObjectExpression";
+ properties: Array<Property | SpreadElement>;
+}
+
+export interface PrivateIdentifier extends BaseNode {
+ type: "PrivateIdentifier";
+ name: string;
+}
+
+export interface Property extends BaseNode {
+ type: "Property";
+ key: Expression | PrivateIdentifier;
+ value: Expression | Pattern; // Could be an AssignmentProperty
+ kind: "init" | "get" | "set";
+ method: boolean;
+ shorthand: boolean;
+ computed: boolean;
+}
+
+export interface PropertyDefinition extends BaseNode {
+ type: "PropertyDefinition";
+ key: Expression | PrivateIdentifier;
+ value?: Expression | null | undefined;
+ computed: boolean;
+ static: boolean;
+}
+
+export interface FunctionExpression extends BaseFunction, BaseExpression {
+ id?: Identifier | null | undefined;
+ type: "FunctionExpression";
+ body: BlockStatement;
+}
+
+export interface SequenceExpression extends BaseExpression {
+ type: "SequenceExpression";
+ expressions: Expression[];
+}
+
+export interface UnaryExpression extends BaseExpression {
+ type: "UnaryExpression";
+ operator: UnaryOperator;
+ prefix: true;
+ argument: Expression;
+}
+
+export interface BinaryExpression extends BaseExpression {
+ type: "BinaryExpression";
+ operator: BinaryOperator;
+ left: Expression | PrivateIdentifier;
+ right: Expression;
+}
+
+export interface AssignmentExpression extends BaseExpression {
+ type: "AssignmentExpression";
+ operator: AssignmentOperator;
+ left: Pattern | MemberExpression;
+ right: Expression;
+}
+
+export interface UpdateExpression extends BaseExpression {
+ type: "UpdateExpression";
+ operator: UpdateOperator;
+ argument: Expression;
+ prefix: boolean;
+}
+
+export interface LogicalExpression extends BaseExpression {
+ type: "LogicalExpression";
+ operator: LogicalOperator;
+ left: Expression;
+ right: Expression;
+}
+
+export interface ConditionalExpression extends BaseExpression {
+ type: "ConditionalExpression";
+ test: Expression;
+ alternate: Expression;
+ consequent: Expression;
+}
+
+export interface BaseCallExpression extends BaseExpression {
+ callee: Expression | Super;
+ arguments: Array<Expression | SpreadElement>;
+}
+export type CallExpression = SimpleCallExpression | NewExpression;
+
+export interface SimpleCallExpression extends BaseCallExpression {
+ type: "CallExpression";
+ optional: boolean;
+}
+
+export interface NewExpression extends BaseCallExpression {
+ type: "NewExpression";
+}
+
+export interface MemberExpression extends BaseExpression, BasePattern {
+ type: "MemberExpression";
+ object: Expression | Super;
+ property: Expression | PrivateIdentifier;
+ computed: boolean;
+ optional: boolean;
+}
+
+export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
+
+export interface BasePattern extends BaseNode {}
+
+export interface SwitchCase extends BaseNode {
+ type: "SwitchCase";
+ test?: Expression | null | undefined;
+ consequent: Statement[];
+}
+
+export interface CatchClause extends BaseNode {
+ type: "CatchClause";
+ param: Pattern | null;
+ body: BlockStatement;
+}
+
+export interface Identifier extends BaseNode, BaseExpression, BasePattern {
+ type: "Identifier";
+ name: string;
+}
+
+export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
+
+export interface SimpleLiteral extends BaseNode, BaseExpression {
+ type: "Literal";
+ value: string | boolean | number | null;
+ raw?: string | undefined;
+}
+
+export interface RegExpLiteral extends BaseNode, BaseExpression {
+ type: "Literal";
+ value?: RegExp | null | undefined;
+ regex: {
+ pattern: string;
+ flags: string;
+ };
+ raw?: string | undefined;
+}
+
+export interface BigIntLiteral extends BaseNode, BaseExpression {
+ type: "Literal";
+ value?: bigint | null | undefined;
+ bigint: string;
+ raw?: string | undefined;
+}
+
+export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
+
+export type BinaryOperator =
+ | "=="
+ | "!="
+ | "==="
+ | "!=="
+ | "<"
+ | "<="
+ | ">"
+ | ">="
+ | "<<"
+ | ">>"
+ | ">>>"
+ | "+"
+ | "-"
+ | "*"
+ | "/"
+ | "%"
+ | "**"
+ | "|"
+ | "^"
+ | "&"
+ | "in"
+ | "instanceof";
+
+export type LogicalOperator = "||" | "&&" | "??";
+
+export type AssignmentOperator =
+ | "="
+ | "+="
+ | "-="
+ | "*="
+ | "/="
+ | "%="
+ | "**="
+ | "<<="
+ | ">>="
+ | ">>>="
+ | "|="
+ | "^="
+ | "&="
+ | "||="
+ | "&&="
+ | "??=";
+
+export type UpdateOperator = "++" | "--";
+
+export interface ForOfStatement extends BaseForXStatement {
+ type: "ForOfStatement";
+ await: boolean;
+}
+
+export interface Super extends BaseNode {
+ type: "Super";
+}
+
+export interface SpreadElement extends BaseNode {
+ type: "SpreadElement";
+ argument: Expression;
+}
+
+export interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
+ type: "ArrowFunctionExpression";
+ expression: boolean;
+ body: BlockStatement | Expression;
+}
+
+export interface YieldExpression extends BaseExpression {
+ type: "YieldExpression";
+ argument?: Expression | null | undefined;
+ delegate: boolean;
+}
+
+export interface TemplateLiteral extends BaseExpression {
+ type: "TemplateLiteral";
+ quasis: TemplateElement[];
+ expressions: Expression[];
+}
+
+export interface TaggedTemplateExpression extends BaseExpression {
+ type: "TaggedTemplateExpression";
+ tag: Expression;
+ quasi: TemplateLiteral;
+}
+
+export interface TemplateElement extends BaseNode {
+ type: "TemplateElement";
+ tail: boolean;
+ value: {
+ /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
+ cooked?: string | null | undefined;
+ raw: string;
+ };
+}
+
+export interface AssignmentProperty extends Property {
+ value: Pattern;
+ kind: "init";
+ method: boolean; // false
+}
+
+export interface ObjectPattern extends BasePattern {
+ type: "ObjectPattern";
+ properties: Array<AssignmentProperty | RestElement>;
+}
+
+export interface ArrayPattern extends BasePattern {
+ type: "ArrayPattern";
+ elements: Array<Pattern | null>;
+}
+
+export interface RestElement extends BasePattern {
+ type: "RestElement";
+ argument: Pattern;
+}
+
+export interface AssignmentPattern extends BasePattern {
+ type: "AssignmentPattern";
+ left: Pattern;
+ right: Expression;
+}
+
+export type Class = ClassDeclaration | ClassExpression;
+export interface BaseClass extends BaseNode {
+ superClass?: Expression | null | undefined;
+ body: ClassBody;
+}
+
+export interface ClassBody extends BaseNode {
+ type: "ClassBody";
+ body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
+}
+
+export interface MethodDefinition extends BaseNode {
+ type: "MethodDefinition";
+ key: Expression | PrivateIdentifier;
+ value: FunctionExpression;
+ kind: "constructor" | "method" | "get" | "set";
+ computed: boolean;
+ static: boolean;
+}
+
+export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
+ type: "ClassDeclaration";
+ /** It is null when a class declaration is a part of the `export default class` statement */
+ id: Identifier | null;
+}
+
+export interface ClassDeclaration extends MaybeNamedClassDeclaration {
+ id: Identifier;
+}
+
+export interface ClassExpression extends BaseClass, BaseExpression {
+ type: "ClassExpression";
+ id?: Identifier | null | undefined;
+}
+
+export interface MetaProperty extends BaseExpression {
+ type: "MetaProperty";
+ meta: Identifier;
+ property: Identifier;
+}
+
+export type ModuleDeclaration =
+ | ImportDeclaration
+ | ExportNamedDeclaration
+ | ExportDefaultDeclaration
+ | ExportAllDeclaration;
+export interface BaseModuleDeclaration extends BaseNode {}
+
+export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
+export interface BaseModuleSpecifier extends BaseNode {
+ local: Identifier;
+}
+
+export interface ImportDeclaration extends BaseModuleDeclaration {
+ type: "ImportDeclaration";
+ specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
+ attributes: ImportAttribute[];
+ source: Literal;
+}
+
+export interface ImportSpecifier extends BaseModuleSpecifier {
+ type: "ImportSpecifier";
+ imported: Identifier | Literal;
+}
+
+export interface ImportAttribute extends BaseNode {
+ type: "ImportAttribute";
+ key: Identifier | Literal;
+ value: Literal;
+}
+
+export interface ImportExpression extends BaseExpression {
+ type: "ImportExpression";
+ source: Expression;
+ options?: Expression | null | undefined;
+}
+
+export interface ImportDefaultSpecifier extends BaseModuleSpecifier {
+ type: "ImportDefaultSpecifier";
+}
+
+export interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
+ type: "ImportNamespaceSpecifier";
+}
+
+export interface ExportNamedDeclaration extends BaseModuleDeclaration {
+ type: "ExportNamedDeclaration";
+ declaration?: Declaration | null | undefined;
+ specifiers: ExportSpecifier[];
+ attributes: ImportAttribute[];
+ source?: Literal | null | undefined;
+}
+
+export interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
+ type: "ExportSpecifier";
+ local: Identifier | Literal;
+ exported: Identifier | Literal;
+}
+
+export interface ExportDefaultDeclaration extends BaseModuleDeclaration {
+ type: "ExportDefaultDeclaration";
+ declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
+}
+
+export interface ExportAllDeclaration extends BaseModuleDeclaration {
+ type: "ExportAllDeclaration";
+ exported: Identifier | Literal | null;
+ attributes: ImportAttribute[];
+ source: Literal;
+}
+
+export interface AwaitExpression extends BaseExpression {
+ type: "AwaitExpression";
+ argument: Expression;
+}
diff --git a/frontend/node_modules/@types/estree/package.json b/frontend/node_modules/@types/estree/package.json
new file mode 100644
index 0000000..68c0782
--- /dev/null
+++ b/frontend/node_modules/@types/estree/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@types/estree",
+ "version": "1.0.8",
+ "description": "TypeScript definitions for estree",
+ "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree",
+ "license": "MIT",
+ "contributors": [
+ {
+ "name": "RReverser",
+ "githubUsername": "RReverser",
+ "url": "https://github.com/RReverser"
+ }
+ ],
+ "main": "",
+ "types": "index.d.ts",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
+ "directory": "types/estree"
+ },
+ "scripts": {},
+ "dependencies": {},
+ "peerDependencies": {},
+ "typesPublisherContentHash": "7a167b6e4a4d9f6e9a2cb9fd3fc45c885f89cbdeb44b3e5961bb057a45c082fd",
+ "typeScriptVersion": "5.1",
+ "nonNpm": true
+}
\ No newline at end of file
diff --git a/frontend/node_modules/esbuild/LICENSE.md b/frontend/node_modules/esbuild/LICENSE.md
new file mode 100644
index 0000000..2027e8d
--- /dev/null
+++ b/frontend/node_modules/esbuild/LICENSE.md
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 Evan Wallace
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/frontend/node_modules/esbuild/README.md b/frontend/node_modules/esbuild/README.md
new file mode 100644
index 0000000..93863d1
--- /dev/null
+++ b/frontend/node_modules/esbuild/README.md
@@ -0,0 +1,3 @@
+# esbuild
+
+This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details.
diff --git a/frontend/node_modules/esbuild/bin/esbuild b/frontend/node_modules/esbuild/bin/esbuild
new file mode 100644
index 0000000..56ab2c9
--- /dev/null
+++ b/frontend/node_modules/esbuild/bin/esbuild
@@ -0,0 +1,223 @@
+#!/usr/bin/env node
+"use strict";
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+
+// lib/npm/node-platform.ts
+var fs = require("fs");
+var os = require("os");
+var path = require("path");
+var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
+var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
+var packageDarwin_arm64 = "@esbuild/darwin-arm64";
+var packageDarwin_x64 = "@esbuild/darwin-x64";
+var knownWindowsPackages = {
+ "win32 arm64 LE": "@esbuild/win32-arm64",
+ "win32 ia32 LE": "@esbuild/win32-ia32",
+ "win32 x64 LE": "@esbuild/win32-x64"
+};
+var knownUnixlikePackages = {
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
+ "android arm64 LE": "@esbuild/android-arm64",
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
+ "darwin x64 LE": "@esbuild/darwin-x64",
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
+ "linux arm LE": "@esbuild/linux-arm",
+ "linux arm64 LE": "@esbuild/linux-arm64",
+ "linux ia32 LE": "@esbuild/linux-ia32",
+ "linux mips64el LE": "@esbuild/linux-mips64el",
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
+ "linux s390x BE": "@esbuild/linux-s390x",
+ "linux x64 LE": "@esbuild/linux-x64",
+ "linux loong64 LE": "@esbuild/linux-loong64",
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
+ "sunos x64 LE": "@esbuild/sunos-x64"
+};
+var knownWebAssemblyFallbackPackages = {
+ "android arm LE": "@esbuild/android-arm",
+ "android x64 LE": "@esbuild/android-x64",
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
+};
+function pkgAndSubpathForCurrentPlatform() {
+ let pkg;
+ let subpath;
+ let isWASM2 = false;
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
+ if (platformKey in knownWindowsPackages) {
+ pkg = knownWindowsPackages[platformKey];
+ subpath = "esbuild.exe";
+ } else if (platformKey in knownUnixlikePackages) {
+ pkg = knownUnixlikePackages[platformKey];
+ subpath = "bin/esbuild";
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
+ subpath = "bin/esbuild";
+ isWASM2 = true;
+ } else {
+ throw new Error(`Unsupported platform: ${platformKey}`);
+ }
+ return { pkg, subpath, isWASM: isWASM2 };
+}
+function pkgForSomeOtherPlatform() {
+ const libMainJS = require.resolve("esbuild");
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
+ for (const unixKey in knownUnixlikePackages) {
+ try {
+ const pkg = knownUnixlikePackages[unixKey];
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
+ } catch {
+ }
+ }
+ for (const windowsKey in knownWindowsPackages) {
+ try {
+ const pkg = knownWindowsPackages[windowsKey];
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
+ } catch {
+ }
+ }
+ }
+ return null;
+}
+function downloadedBinPath(pkg, subpath) {
+ const esbuildLibDir = path.dirname(require.resolve("esbuild"));
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
+}
+function generateBinPath() {
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
+ } else {
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
+ }
+ }
+ const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform();
+ let binPath2;
+ try {
+ binPath2 = require.resolve(`${pkg}/${subpath}`);
+ } catch (e) {
+ binPath2 = downloadedBinPath(pkg, subpath);
+ if (!fs.existsSync(binPath2)) {
+ try {
+ require.resolve(pkg);
+ } catch {
+ const otherPkg = pkgForSomeOtherPlatform();
+ if (otherPkg) {
+ let suggestions = `
+Specifically the "${otherPkg}" package is present but this platform
+needs the "${pkg}" package instead. People often get into this
+situation by installing esbuild on Windows or macOS and copying "node_modules"
+into a Docker image that runs Linux, or by copying "node_modules" between
+Windows and WSL environments.
+
+If you are installing with npm, you can try not copying the "node_modules"
+directory when you copy the files over, and running "npm ci" or "npm install"
+on the destination platform after the copy. Or you could consider using yarn
+instead of npm which has built-in support for installing a package on multiple
+platforms simultaneously.
+
+If you are installing with yarn, you can try listing both this platform and the
+other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
+feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
+Keep in mind that this means multiple copies of esbuild will be present.
+`;
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
+ suggestions = `
+Specifically the "${otherPkg}" package is present but this platform
+needs the "${pkg}" package instead. People often get into this
+situation by installing esbuild with npm running inside of Rosetta 2 and then
+trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
+2 is Apple's on-the-fly x86_64-to-arm64 translation service).
+
+If you are installing with npm, you can try ensuring that both npm and node are
+not running under Rosetta 2 and then reinstalling esbuild. This likely involves
+changing how you installed npm and/or node. For example, installing node with
+the universal installer here should work: https://nodejs.org/en/download/. Or
+you could consider using yarn instead of npm which has built-in support for
+installing a package on multiple platforms simultaneously.
+
+If you are installing with yarn, you can try listing both "arm64" and "x64"
+in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
+https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
+Keep in mind that this means multiple copies of esbuild will be present.
+`;
+ }
+ throw new Error(`
+You installed esbuild for another platform than the one you're currently using.
+This won't work because esbuild is written with native code and needs to
+install a platform-specific binary executable.
+${suggestions}
+Another alternative is to use the "esbuild-wasm" package instead, which works
+the same way on all platforms. But it comes with a heavy performance cost and
+can sometimes be 10x slower than the "esbuild" package, so you may also not
+want to do that.
+`);
+ }
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
+
+If you are installing esbuild with npm, make sure that you don't specify the
+"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
+of "package.json" is used by esbuild to install the correct binary executable
+for your current platform.`);
+ }
+ throw e;
+ }
+ }
+ if (/\.zip\//.test(binPath2)) {
+ let pnpapi;
+ try {
+ pnpapi = require("pnpapi");
+ } catch (e) {
+ }
+ if (pnpapi) {
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
+ const binTargetPath = path.join(
+ root,
+ "node_modules",
+ ".cache",
+ "esbuild",
+ `pnpapi-${pkg.replace("/", "-")}-${"0.25.11"}-${path.basename(subpath)}`
+ );
+ if (!fs.existsSync(binTargetPath)) {
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
+ fs.copyFileSync(binPath2, binTargetPath);
+ fs.chmodSync(binTargetPath, 493);
+ }
+ return { binPath: binTargetPath, isWASM: isWASM2 };
+ }
+ }
+ return { binPath: binPath2, isWASM: isWASM2 };
+}
+
+// lib/npm/node-shim.ts
+var { binPath, isWASM } = generateBinPath();
+if (isWASM) {
+ require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" });
+} else {
+ require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" });
+}
diff --git a/frontend/node_modules/esbuild/install.js b/frontend/node_modules/esbuild/install.js
new file mode 100644
index 0000000..1019e62
--- /dev/null
+++ b/frontend/node_modules/esbuild/install.js
@@ -0,0 +1,289 @@
+"use strict";
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+
+// lib/npm/node-platform.ts
+var fs = require("fs");
+var os = require("os");
+var path = require("path");
+var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
+var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
+var knownWindowsPackages = {
+ "win32 arm64 LE": "@esbuild/win32-arm64",
+ "win32 ia32 LE": "@esbuild/win32-ia32",
+ "win32 x64 LE": "@esbuild/win32-x64"
+};
+var knownUnixlikePackages = {
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
+ "android arm64 LE": "@esbuild/android-arm64",
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
+ "darwin x64 LE": "@esbuild/darwin-x64",
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
+ "linux arm LE": "@esbuild/linux-arm",
+ "linux arm64 LE": "@esbuild/linux-arm64",
+ "linux ia32 LE": "@esbuild/linux-ia32",
+ "linux mips64el LE": "@esbuild/linux-mips64el",
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
+ "linux s390x BE": "@esbuild/linux-s390x",
+ "linux x64 LE": "@esbuild/linux-x64",
+ "linux loong64 LE": "@esbuild/linux-loong64",
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
+ "sunos x64 LE": "@esbuild/sunos-x64"
+};
+var knownWebAssemblyFallbackPackages = {
+ "android arm LE": "@esbuild/android-arm",
+ "android x64 LE": "@esbuild/android-x64",
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
+};
+function pkgAndSubpathForCurrentPlatform() {
+ let pkg;
+ let subpath;
+ let isWASM = false;
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
+ if (platformKey in knownWindowsPackages) {
+ pkg = knownWindowsPackages[platformKey];
+ subpath = "esbuild.exe";
+ } else if (platformKey in knownUnixlikePackages) {
+ pkg = knownUnixlikePackages[platformKey];
+ subpath = "bin/esbuild";
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
+ subpath = "bin/esbuild";
+ isWASM = true;
+ } else {
+ throw new Error(`Unsupported platform: ${platformKey}`);
+ }
+ return { pkg, subpath, isWASM };
+}
+function downloadedBinPath(pkg, subpath) {
+ const esbuildLibDir = path.dirname(require.resolve("esbuild"));
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
+}
+
+// lib/npm/node-install.ts
+var fs2 = require("fs");
+var os2 = require("os");
+var path2 = require("path");
+var zlib = require("zlib");
+var https = require("https");
+var child_process = require("child_process");
+var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
+var toPath = path2.join(__dirname, "bin", "esbuild");
+var isToPathJS = true;
+function validateBinaryVersion(...command) {
+ command.push("--version");
+ let stdout;
+ try {
+ stdout = child_process.execFileSync(command.shift(), command, {
+ // Without this, this install script strangely crashes with the error
+ // "EACCES: permission denied, write" but only on Ubuntu Linux when node is
+ // installed from the Snap Store. This is not a problem when you download
+ // the official version of node. The problem appears to be that stderr
+ // (i.e. file descriptor 2) isn't writable?
+ //
+ // More info:
+ // - https://snapcraft.io/ (what the Snap Store is)
+ // - https://nodejs.org/dist/ (download the official version of node)
+ // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
+ //
+ stdio: "pipe"
+ }).toString().trim();
+ } catch (err) {
+ if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
+ let os3 = "this version of macOS";
+ try {
+ os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
+ } catch {
+ }
+ throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
+
+The Go compiler (which esbuild relies on) no longer supports ${os3},
+which means the "esbuild" binary executable can't be run. You can either:
+
+ * Update your version of macOS to one that the Go compiler supports
+ * Use the "esbuild-wasm" package instead of the "esbuild" package
+ * Build esbuild yourself using an older version of the Go compiler
+`);
+ }
+ throw err;
+ }
+ if (stdout !== versionFromPackageJSON) {
+ throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
+ }
+}
+function isYarn() {
+ const { npm_config_user_agent } = process.env;
+ if (npm_config_user_agent) {
+ return /\byarn\//.test(npm_config_user_agent);
+ }
+ return false;
+}
+function fetch(url) {
+ return new Promise((resolve, reject) => {
+ https.get(url, (res) => {
+ if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
+ return fetch(res.headers.location).then(resolve, reject);
+ if (res.statusCode !== 200)
+ return reject(new Error(`Server responded with ${res.statusCode}`));
+ let chunks = [];
+ res.on("data", (chunk) => chunks.push(chunk));
+ res.on("end", () => resolve(Buffer.concat(chunks)));
+ }).on("error", reject);
+ });
+}
+function extractFileFromTarGzip(buffer, subpath) {
+ try {
+ buffer = zlib.unzipSync(buffer);
+ } catch (err) {
+ throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
+ }
+ let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
+ let offset = 0;
+ subpath = `package/${subpath}`;
+ while (offset < buffer.length) {
+ let name = str(offset, 100);
+ let size = parseInt(str(offset + 124, 12), 8);
+ offset += 512;
+ if (!isNaN(size)) {
+ if (name === subpath) return buffer.subarray(offset, offset + size);
+ offset += size + 511 & ~511;
+ }
+ }
+ throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
+}
+function installUsingNPM(pkg, subpath, binPath) {
+ const env = { ...process.env, npm_config_global: void 0 };
+ const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
+ const installDir = path2.join(esbuildLibDir, "npm-install");
+ fs2.mkdirSync(installDir);
+ try {
+ fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
+ child_process.execSync(
+ `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
+ { cwd: installDir, stdio: "pipe", env }
+ );
+ const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
+ fs2.renameSync(installedBinPath, binPath);
+ } finally {
+ try {
+ removeRecursive(installDir);
+ } catch {
+ }
+ }
+}
+function removeRecursive(dir) {
+ for (const entry of fs2.readdirSync(dir)) {
+ const entryPath = path2.join(dir, entry);
+ let stats;
+ try {
+ stats = fs2.lstatSync(entryPath);
+ } catch {
+ continue;
+ }
+ if (stats.isDirectory()) removeRecursive(entryPath);
+ else fs2.unlinkSync(entryPath);
+ }
+ fs2.rmdirSync(dir);
+}
+function applyManualBinaryPathOverride(overridePath) {
+ const pathString = JSON.stringify(overridePath);
+ fs2.writeFileSync(toPath, `#!/usr/bin/env node
+require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
+`);
+ const libMain = path2.join(__dirname, "lib", "main.js");
+ const code = fs2.readFileSync(libMain, "utf8");
+ fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
+${code}`);
+}
+function maybeOptimizePackage(binPath) {
+ const { isWASM } = pkgAndSubpathForCurrentPlatform();
+ if (os2.platform() !== "win32" && !isYarn() && !isWASM) {
+ const tempPath = path2.join(__dirname, "bin-esbuild");
+ try {
+ fs2.linkSync(binPath, tempPath);
+ fs2.renameSync(tempPath, toPath);
+ isToPathJS = false;
+ fs2.unlinkSync(tempPath);
+ } catch {
+ }
+ }
+}
+async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
+ const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
+ console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
+ try {
+ fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
+ fs2.chmodSync(binPath, 493);
+ } catch (e) {
+ console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
+ throw e;
+ }
+}
+async function checkAndPreparePackage() {
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
+ if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
+ } else {
+ applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
+ return;
+ }
+ }
+ const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
+ let binPath;
+ try {
+ binPath = require.resolve(`${pkg}/${subpath}`);
+ } catch (e) {
+ console.error(`[esbuild] Failed to find package "${pkg}" on the file system
+
+This can happen if you use the "--no-optional" flag. The "optionalDependencies"
+package.json feature is used by esbuild to install the correct binary executable
+for your current platform. This install script will now attempt to work around
+this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
+`);
+ binPath = downloadedBinPath(pkg, subpath);
+ try {
+ console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
+ installUsingNPM(pkg, subpath, binPath);
+ } catch (e2) {
+ console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
+ try {
+ await downloadDirectlyFromNPM(pkg, subpath, binPath);
+ } catch (e3) {
+ throw new Error(`Failed to install package "${pkg}"`);
+ }
+ }
+ }
+ maybeOptimizePackage(binPath);
+}
+checkAndPreparePackage().then(() => {
+ if (isToPathJS) {
+ validateBinaryVersion(process.execPath, toPath);
+ } else {
+ validateBinaryVersion(toPath);
+ }
+});
diff --git a/frontend/node_modules/esbuild/lib/main.d.ts b/frontend/node_modules/esbuild/lib/main.d.ts
new file mode 100644
index 0000000..9e69c39
--- /dev/null
+++ b/frontend/node_modules/esbuild/lib/main.d.ts
@@ -0,0 +1,716 @@
+export type Platform = 'browser' | 'node' | 'neutral'
+export type Format = 'iife' | 'cjs' | 'esm'
+export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx'
+export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent'
+export type Charset = 'ascii' | 'utf8'
+export type Drop = 'console' | 'debugger'
+export type AbsPaths = 'code' | 'log' | 'metafile'
+
+interface CommonOptions {
+ /** Documentation: https://esbuild.github.io/api/#sourcemap */
+ sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both'
+ /** Documentation: https://esbuild.github.io/api/#legal-comments */
+ legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external'
+ /** Documentation: https://esbuild.github.io/api/#source-root */
+ sourceRoot?: string
+ /** Documentation: https://esbuild.github.io/api/#sources-content */
+ sourcesContent?: boolean
+
+ /** Documentation: https://esbuild.github.io/api/#format */
+ format?: Format
+ /** Documentation: https://esbuild.github.io/api/#global-name */
+ globalName?: string
+ /** Documentation: https://esbuild.github.io/api/#target */
+ target?: string | string[]
+ /** Documentation: https://esbuild.github.io/api/#supported */
+ supported?: Record<string, boolean>
+ /** Documentation: https://esbuild.github.io/api/#platform */
+ platform?: Platform
+
+ /** Documentation: https://esbuild.github.io/api/#mangle-props */
+ mangleProps?: RegExp
+ /** Documentation: https://esbuild.github.io/api/#mangle-props */
+ reserveProps?: RegExp
+ /** Documentation: https://esbuild.github.io/api/#mangle-props */
+ mangleQuoted?: boolean
+ /** Documentation: https://esbuild.github.io/api/#mangle-props */
+ mangleCache?: Record<string, string | false>
+ /** Documentation: https://esbuild.github.io/api/#drop */
+ drop?: Drop[]
+ /** Documentation: https://esbuild.github.io/api/#drop-labels */
+ dropLabels?: string[]
+ /** Documentation: https://esbuild.github.io/api/#minify */
+ minify?: boolean
+ /** Documentation: https://esbuild.github.io/api/#minify */
+ minifyWhitespace?: boolean
+ /** Documentation: https://esbuild.github.io/api/#minify */
+ minifyIdentifiers?: boolean
+ /** Documentation: https://esbuild.github.io/api/#minify */
+ minifySyntax?: boolean
+ /** Documentation: https://esbuild.github.io/api/#line-limit */
+ lineLimit?: number
+ /** Documentation: https://esbuild.github.io/api/#charset */
+ charset?: Charset
+ /** Documentation: https://esbuild.github.io/api/#tree-shaking */
+ treeShaking?: boolean
+ /** Documentation: https://esbuild.github.io/api/#ignore-annotations */
+ ignoreAnnotations?: boolean
+
+ /** Documentation: https://esbuild.github.io/api/#jsx */
+ jsx?: 'transform' | 'preserve' | 'automatic'
+ /** Documentation: https://esbuild.github.io/api/#jsx-factory */
+ jsxFactory?: string
+ /** Documentation: https://esbuild.github.io/api/#jsx-fragment */
+ jsxFragment?: string
+ /** Documentation: https://esbuild.github.io/api/#jsx-import-source */
+ jsxImportSource?: string
+ /** Documentation: https://esbuild.github.io/api/#jsx-development */
+ jsxDev?: boolean
+ /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */
+ jsxSideEffects?: boolean
+
+ /** Documentation: https://esbuild.github.io/api/#define */
+ define?: { [key: string]: string }
+ /** Documentation: https://esbuild.github.io/api/#pure */
+ pure?: string[]
+ /** Documentation: https://esbuild.github.io/api/#keep-names */
+ keepNames?: boolean
+
+ /** Documentation: https://esbuild.github.io/api/#abs-paths */
+ absPaths?: AbsPaths[]
+ /** Documentation: https://esbuild.github.io/api/#color */
+ color?: boolean
+ /** Documentation: https://esbuild.github.io/api/#log-level */
+ logLevel?: LogLevel
+ /** Documentation: https://esbuild.github.io/api/#log-limit */
+ logLimit?: number
+ /** Documentation: https://esbuild.github.io/api/#log-override */
+ logOverride?: Record<string, LogLevel>
+
+ /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */
+ tsconfigRaw?: string | TsconfigRaw
+}
+
+export interface TsconfigRaw {
+ compilerOptions?: {
+ alwaysStrict?: boolean
+ baseUrl?: string
+ experimentalDecorators?: boolean
+ importsNotUsedAsValues?: 'remove' | 'preserve' | 'error'
+ jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev'
+ jsxFactory?: string
+ jsxFragmentFactory?: string
+ jsxImportSource?: string
+ paths?: Record<string, string[]>
+ preserveValueImports?: boolean
+ strict?: boolean
+ target?: string
+ useDefineForClassFields?: boolean
+ verbatimModuleSyntax?: boolean
+ }
+}
+
+export interface BuildOptions extends CommonOptions {
+ /** Documentation: https://esbuild.github.io/api/#bundle */
+ bundle?: boolean
+ /** Documentation: https://esbuild.github.io/api/#splitting */
+ splitting?: boolean
+ /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */
+ preserveSymlinks?: boolean
+ /** Documentation: https://esbuild.github.io/api/#outfile */
+ outfile?: string
+ /** Documentation: https://esbuild.github.io/api/#metafile */
+ metafile?: boolean
+ /** Documentation: https://esbuild.github.io/api/#outdir */
+ outdir?: string
+ /** Documentation: https://esbuild.github.io/api/#outbase */
+ outbase?: string
+ /** Documentation: https://esbuild.github.io/api/#external */
+ external?: string[]
+ /** Documentation: https://esbuild.github.io/api/#packages */
+ packages?: 'bundle' | 'external'
+ /** Documentation: https://esbuild.github.io/api/#alias */
+ alias?: Record<string, string>
+ /** Documentation: https://esbuild.github.io/api/#loader */
+ loader?: { [ext: string]: Loader }
+ /** Documentation: https://esbuild.github.io/api/#resolve-extensions */
+ resolveExtensions?: string[]
+ /** Documentation: https://esbuild.github.io/api/#main-fields */
+ mainFields?: string[]
+ /** Documentation: https://esbuild.github.io/api/#conditions */
+ conditions?: string[]
+ /** Documentation: https://esbuild.github.io/api/#write */
+ write?: boolean
+ /** Documentation: https://esbuild.github.io/api/#allow-overwrite */
+ allowOverwrite?: boolean
+ /** Documentation: https://esbuild.github.io/api/#tsconfig */
+ tsconfig?: string
+ /** Documentation: https://esbuild.github.io/api/#out-extension */
+ outExtension?: { [ext: string]: string }
+ /** Documentation: https://esbuild.github.io/api/#public-path */
+ publicPath?: string
+ /** Documentation: https://esbuild.github.io/api/#entry-names */
+ entryNames?: string
+ /** Documentation: https://esbuild.github.io/api/#chunk-names */
+ chunkNames?: string
+ /** Documentation: https://esbuild.github.io/api/#asset-names */
+ assetNames?: string
+ /** Documentation: https://esbuild.github.io/api/#inject */
+ inject?: string[]
+ /** Documentation: https://esbuild.github.io/api/#banner */
+ banner?: { [type: string]: string }
+ /** Documentation: https://esbuild.github.io/api/#footer */
+ footer?: { [type: string]: string }
+ /** Documentation: https://esbuild.github.io/api/#entry-points */
+ entryPoints?: (string | { in: string, out: string })[] | Record<string, string>
+ /** Documentation: https://esbuild.github.io/api/#stdin */
+ stdin?: StdinOptions
+ /** Documentation: https://esbuild.github.io/plugins/ */
+ plugins?: Plugin[]
+ /** Documentation: https://esbuild.github.io/api/#working-directory */
+ absWorkingDir?: string
+ /** Documentation: https://esbuild.github.io/api/#node-paths */
+ nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
+}
+
+export interface StdinOptions {
+ contents: string | Uint8Array
+ resolveDir?: string
+ sourcefile?: string
+ loader?: Loader
+}
+
+export interface Message {
+ id: string
+ pluginName: string
+ text: string
+ location: Location | null
+ notes: Note[]
+
+ /**
+ * Optional user-specified data that is passed through unmodified. You can
+ * use this to stash the original error, for example.
+ */
+ detail: any
+}
+
+export interface Note {
+ text: string
+ location: Location | null
+}
+
+export interface Location {
+ file: string
+ namespace: string
+ /** 1-based */
+ line: number
+ /** 0-based, in bytes */
+ column: number
+ /** in bytes */
+ length: number
+ lineText: string
+ suggestion: string
+}
+
+export interface OutputFile {
+ path: string
+ contents: Uint8Array
+ hash: string
+ /** "contents" as text (changes automatically with "contents") */
+ readonly text: string
+}
+
+export interface BuildResult<ProvidedOptions extends BuildOptions = BuildOptions> {
+ errors: Message[]
+ warnings: Message[]
+ /** Only when "write: false" */
+ outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined)
+ /** Only when "metafile: true" */
+ metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined)
+ /** Only when "mangleCache" is present */
+ mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
+}
+
+export interface BuildFailure extends Error {
+ errors: Message[]
+ warnings: Message[]
+}
+
+/** Documentation: https://esbuild.github.io/api/#serve-arguments */
+export interface ServeOptions {
+ port?: number
+ host?: string
+ servedir?: string
+ keyfile?: string
+ certfile?: string
+ fallback?: string
+ cors?: CORSOptions
+ onRequest?: (args: ServeOnRequestArgs) => void
+}
+
+/** Documentation: https://esbuild.github.io/api/#cors */
+export interface CORSOptions {
+ origin?: string | string[]
+}
+
+export interface ServeOnRequestArgs {
+ remoteAddress: string
+ method: string
+ path: string
+ status: number
+ /** The time to generate the response, not to send it */
+ timeInMS: number
+}
+
+/** Documentation: https://esbuild.github.io/api/#serve-return-values */
+export interface ServeResult {
+ port: number
+ hosts: string[]
+}
+
+export interface TransformOptions extends CommonOptions {
+ /** Documentation: https://esbuild.github.io/api/#sourcefile */
+ sourcefile?: string
+ /** Documentation: https://esbuild.github.io/api/#loader */
+ loader?: Loader
+ /** Documentation: https://esbuild.github.io/api/#banner */
+ banner?: string
+ /** Documentation: https://esbuild.github.io/api/#footer */
+ footer?: string
+}
+
+export interface TransformResult<ProvidedOptions extends TransformOptions = TransformOptions> {
+ code: string
+ map: string
+ warnings: Message[]
+ /** Only when "mangleCache" is present */
+ mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
+ /** Only when "legalComments" is "external" */
+ legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined)
+}
+
+export interface TransformFailure extends Error {
+ errors: Message[]
+ warnings: Message[]
+}
+
+export interface Plugin {
+ name: string
+ setup: (build: PluginBuild) => (void | Promise<void>)
+}
+
+export interface PluginBuild {
+ /** Documentation: https://esbuild.github.io/plugins/#build-options */
+ initialOptions: BuildOptions
+
+ /** Documentation: https://esbuild.github.io/plugins/#resolve */
+ resolve(path: string, options?: ResolveOptions): Promise<ResolveResult>
+
+ /** Documentation: https://esbuild.github.io/plugins/#on-start */
+ onStart(callback: () =>
+ (OnStartResult | null | void | Promise<OnStartResult | null | void>)): void
+
+ /** Documentation: https://esbuild.github.io/plugins/#on-end */
+ onEnd(callback: (result: BuildResult) =>
+ (OnEndResult | null | void | Promise<OnEndResult | null | void>)): void
+
+ /** Documentation: https://esbuild.github.io/plugins/#on-resolve */
+ onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
+ (OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void
+
+ /** Documentation: https://esbuild.github.io/plugins/#on-load */
+ onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
+ (OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void
+
+ /** Documentation: https://esbuild.github.io/plugins/#on-dispose */
+ onDispose(callback: () => void): void
+
+ // This is a full copy of the esbuild library in case you need it
+ esbuild: {
+ context: typeof context,
+ build: typeof build,
+ buildSync: typeof buildSync,
+ transform: typeof transform,
+ transformSync: typeof transformSync,
+ formatMessages: typeof formatMessages,
+ formatMessagesSync: typeof formatMessagesSync,
+ analyzeMetafile: typeof analyzeMetafile,
+ analyzeMetafileSync: typeof analyzeMetafileSync,
+ initialize: typeof initialize,
+ version: typeof version,
+ }
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#resolve-options */
+export interface ResolveOptions {
+ pluginName?: string
+ importer?: string
+ namespace?: string
+ resolveDir?: string
+ kind?: ImportKind
+ pluginData?: any
+ with?: Record<string, string>
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#resolve-results */
+export interface ResolveResult {
+ errors: Message[]
+ warnings: Message[]
+
+ path: string
+ external: boolean
+ sideEffects: boolean
+ namespace: string
+ suffix: string
+ pluginData: any
+}
+
+export interface OnStartResult {
+ errors?: PartialMessage[]
+ warnings?: PartialMessage[]
+}
+
+export interface OnEndResult {
+ errors?: PartialMessage[]
+ warnings?: PartialMessage[]
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */
+export interface OnResolveOptions {
+ filter: RegExp
+ namespace?: string
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */
+export interface OnResolveArgs {
+ path: string
+ importer: string
+ namespace: string
+ resolveDir: string
+ kind: ImportKind
+ pluginData: any
+ with: Record<string, string>
+}
+
+export type ImportKind =
+ | 'entry-point'
+
+ // JS
+ | 'import-statement'
+ | 'require-call'
+ | 'dynamic-import'
+ | 'require-resolve'
+
+ // CSS
+ | 'import-rule'
+ | 'composes-from'
+ | 'url-token'
+
+/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */
+export interface OnResolveResult {
+ pluginName?: string
+
+ errors?: PartialMessage[]
+ warnings?: PartialMessage[]
+
+ path?: string
+ external?: boolean
+ sideEffects?: boolean
+ namespace?: string
+ suffix?: string
+ pluginData?: any
+
+ watchFiles?: string[]
+ watchDirs?: string[]
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#on-load-options */
+export interface OnLoadOptions {
+ filter: RegExp
+ namespace?: string
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */
+export interface OnLoadArgs {
+ path: string
+ namespace: string
+ suffix: string
+ pluginData: any
+ with: Record<string, string>
+}
+
+/** Documentation: https://esbuild.github.io/plugins/#on-load-results */
+export interface OnLoadResult {
+ pluginName?: string
+
+ errors?: PartialMessage[]
+ warnings?: PartialMessage[]
+
+ contents?: string | Uint8Array
+ resolveDir?: string
+ loader?: Loader
+ pluginData?: any
+
+ watchFiles?: string[]
+ watchDirs?: string[]
+}
+
+export interface PartialMessage {
+ id?: string
+ pluginName?: string
+ text?: string
+ location?: Partial<Location> | null
+ notes?: PartialNote[]
+ detail?: any
+}
+
+export interface PartialNote {
+ text?: string
+ location?: Partial<Location> | null
+}
+
+/** Documentation: https://esbuild.github.io/api/#metafile */
+export interface Metafile {
+ inputs: {
+ [path: string]: {
+ bytes: number
+ imports: {
+ path: string
+ kind: ImportKind
+ external?: boolean
+ original?: string
+ with?: Record<string, string>
+ }[]
+ format?: 'cjs' | 'esm'
+ with?: Record<string, string>
+ }
+ }
+ outputs: {
+ [path: string]: {
+ bytes: number
+ inputs: {
+ [path: string]: {
+ bytesInOutput: number
+ }
+ }
+ imports: {
+ path: string
+ kind: ImportKind | 'file-loader'
+ external?: boolean
+ }[]
+ exports: string[]
+ entryPoint?: string
+ cssBundle?: string
+ }
+ }
+}
+
+export interface FormatMessagesOptions {
+ kind: 'error' | 'warning'
+ color?: boolean
+ terminalWidth?: number
+}
+
+export interface AnalyzeMetafileOptions {
+ color?: boolean
+ verbose?: boolean
+}
+
+/** Documentation: https://esbuild.github.io/api/#watch-arguments */
+export interface WatchOptions {
+ delay?: number // In milliseconds
+}
+
+export interface BuildContext<ProvidedOptions extends BuildOptions = BuildOptions> {
+ /** Documentation: https://esbuild.github.io/api/#rebuild */
+ rebuild(): Promise<BuildResult<ProvidedOptions>>
+
+ /** Documentation: https://esbuild.github.io/api/#watch */
+ watch(options?: WatchOptions): Promise<void>
+
+ /** Documentation: https://esbuild.github.io/api/#serve */
+ serve(options?: ServeOptions): Promise<ServeResult>
+
+ cancel(): Promise<void>
+ dispose(): Promise<void>
+}
+
+// This is a TypeScript type-level function which replaces any keys in "In"
+// that aren't in "Out" with "never". We use this to reject properties with
+// typos in object literals. See: https://stackoverflow.com/questions/49580725
+type SameShape<Out, In extends Out> = In & { [Key in Exclude<keyof In, keyof Out>]: never }
+
+/**
+ * This function invokes the "esbuild" command-line tool for you. It returns a
+ * promise that either resolves with a "BuildResult" object or rejects with a
+ * "BuildFailure" object.
+ *
+ * - Works in node: yes
+ * - Works in browser: yes
+ *
+ * Documentation: https://esbuild.github.io/api/#build
+ */
+export declare function build<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildResult<T>>
+
+/**
+ * This is the advanced long-running form of "build" that supports additional
+ * features such as watch mode and a local development server.
+ *
+ * - Works in node: yes
+ * - Works in browser: no
+ *
+ * Documentation: https://esbuild.github.io/api/#build
+ */
+export declare function context<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildContext<T>>
+
+/**
+ * This function transforms a single JavaScript file. It can be used to minify
+ * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
+ * to older JavaScript. It returns a promise that is either resolved with a
+ * "TransformResult" object or rejected with a "TransformFailure" object.
+ *
+ * - Works in node: yes
+ * - Works in browser: yes
+ *
+ * Documentation: https://esbuild.github.io/api/#transform
+ */
+export declare function transform<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): Promise<TransformResult<T>>
+
+/**
+ * Converts log messages to formatted message strings suitable for printing in
+ * the terminal. This allows you to reuse the built-in behavior of esbuild's
+ * log message formatter. This is a batch-oriented API for efficiency.
+ *
+ * - Works in node: yes
+ * - Works in browser: yes
+ */
+export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>
+
+/**
+ * Pretty-prints an analysis of the metafile JSON to a string. This is just for
+ * convenience to be able to match esbuild's pretty-printing exactly. If you want
+ * to customize it, you can just inspect the data in the metafile yourself.
+ *
+ * - Works in node: yes
+ * - Works in browser: yes
+ *
+ * Documentation: https://esbuild.github.io/api/#analyze
+ */
+export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise<string>
+
+/**
+ * A synchronous version of "build".
+ *
+ * - Works in node: yes
+ * - Works in browser: no
+ *
+ * Documentation: https://esbuild.github.io/api/#build
+ */
+export declare function buildSync<T extends BuildOptions>(options: SameShape<BuildOptions, T>): BuildResult<T>
+
+/**
+ * A synchronous version of "transform".
+ *
+ * - Works in node: yes
+ * - Works in browser: no
+ *
+ * Documentation: https://esbuild.github.io/api/#transform
+ */
+export declare function transformSync<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): TransformResult<T>
+
+/**
+ * A synchronous version of "formatMessages".
+ *
+ * - Works in node: yes
+ * - Works in browser: no
+ */
+export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[]
+
+/**
+ * A synchronous version of "analyzeMetafile".
+ *
+ * - Works in node: yes
+ * - Works in browser: no
+ *
+ * Documentation: https://esbuild.github.io/api/#analyze
+ */
+export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string
+
+/**
+ * This configures the browser-based version of esbuild. It is necessary to
+ * call this first and wait for the returned promise to be resolved before
+ * making other API calls when using esbuild in the browser.
+ *
+ * - Works in node: yes
+ * - Works in browser: yes ("options" is required)
+ *
+ * Documentation: https://esbuild.github.io/api/#browser
+ */
+export declare function initialize(options: InitializeOptions): Promise<void>
+
+export interface InitializeOptions {
+ /**
+ * The URL of the "esbuild.wasm" file. This must be provided when running
+ * esbuild in the browser.
+ */
+ wasmURL?: string | URL
+
+ /**
+ * The result of calling "new WebAssembly.Module(buffer)" where "buffer"
+ * is a typed array or ArrayBuffer containing the binary code of the
+ * "esbuild.wasm" file.
+ *
+ * You can use this as an alternative to "wasmURL" for environments where it's
+ * not possible to download the WebAssembly module.
+ */
+ wasmModule?: WebAssembly.Module
+
+ /**
+ * By default esbuild runs the WebAssembly-based browser API in a web worker
+ * to avoid blocking the UI thread. This can be disabled by setting "worker"
+ * to false.
+ */
+ worker?: boolean
+}
+
+export let version: string
+
+// Call this function to terminate esbuild's child process. The child process
+// is not terminated and re-created after each API call because it's more
+// efficient to keep it around when there are multiple API calls.
+//
+// In node this happens automatically before the parent node process exits. So
+// you only need to call this if you know you will not make any more esbuild
+// API calls and you want to clean up resources.
+//
+// Unlike node, Deno lacks the necessary APIs to clean up child processes
+// automatically. You must manually call stop() in Deno when you're done
+// using esbuild or Deno will continue running forever.
+//
+// Another reason you might want to call this is if you are using esbuild from
+// within a Deno test. Deno fails tests that create a child process without
+// killing it before the test ends, so you have to call this function (and
+// await the returned promise) in every Deno test that uses esbuild.
+export declare function stop(): Promise<void>
+
+// Note: These declarations exist to avoid type errors when you omit "dom" from
+// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the
+// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do
+// with the browser DOM and is present in many non-browser JavaScript runtimes
+// (e.g. node and deno). Declaring it here allows esbuild's API to be used in
+// these scenarios.
+//
+// There's an open issue about getting this problem corrected (although these
+// declarations will need to remain even if this is fixed for backward
+// compatibility with older TypeScript versions):
+//
+// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826
+//
+declare global {
+ namespace WebAssembly {
+ interface Module {
+ }
+ }
+ interface URL {
+ }
+}
diff --git a/frontend/node_modules/esbuild/lib/main.js b/frontend/node_modules/esbuild/lib/main.js
new file mode 100644
index 0000000..b796538
--- /dev/null
+++ b/frontend/node_modules/esbuild/lib/main.js
@@ -0,0 +1,2242 @@
+"use strict";
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// lib/npm/node.ts
+var node_exports = {};
+__export(node_exports, {
+ analyzeMetafile: () => analyzeMetafile,
+ analyzeMetafileSync: () => analyzeMetafileSync,
+ build: () => build,
+ buildSync: () => buildSync,
+ context: () => context,
+ default: () => node_default,
+ formatMessages: () => formatMessages,
+ formatMessagesSync: () => formatMessagesSync,
+ initialize: () => initialize,
+ stop: () => stop,
+ transform: () => transform,
+ transformSync: () => transformSync,
+ version: () => version
+});
+module.exports = __toCommonJS(node_exports);
+
+// lib/shared/stdio_protocol.ts
+function encodePacket(packet) {
+ let visit = (value) => {
+ if (value === null) {
+ bb.write8(0);
+ } else if (typeof value === "boolean") {
+ bb.write8(1);
+ bb.write8(+value);
+ } else if (typeof value === "number") {
+ bb.write8(2);
+ bb.write32(value | 0);
+ } else if (typeof value === "string") {
+ bb.write8(3);
+ bb.write(encodeUTF8(value));
+ } else if (value instanceof Uint8Array) {
+ bb.write8(4);
+ bb.write(value);
+ } else if (value instanceof Array) {
+ bb.write8(5);
+ bb.write32(value.length);
+ for (let item of value) {
+ visit(item);
+ }
+ } else {
+ let keys = Object.keys(value);
+ bb.write8(6);
+ bb.write32(keys.length);
+ for (let key of keys) {
+ bb.write(encodeUTF8(key));
+ visit(value[key]);
+ }
+ }
+ };
+ let bb = new ByteBuffer();
+ bb.write32(0);
+ bb.write32(packet.id << 1 | +!packet.isRequest);
+ visit(packet.value);
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
+ return bb.buf.subarray(0, bb.len);
+}
+function decodePacket(bytes) {
+ let visit = () => {
+ switch (bb.read8()) {
+ case 0:
+ return null;
+ case 1:
+ return !!bb.read8();
+ case 2:
+ return bb.read32();
+ case 3:
+ return decodeUTF8(bb.read());
+ case 4:
+ return bb.read();
+ case 5: {
+ let count = bb.read32();
+ let value2 = [];
+ for (let i = 0; i < count; i++) {
+ value2.push(visit());
+ }
+ return value2;
+ }
+ case 6: {
+ let count = bb.read32();
+ let value2 = {};
+ for (let i = 0; i < count; i++) {
+ value2[decodeUTF8(bb.read())] = visit();
+ }
+ return value2;
+ }
+ default:
+ throw new Error("Invalid packet");
+ }
+ };
+ let bb = new ByteBuffer(bytes);
+ let id = bb.read32();
+ let isRequest = (id & 1) === 0;
+ id >>>= 1;
+ let value = visit();
+ if (bb.ptr !== bytes.length) {
+ throw new Error("Invalid packet");
+ }
+ return { id, isRequest, value };
+}
+var ByteBuffer = class {
+ constructor(buf = new Uint8Array(1024)) {
+ this.buf = buf;
+ this.len = 0;
+ this.ptr = 0;
+ }
+ _write(delta) {
+ if (this.len + delta > this.buf.length) {
+ let clone = new Uint8Array((this.len + delta) * 2);
+ clone.set(this.buf);
+ this.buf = clone;
+ }
+ this.len += delta;
+ return this.len - delta;
+ }
+ write8(value) {
+ let offset = this._write(1);
+ this.buf[offset] = value;
+ }
+ write32(value) {
+ let offset = this._write(4);
+ writeUInt32LE(this.buf, value, offset);
+ }
+ write(bytes) {
+ let offset = this._write(4 + bytes.length);
+ writeUInt32LE(this.buf, bytes.length, offset);
+ this.buf.set(bytes, offset + 4);
+ }
+ _read(delta) {
+ if (this.ptr + delta > this.buf.length) {
+ throw new Error("Invalid packet");
+ }
+ this.ptr += delta;
+ return this.ptr - delta;
+ }
+ read8() {
+ return this.buf[this._read(1)];
+ }
+ read32() {
+ return readUInt32LE(this.buf, this._read(4));
+ }
+ read() {
+ let length = this.read32();
+ let bytes = new Uint8Array(length);
+ let ptr = this._read(bytes.length);
+ bytes.set(this.buf.subarray(ptr, ptr + length));
+ return bytes;
+ }
+};
+var encodeUTF8;
+var decodeUTF8;
+var encodeInvariant;
+if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
+ let encoder = new TextEncoder();
+ let decoder = new TextDecoder();
+ encodeUTF8 = (text) => encoder.encode(text);
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
+ encodeInvariant = 'new TextEncoder().encode("")';
+} else if (typeof Buffer !== "undefined") {
+ encodeUTF8 = (text) => Buffer.from(text);
+ decodeUTF8 = (bytes) => {
+ let { buffer, byteOffset, byteLength } = bytes;
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
+ };
+ encodeInvariant = 'Buffer.from("")';
+} else {
+ throw new Error("No UTF-8 codec found");
+}
+if (!(encodeUTF8("") instanceof Uint8Array))
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
+
+This indicates that your JavaScript environment is broken. You cannot use
+esbuild in this environment because esbuild relies on this invariant. This
+is not a problem with esbuild. You need to fix your environment instead.
+`);
+function readUInt32LE(buffer, offset) {
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
+}
+function writeUInt32LE(buffer, value, offset) {
+ buffer[offset++] = value;
+ buffer[offset++] = value >> 8;
+ buffer[offset++] = value >> 16;
+ buffer[offset++] = value >> 24;
+}
+
+// lib/shared/common.ts
+var quote = JSON.stringify;
+var buildLogLevelDefault = "warning";
+var transformLogLevelDefault = "silent";
+function validateAndJoinStringArray(values, what) {
+ const toJoin = [];
+ for (const value of values) {
+ validateStringValue(value, what);
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
+ toJoin.push(value);
+ }
+ return toJoin.join(",");
+}
+var canBeAnything = () => null;
+var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
+var mustBeString = (value) => typeof value === "string" ? null : "a string";
+var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
+var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
+var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
+var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
+var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
+var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
+var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
+var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
+var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
+var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
+var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
+var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
+var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
+var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
+var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
+function getFlag(object, keys, key, mustBeFn) {
+ let value = object[key];
+ keys[key + ""] = true;
+ if (value === void 0) return void 0;
+ let mustBe = mustBeFn(value);
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
+ return value;
+}
+function checkForInvalidFlags(object, keys, where) {
+ for (let key in object) {
+ if (!(key in keys)) {
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
+ }
+ }
+}
+function validateInitializeOptions(options) {
+ let keys = /* @__PURE__ */ Object.create(null);
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
+ checkForInvalidFlags(options, keys, "in initialize() call");
+ return {
+ wasmURL,
+ wasmModule,
+ worker
+ };
+}
+function validateMangleCache(mangleCache) {
+ let validated;
+ if (mangleCache !== void 0) {
+ validated = /* @__PURE__ */ Object.create(null);
+ for (let key in mangleCache) {
+ let value = mangleCache[key];
+ if (typeof value === "string" || value === false) {
+ validated[key] = value;
+ } else {
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
+ }
+ }
+ }
+ return validated;
+}
+function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
+ let color = getFlag(options, keys, "color", mustBeBoolean);
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
+ if (color !== void 0) flags.push(`--color=${color}`);
+ else if (isTTY2) flags.push(`--color=true`);
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
+ flags.push(`--log-limit=${logLimit || 0}`);
+}
+function validateStringValue(value, what, key) {
+ if (typeof value !== "string") {
+ throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
+ }
+ return value;
+}
+function pushCommonFlags(flags, options, keys) {
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
+ let format = getFlag(options, keys, "format", mustBeString);
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
+ let charset = getFlag(options, keys, "charset", mustBeString);
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
+ let define = getFlag(options, keys, "define", mustBeObject);
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
+ let supported = getFlag(options, keys, "supported", mustBeObject);
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
+ let platform = getFlag(options, keys, "platform", mustBeString);
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
+ if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
+ if (format) flags.push(`--format=${format}`);
+ if (globalName) flags.push(`--global-name=${globalName}`);
+ if (platform) flags.push(`--platform=${platform}`);
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
+ if (minify) flags.push("--minify");
+ if (minifySyntax) flags.push("--minify-syntax");
+ if (minifyWhitespace) flags.push("--minify-whitespace");
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
+ if (charset) flags.push(`--charset=${charset}`);
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
+ if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
+ if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
+ if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
+ if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
+ if (jsx) flags.push(`--jsx=${jsx}`);
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
+ if (jsxDev) flags.push(`--jsx-dev`);
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
+ if (define) {
+ for (let key in define) {
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
+ }
+ }
+ if (logOverride) {
+ for (let key in logOverride) {
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
+ }
+ }
+ if (supported) {
+ for (let key in supported) {
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
+ const value = supported[key];
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
+ flags.push(`--supported:${key}=${value}`);
+ }
+ }
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
+ if (keepNames) flags.push(`--keep-names`);
+}
+function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
+ var _a2;
+ let flags = [];
+ let entries = [];
+ let keys = /* @__PURE__ */ Object.create(null);
+ let stdinContents = null;
+ let stdinResolveDir = null;
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
+ pushCommonFlags(flags, options, keys);
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
+ let packages = getFlag(options, keys, "packages", mustBeString);
+ let alias = getFlag(options, keys, "alias", mustBeObject);
+ let loader = getFlag(options, keys, "loader", mustBeObject);
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
+ let banner = getFlag(options, keys, "banner", mustBeObject);
+ let footer = getFlag(options, keys, "footer", mustBeObject);
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
+ keys.plugins = true;
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
+ if (bundle) flags.push("--bundle");
+ if (allowOverwrite) flags.push("--allow-overwrite");
+ if (splitting) flags.push("--splitting");
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
+ if (metafile) flags.push(`--metafile`);
+ if (outfile) flags.push(`--outfile=${outfile}`);
+ if (outdir) flags.push(`--outdir=${outdir}`);
+ if (outbase) flags.push(`--outbase=${outbase}`);
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
+ if (packages) flags.push(`--packages=${packages}`);
+ if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
+ if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
+ if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
+ if (alias) {
+ for (let old in alias) {
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
+ }
+ }
+ if (banner) {
+ for (let type in banner) {
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
+ }
+ }
+ if (footer) {
+ for (let type in footer) {
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
+ }
+ }
+ if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
+ if (loader) {
+ for (let ext in loader) {
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
+ }
+ }
+ if (outExtension) {
+ for (let ext in outExtension) {
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
+ }
+ }
+ if (entryPoints) {
+ if (Array.isArray(entryPoints)) {
+ for (let i = 0, n = entryPoints.length; i < n; i++) {
+ let entryPoint = entryPoints[i];
+ if (typeof entryPoint === "object" && entryPoint !== null) {
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
+ if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
+ if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
+ entries.push([output, input]);
+ } else {
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
+ }
+ }
+ } else {
+ for (let key in entryPoints) {
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
+ }
+ }
+ }
+ if (stdin) {
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
+ if (loader2) flags.push(`--loader=${loader2}`);
+ if (resolveDir) stdinResolveDir = resolveDir;
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
+ else if (contents instanceof Uint8Array) stdinContents = contents;
+ }
+ let nodePaths = [];
+ if (nodePathsInput) {
+ for (let value of nodePathsInput) {
+ value += "";
+ nodePaths.push(value);
+ }
+ }
+ return {
+ entries,
+ flags,
+ write,
+ stdinContents,
+ stdinResolveDir,
+ absWorkingDir,
+ nodePaths,
+ mangleCache: validateMangleCache(mangleCache)
+ };
+}
+function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
+ let flags = [];
+ let keys = /* @__PURE__ */ Object.create(null);
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
+ pushCommonFlags(flags, options, keys);
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
+ let loader = getFlag(options, keys, "loader", mustBeString);
+ let banner = getFlag(options, keys, "banner", mustBeString);
+ let footer = getFlag(options, keys, "footer", mustBeString);
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
+ if (loader) flags.push(`--loader=${loader}`);
+ if (banner) flags.push(`--banner=${banner}`);
+ if (footer) flags.push(`--footer=${footer}`);
+ return {
+ flags,
+ mangleCache: validateMangleCache(mangleCache)
+ };
+}
+function createChannel(streamIn) {
+ const requestCallbacksByKey = {};
+ const closeData = { didClose: false, reason: "" };
+ let responseCallbacks = {};
+ let nextRequestID = 0;
+ let nextBuildKey = 0;
+ let stdout = new Uint8Array(16 * 1024);
+ let stdoutUsed = 0;
+ let readFromStdout = (chunk) => {
+ let limit = stdoutUsed + chunk.length;
+ if (limit > stdout.length) {
+ let swap = new Uint8Array(limit * 2);
+ swap.set(stdout);
+ stdout = swap;
+ }
+ stdout.set(chunk, stdoutUsed);
+ stdoutUsed += chunk.length;
+ let offset = 0;
+ while (offset + 4 <= stdoutUsed) {
+ let length = readUInt32LE(stdout, offset);
+ if (offset + 4 + length > stdoutUsed) {
+ break;
+ }
+ offset += 4;
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
+ offset += length;
+ }
+ if (offset > 0) {
+ stdout.copyWithin(0, offset, stdoutUsed);
+ stdoutUsed -= offset;
+ }
+ };
+ let afterClose = (error) => {
+ closeData.didClose = true;
+ if (error) closeData.reason = ": " + (error.message || error);
+ const text = "The service was stopped" + closeData.reason;
+ for (let id in responseCallbacks) {
+ responseCallbacks[id](text, null);
+ }
+ responseCallbacks = {};
+ };
+ let sendRequest = (refs, value, callback) => {
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
+ let id = nextRequestID++;
+ responseCallbacks[id] = (error, response) => {
+ try {
+ callback(error, response);
+ } finally {
+ if (refs) refs.unref();
+ }
+ };
+ if (refs) refs.ref();
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
+ };
+ let sendResponse = (id, value) => {
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
+ };
+ let handleRequest = async (id, request) => {
+ try {
+ if (request.command === "ping") {
+ sendResponse(id, {});
+ return;
+ }
+ if (typeof request.key === "number") {
+ const requestCallbacks = requestCallbacksByKey[request.key];
+ if (!requestCallbacks) {
+ return;
+ }
+ const callback = requestCallbacks[request.command];
+ if (callback) {
+ await callback(id, request);
+ return;
+ }
+ }
+ throw new Error(`Invalid command: ` + request.command);
+ } catch (e) {
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
+ try {
+ sendResponse(id, { errors });
+ } catch {
+ }
+ }
+ };
+ let isFirstPacket = true;
+ let handleIncomingPacket = (bytes) => {
+ if (isFirstPacket) {
+ isFirstPacket = false;
+ let binaryVersion = String.fromCharCode(...bytes);
+ if (binaryVersion !== "0.25.11") {
+ throw new Error(`Cannot start service: Host version "${"0.25.11"}" does not match binary version ${quote(binaryVersion)}`);
+ }
+ return;
+ }
+ let packet = decodePacket(bytes);
+ if (packet.isRequest) {
+ handleRequest(packet.id, packet.value);
+ } else {
+ let callback = responseCallbacks[packet.id];
+ delete responseCallbacks[packet.id];
+ if (packet.value.error) callback(packet.value.error, {});
+ else callback(null, packet.value);
+ }
+ };
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
+ let refCount = 0;
+ const buildKey = nextBuildKey++;
+ const requestCallbacks = {};
+ const buildRefs = {
+ ref() {
+ if (++refCount === 1) {
+ if (refs) refs.ref();
+ }
+ },
+ unref() {
+ if (--refCount === 0) {
+ delete requestCallbacksByKey[buildKey];
+ if (refs) refs.unref();
+ }
+ }
+ };
+ requestCallbacksByKey[buildKey] = requestCallbacks;
+ buildRefs.ref();
+ buildOrContextImpl(
+ callName,
+ buildKey,
+ sendRequest,
+ sendResponse,
+ buildRefs,
+ streamIn,
+ requestCallbacks,
+ options,
+ isTTY2,
+ defaultWD2,
+ (err, res) => {
+ try {
+ callback(err, res);
+ } finally {
+ buildRefs.unref();
+ }
+ }
+ );
+ };
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
+ const details = createObjectStash();
+ let start = (inputPath) => {
+ try {
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
+ let {
+ flags,
+ mangleCache
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
+ let request = {
+ command: "transform",
+ flags,
+ inputFS: inputPath !== null,
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
+ };
+ if (mangleCache) request.mangleCache = mangleCache;
+ sendRequest(refs, request, (error, response) => {
+ if (error) return callback(new Error(error), null);
+ let errors = replaceDetailsInMessages(response.errors, details);
+ let warnings = replaceDetailsInMessages(response.warnings, details);
+ let outstanding = 1;
+ let next = () => {
+ if (--outstanding === 0) {
+ let result = {
+ warnings,
+ code: response.code,
+ map: response.map,
+ mangleCache: void 0,
+ legalComments: void 0
+ };
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
+ callback(null, result);
+ }
+ };
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
+ if (response.codeFS) {
+ outstanding++;
+ fs3.readFile(response.code, (err, contents) => {
+ if (err !== null) {
+ callback(err, null);
+ } else {
+ response.code = contents;
+ next();
+ }
+ });
+ }
+ if (response.mapFS) {
+ outstanding++;
+ fs3.readFile(response.map, (err, contents) => {
+ if (err !== null) {
+ callback(err, null);
+ } else {
+ response.map = contents;
+ next();
+ }
+ });
+ }
+ next();
+ });
+ } catch (e) {
+ let flags = [];
+ try {
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
+ } catch {
+ }
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
+ sendRequest(refs, { command: "error", flags, error }, () => {
+ error.detail = details.load(error.detail);
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
+ });
+ }
+ };
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
+ let next = start;
+ start = () => fs3.writeFile(input, next);
+ }
+ start(null);
+ };
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
+ let keys = {};
+ let kind = getFlag(options, keys, "kind", mustBeString);
+ let color = getFlag(options, keys, "color", mustBeBoolean);
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
+ let request = {
+ command: "format-msgs",
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
+ isWarning: kind === "warning"
+ };
+ if (color !== void 0) request.color = color;
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
+ sendRequest(refs, request, (error, response) => {
+ if (error) return callback(new Error(error), null);
+ callback(null, response.messages);
+ });
+ };
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
+ if (options === void 0) options = {};
+ let keys = {};
+ let color = getFlag(options, keys, "color", mustBeBoolean);
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
+ let request = {
+ command: "analyze-metafile",
+ metafile
+ };
+ if (color !== void 0) request.color = color;
+ if (verbose !== void 0) request.verbose = verbose;
+ sendRequest(refs, request, (error, response) => {
+ if (error) return callback(new Error(error), null);
+ callback(null, response.result);
+ });
+ };
+ return {
+ readFromStdout,
+ afterClose,
+ service: {
+ buildOrContext,
+ transform: transform2,
+ formatMessages: formatMessages2,
+ analyzeMetafile: analyzeMetafile2
+ }
+ };
+}
+function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
+ const details = createObjectStash();
+ const isContext = callName === "context";
+ const handleError = (e, pluginName) => {
+ const flags = [];
+ try {
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
+ } catch {
+ }
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
+ message.detail = details.load(message.detail);
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
+ });
+ };
+ let plugins;
+ if (typeof options === "object") {
+ const value = options.plugins;
+ if (value !== void 0) {
+ if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
+ plugins = value;
+ }
+ }
+ if (plugins && plugins.length > 0) {
+ if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
+ handlePlugins(
+ buildKey,
+ sendRequest,
+ sendResponse,
+ refs,
+ streamIn,
+ requestCallbacks,
+ options,
+ plugins,
+ details
+ ).then(
+ (result) => {
+ if (!result.ok) return handleError(result.error, result.pluginName);
+ try {
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
+ } catch (e) {
+ handleError(e, "");
+ }
+ },
+ (e) => handleError(e, "")
+ );
+ return;
+ }
+ try {
+ buildOrContextContinue(null, (result, done) => done([], []), () => {
+ });
+ } catch (e) {
+ handleError(e, "");
+ }
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
+ const writeDefault = streamIn.hasFS;
+ const {
+ entries,
+ flags,
+ write,
+ stdinContents,
+ stdinResolveDir,
+ absWorkingDir,
+ nodePaths,
+ mangleCache
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
+ const request = {
+ command: "build",
+ key: buildKey,
+ entries,
+ flags,
+ write,
+ stdinContents,
+ stdinResolveDir,
+ absWorkingDir: absWorkingDir || defaultWD2,
+ nodePaths,
+ context: isContext
+ };
+ if (requestPlugins) request.plugins = requestPlugins;
+ if (mangleCache) request.mangleCache = mangleCache;
+ const buildResponseToResult = (response, callback2) => {
+ const result = {
+ errors: replaceDetailsInMessages(response.errors, details),
+ warnings: replaceDetailsInMessages(response.warnings, details),
+ outputFiles: void 0,
+ metafile: void 0,
+ mangleCache: void 0
+ };
+ const originalErrors = result.errors.slice();
+ const originalWarnings = result.warnings.slice();
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
+ if (response.metafile) result.metafile = JSON.parse(response.metafile);
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
+ return callback2(error, null, onEndErrors, onEndWarnings);
+ }
+ callback2(null, result, onEndErrors, onEndWarnings);
+ });
+ };
+ let latestResultPromise;
+ let provideLatestResult;
+ if (isContext)
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
+ const response = {
+ errors: onEndErrors,
+ warnings: onEndWarnings
+ };
+ if (provideLatestResult) provideLatestResult(err, result);
+ latestResultPromise = void 0;
+ provideLatestResult = void 0;
+ sendResponse(id, response);
+ resolve();
+ });
+ });
+ sendRequest(refs, request, (error, response) => {
+ if (error) return callback(new Error(error), null);
+ if (!isContext) {
+ return buildResponseToResult(response, (err, res) => {
+ scheduleOnDisposeCallbacks();
+ return callback(err, res);
+ });
+ }
+ if (response.errors.length > 0) {
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
+ }
+ let didDispose = false;
+ const result = {
+ rebuild: () => {
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
+ let settlePromise;
+ provideLatestResult = (err, result2) => {
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
+ };
+ const triggerAnotherBuild = () => {
+ const request2 = {
+ command: "rebuild",
+ key: buildKey
+ };
+ sendRequest(refs, request2, (error2, response2) => {
+ if (error2) {
+ reject(new Error(error2));
+ } else if (settlePromise) {
+ settlePromise();
+ } else {
+ triggerAnotherBuild();
+ }
+ });
+ };
+ triggerAnotherBuild();
+ });
+ return latestResultPromise;
+ },
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
+ const keys = {};
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
+ checkForInvalidFlags(options2, keys, `in watch() call`);
+ const request2 = {
+ command: "watch",
+ key: buildKey
+ };
+ if (delay) request2.delay = delay;
+ sendRequest(refs, request2, (error2) => {
+ if (error2) reject(new Error(error2));
+ else resolve(void 0);
+ });
+ }),
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
+ const keys = {};
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
+ const host = getFlag(options2, keys, "host", mustBeString);
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
+ checkForInvalidFlags(options2, keys, `in serve() call`);
+ const request2 = {
+ command: "serve",
+ key: buildKey,
+ onRequest: !!onRequest
+ };
+ if (port !== void 0) request2.port = port;
+ if (host !== void 0) request2.host = host;
+ if (servedir !== void 0) request2.servedir = servedir;
+ if (keyfile !== void 0) request2.keyfile = keyfile;
+ if (certfile !== void 0) request2.certfile = certfile;
+ if (fallback !== void 0) request2.fallback = fallback;
+ if (cors) {
+ const corsKeys = {};
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
+ if (Array.isArray(origin)) request2.corsOrigin = origin;
+ else if (origin !== void 0) request2.corsOrigin = [origin];
+ }
+ sendRequest(refs, request2, (error2, response2) => {
+ if (error2) return reject(new Error(error2));
+ if (onRequest) {
+ requestCallbacks["serve-request"] = (id, request3) => {
+ onRequest(request3.args);
+ sendResponse(id, {});
+ };
+ }
+ resolve(response2);
+ });
+ }),
+ cancel: () => new Promise((resolve) => {
+ if (didDispose) return resolve();
+ const request2 = {
+ command: "cancel",
+ key: buildKey
+ };
+ sendRequest(refs, request2, () => {
+ resolve();
+ });
+ }),
+ dispose: () => new Promise((resolve) => {
+ if (didDispose) return resolve();
+ didDispose = true;
+ const request2 = {
+ command: "dispose",
+ key: buildKey
+ };
+ sendRequest(refs, request2, () => {
+ resolve();
+ scheduleOnDisposeCallbacks();
+ refs.unref();
+ });
+ })
+ };
+ refs.ref();
+ callback(null, result);
+ });
+ }
+}
+var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
+ let onStartCallbacks = [];
+ let onEndCallbacks = [];
+ let onResolveCallbacks = {};
+ let onLoadCallbacks = {};
+ let onDisposeCallbacks = [];
+ let nextCallbackID = 0;
+ let i = 0;
+ let requestPlugins = [];
+ let isSetupDone = false;
+ plugins = [...plugins];
+ for (let item of plugins) {
+ let keys = {};
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
+ const name = getFlag(item, keys, "name", mustBeString);
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
+ try {
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
+ let plugin = {
+ name,
+ onStart: false,
+ onEnd: false,
+ onResolve: [],
+ onLoad: []
+ };
+ i++;
+ let resolve = (path3, options = {}) => {
+ if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
+ if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
+ let keys2 = /* @__PURE__ */ Object.create(null);
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
+ let importer = getFlag(options, keys2, "importer", mustBeString);
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
+ let kind = getFlag(options, keys2, "kind", mustBeString);
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
+ checkForInvalidFlags(options, keys2, "in resolve() call");
+ return new Promise((resolve2, reject) => {
+ const request = {
+ command: "resolve",
+ path: path3,
+ key: buildKey,
+ pluginName: name
+ };
+ if (pluginName != null) request.pluginName = pluginName;
+ if (importer != null) request.importer = importer;
+ if (namespace != null) request.namespace = namespace;
+ if (resolveDir != null) request.resolveDir = resolveDir;
+ if (kind != null) request.kind = kind;
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
+ if (pluginData != null) request.pluginData = details.store(pluginData);
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
+ sendRequest(refs, request, (error, response) => {
+ if (error !== null) reject(new Error(error));
+ else resolve2({
+ errors: replaceDetailsInMessages(response.errors, details),
+ warnings: replaceDetailsInMessages(response.warnings, details),
+ path: response.path,
+ external: response.external,
+ sideEffects: response.sideEffects,
+ namespace: response.namespace,
+ suffix: response.suffix,
+ pluginData: details.load(response.pluginData)
+ });
+ });
+ });
+ };
+ let promise = setup({
+ initialOptions,
+ resolve,
+ onStart(callback) {
+ let registeredText = `This error came from the "onStart" callback registered here:`;
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
+ onStartCallbacks.push({ name, callback, note: registeredNote });
+ plugin.onStart = true;
+ },
+ onEnd(callback) {
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
+ onEndCallbacks.push({ name, callback, note: registeredNote });
+ plugin.onEnd = true;
+ },
+ onResolve(options, callback) {
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
+ let keys2 = {};
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
+ let id = nextCallbackID++;
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
+ plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
+ },
+ onLoad(options, callback) {
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
+ let keys2 = {};
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
+ let id = nextCallbackID++;
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
+ plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
+ },
+ onDispose(callback) {
+ onDisposeCallbacks.push(callback);
+ },
+ esbuild: streamIn.esbuild
+ });
+ if (promise) await promise;
+ requestPlugins.push(plugin);
+ } catch (e) {
+ return { ok: false, error: e, pluginName: name };
+ }
+ }
+ requestCallbacks["on-start"] = async (id, request) => {
+ details.clear();
+ let response = { errors: [], warnings: [] };
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
+ try {
+ let result = await callback();
+ if (result != null) {
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
+ let keys = {};
+ let errors = getFlag(result, keys, "errors", mustBeArray);
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
+ }
+ } catch (e) {
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
+ }
+ }));
+ sendResponse(id, response);
+ };
+ requestCallbacks["on-resolve"] = async (id, request) => {
+ let response = {}, name = "", callback, note;
+ for (let id2 of request.ids) {
+ try {
+ ({ name, callback, note } = onResolveCallbacks[id2]);
+ let result = await callback({
+ path: request.path,
+ importer: request.importer,
+ namespace: request.namespace,
+ resolveDir: request.resolveDir,
+ kind: request.kind,
+ pluginData: details.load(request.pluginData),
+ with: request.with
+ });
+ if (result != null) {
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
+ let keys = {};
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
+ let path3 = getFlag(result, keys, "path", mustBeString);
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
+ let external = getFlag(result, keys, "external", mustBeBoolean);
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
+ let errors = getFlag(result, keys, "errors", mustBeArray);
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
+ response.id = id2;
+ if (pluginName != null) response.pluginName = pluginName;
+ if (path3 != null) response.path = path3;
+ if (namespace != null) response.namespace = namespace;
+ if (suffix != null) response.suffix = suffix;
+ if (external != null) response.external = external;
+ if (sideEffects != null) response.sideEffects = sideEffects;
+ if (pluginData != null) response.pluginData = details.store(pluginData);
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
+ break;
+ }
+ } catch (e) {
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
+ break;
+ }
+ }
+ sendResponse(id, response);
+ };
+ requestCallbacks["on-load"] = async (id, request) => {
+ let response = {}, name = "", callback, note;
+ for (let id2 of request.ids) {
+ try {
+ ({ name, callback, note } = onLoadCallbacks[id2]);
+ let result = await callback({
+ path: request.path,
+ namespace: request.namespace,
+ suffix: request.suffix,
+ pluginData: details.load(request.pluginData),
+ with: request.with
+ });
+ if (result != null) {
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
+ let keys = {};
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
+ let loader = getFlag(result, keys, "loader", mustBeString);
+ let errors = getFlag(result, keys, "errors", mustBeArray);
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
+ response.id = id2;
+ if (pluginName != null) response.pluginName = pluginName;
+ if (contents instanceof Uint8Array) response.contents = contents;
+ else if (contents != null) response.contents = encodeUTF8(contents);
+ if (resolveDir != null) response.resolveDir = resolveDir;
+ if (pluginData != null) response.pluginData = details.store(pluginData);
+ if (loader != null) response.loader = loader;
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
+ break;
+ }
+ } catch (e) {
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
+ break;
+ }
+ }
+ sendResponse(id, response);
+ };
+ let runOnEndCallbacks = (result, done) => done([], []);
+ if (onEndCallbacks.length > 0) {
+ runOnEndCallbacks = (result, done) => {
+ (async () => {
+ const onEndErrors = [];
+ const onEndWarnings = [];
+ for (const { name, callback, note } of onEndCallbacks) {
+ let newErrors;
+ let newWarnings;
+ try {
+ const value = await callback(result);
+ if (value != null) {
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
+ let keys = {};
+ let errors = getFlag(value, keys, "errors", mustBeArray);
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
+ }
+ } catch (e) {
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
+ }
+ if (newErrors) {
+ onEndErrors.push(...newErrors);
+ try {
+ result.errors.push(...newErrors);
+ } catch {
+ }
+ }
+ if (newWarnings) {
+ onEndWarnings.push(...newWarnings);
+ try {
+ result.warnings.push(...newWarnings);
+ } catch {
+ }
+ }
+ }
+ done(onEndErrors, onEndWarnings);
+ })();
+ };
+ }
+ let scheduleOnDisposeCallbacks = () => {
+ for (const cb of onDisposeCallbacks) {
+ setTimeout(() => cb(), 0);
+ }
+ };
+ isSetupDone = true;
+ return {
+ ok: true,
+ requestPlugins,
+ runOnEndCallbacks,
+ scheduleOnDisposeCallbacks
+ };
+};
+function createObjectStash() {
+ const map = /* @__PURE__ */ new Map();
+ let nextID = 0;
+ return {
+ clear() {
+ map.clear();
+ },
+ load(id) {
+ return map.get(id);
+ },
+ store(value) {
+ if (value === void 0) return -1;
+ const id = nextID++;
+ map.set(id, value);
+ return id;
+ }
+ };
+}
+function extractCallerV8(e, streamIn, ident) {
+ let note;
+ let tried = false;
+ return () => {
+ if (tried) return note;
+ tried = true;
+ try {
+ let lines = (e.stack + "").split("\n");
+ lines.splice(1, 1);
+ let location = parseStackLinesV8(streamIn, lines, ident);
+ if (location) {
+ note = { text: e.message, location };
+ return note;
+ }
+ } catch {
+ }
+ };
+}
+function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
+ let text = "Internal error";
+ let location = null;
+ try {
+ text = (e && e.message || e) + "";
+ } catch {
+ }
+ try {
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
+ } catch {
+ }
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
+}
+function parseStackLinesV8(streamIn, lines, ident) {
+ let at = " at ";
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
+ for (let i = 1; i < lines.length; i++) {
+ let line = lines[i];
+ if (!line.startsWith(at)) continue;
+ line = line.slice(at.length);
+ while (true) {
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
+ if (match) {
+ line = match[1];
+ continue;
+ }
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
+ if (match) {
+ line = match[1];
+ continue;
+ }
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
+ if (match) {
+ let contents;
+ try {
+ contents = streamIn.readFileSync(match[1], "utf8");
+ } catch {
+ break;
+ }
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
+ let column = +match[3] - 1;
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
+ return {
+ file: match[1],
+ namespace: "file",
+ line: +match[2],
+ column: encodeUTF8(lineText.slice(0, column)).length,
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
+ suggestion: ""
+ };
+ }
+ break;
+ }
+ }
+ }
+ return null;
+}
+function failureErrorWithLog(text, errors, warnings) {
+ let limit = 5;
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
+ if (i === limit) return "\n...";
+ if (!e.location) return `
+error: ${e.text}`;
+ let { file, line, column } = e.location;
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
+ return `
+${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
+ }).join("");
+ let error = new Error(text);
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
+ Object.defineProperty(error, key, {
+ configurable: true,
+ enumerable: true,
+ get: () => value,
+ set: (value2) => Object.defineProperty(error, key, {
+ configurable: true,
+ enumerable: true,
+ value: value2
+ })
+ });
+ }
+ return error;
+}
+function replaceDetailsInMessages(messages, stash) {
+ for (const message of messages) {
+ message.detail = stash.load(message.detail);
+ }
+ return messages;
+}
+function sanitizeLocation(location, where, terminalWidth) {
+ if (location == null) return null;
+ let keys = {};
+ let file = getFlag(location, keys, "file", mustBeString);
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
+ let line = getFlag(location, keys, "line", mustBeInteger);
+ let column = getFlag(location, keys, "column", mustBeInteger);
+ let length = getFlag(location, keys, "length", mustBeInteger);
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
+ checkForInvalidFlags(location, keys, where);
+ if (lineText) {
+ const relevantASCII = lineText.slice(
+ 0,
+ (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
+ );
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
+ lineText = relevantASCII;
+ }
+ }
+ return {
+ file: file || "",
+ namespace: namespace || "",
+ line: line || 0,
+ column: column || 0,
+ length: length || 0,
+ lineText: lineText || "",
+ suggestion: suggestion || ""
+ };
+}
+function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
+ let messagesClone = [];
+ let index = 0;
+ for (const message of messages) {
+ let keys = {};
+ let id = getFlag(message, keys, "id", mustBeString);
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
+ let text = getFlag(message, keys, "text", mustBeString);
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
+ let notes = getFlag(message, keys, "notes", mustBeArray);
+ let detail = getFlag(message, keys, "detail", canBeAnything);
+ let where = `in element ${index} of "${property}"`;
+ checkForInvalidFlags(message, keys, where);
+ let notesClone = [];
+ if (notes) {
+ for (const note of notes) {
+ let noteKeys = {};
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
+ checkForInvalidFlags(note, noteKeys, where);
+ notesClone.push({
+ text: noteText || "",
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
+ });
+ }
+ }
+ messagesClone.push({
+ id: id || "",
+ pluginName: pluginName || fallbackPluginName,
+ text: text || "",
+ location: sanitizeLocation(location, where, terminalWidth),
+ notes: notesClone,
+ detail: stash ? stash.store(detail) : -1
+ });
+ index++;
+ }
+ return messagesClone;
+}
+function sanitizeStringArray(values, property) {
+ const result = [];
+ for (const value of values) {
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
+ result.push(value);
+ }
+ return result;
+}
+function sanitizeStringMap(map, property) {
+ const result = /* @__PURE__ */ Object.create(null);
+ for (const key in map) {
+ const value = map[key];
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
+ result[key] = value;
+ }
+ return result;
+}
+function convertOutputFiles({ path: path3, contents, hash }) {
+ let text = null;
+ return {
+ path: path3,
+ contents,
+ hash,
+ get text() {
+ const binary = this.contents;
+ if (text === null || binary !== contents) {
+ contents = binary;
+ text = decodeUTF8(binary);
+ }
+ return text;
+ }
+ };
+}
+function jsRegExpToGoRegExp(regexp) {
+ let result = regexp.source;
+ if (regexp.flags) result = `(?${regexp.flags})${result}`;
+ return result;
+}
+
+// lib/npm/node-platform.ts
+var fs = require("fs");
+var os = require("os");
+var path = require("path");
+var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
+var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
+var packageDarwin_arm64 = "@esbuild/darwin-arm64";
+var packageDarwin_x64 = "@esbuild/darwin-x64";
+var knownWindowsPackages = {
+ "win32 arm64 LE": "@esbuild/win32-arm64",
+ "win32 ia32 LE": "@esbuild/win32-ia32",
+ "win32 x64 LE": "@esbuild/win32-x64"
+};
+var knownUnixlikePackages = {
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
+ "android arm64 LE": "@esbuild/android-arm64",
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
+ "darwin x64 LE": "@esbuild/darwin-x64",
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
+ "linux arm LE": "@esbuild/linux-arm",
+ "linux arm64 LE": "@esbuild/linux-arm64",
+ "linux ia32 LE": "@esbuild/linux-ia32",
+ "linux mips64el LE": "@esbuild/linux-mips64el",
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
+ "linux s390x BE": "@esbuild/linux-s390x",
+ "linux x64 LE": "@esbuild/linux-x64",
+ "linux loong64 LE": "@esbuild/linux-loong64",
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
+ "sunos x64 LE": "@esbuild/sunos-x64"
+};
+var knownWebAssemblyFallbackPackages = {
+ "android arm LE": "@esbuild/android-arm",
+ "android x64 LE": "@esbuild/android-x64",
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
+};
+function pkgAndSubpathForCurrentPlatform() {
+ let pkg;
+ let subpath;
+ let isWASM = false;
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
+ if (platformKey in knownWindowsPackages) {
+ pkg = knownWindowsPackages[platformKey];
+ subpath = "esbuild.exe";
+ } else if (platformKey in knownUnixlikePackages) {
+ pkg = knownUnixlikePackages[platformKey];
+ subpath = "bin/esbuild";
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
+ subpath = "bin/esbuild";
+ isWASM = true;
+ } else {
+ throw new Error(`Unsupported platform: ${platformKey}`);
+ }
+ return { pkg, subpath, isWASM };
+}
+function pkgForSomeOtherPlatform() {
+ const libMainJS = require.resolve("esbuild");
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
+ for (const unixKey in knownUnixlikePackages) {
+ try {
+ const pkg = knownUnixlikePackages[unixKey];
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
+ } catch {
+ }
+ }
+ for (const windowsKey in knownWindowsPackages) {
+ try {
+ const pkg = knownWindowsPackages[windowsKey];
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
+ } catch {
+ }
+ }
+ }
+ return null;
+}
+function downloadedBinPath(pkg, subpath) {
+ const esbuildLibDir = path.dirname(require.resolve("esbuild"));
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
+}
+function generateBinPath() {
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
+ } else {
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
+ }
+ }
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
+ let binPath;
+ try {
+ binPath = require.resolve(`${pkg}/${subpath}`);
+ } catch (e) {
+ binPath = downloadedBinPath(pkg, subpath);
+ if (!fs.existsSync(binPath)) {
+ try {
+ require.resolve(pkg);
+ } catch {
+ const otherPkg = pkgForSomeOtherPlatform();
+ if (otherPkg) {
+ let suggestions = `
+Specifically the "${otherPkg}" package is present but this platform
+needs the "${pkg}" package instead. People often get into this
+situation by installing esbuild on Windows or macOS and copying "node_modules"
+into a Docker image that runs Linux, or by copying "node_modules" between
+Windows and WSL environments.
+
+If you are installing with npm, you can try not copying the "node_modules"
+directory when you copy the files over, and running "npm ci" or "npm install"
+on the destination platform after the copy. Or you could consider using yarn
+instead of npm which has built-in support for installing a package on multiple
+platforms simultaneously.
+
+If you are installing with yarn, you can try listing both this platform and the
+other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
+feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
+Keep in mind that this means multiple copies of esbuild will be present.
+`;
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
+ suggestions = `
+Specifically the "${otherPkg}" package is present but this platform
+needs the "${pkg}" package instead. People often get into this
+situation by installing esbuild with npm running inside of Rosetta 2 and then
+trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
+2 is Apple's on-the-fly x86_64-to-arm64 translation service).
+
+If you are installing with npm, you can try ensuring that both npm and node are
+not running under Rosetta 2 and then reinstalling esbuild. This likely involves
+changing how you installed npm and/or node. For example, installing node with
+the universal installer here should work: https://nodejs.org/en/download/. Or
+you could consider using yarn instead of npm which has built-in support for
+installing a package on multiple platforms simultaneously.
+
+If you are installing with yarn, you can try listing both "arm64" and "x64"
+in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
+https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
+Keep in mind that this means multiple copies of esbuild will be present.
+`;
+ }
+ throw new Error(`
+You installed esbuild for another platform than the one you're currently using.
+This won't work because esbuild is written with native code and needs to
+install a platform-specific binary executable.
+${suggestions}
+Another alternative is to use the "esbuild-wasm" package instead, which works
+the same way on all platforms. But it comes with a heavy performance cost and
+can sometimes be 10x slower than the "esbuild" package, so you may also not
+want to do that.
+`);
+ }
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
+
+If you are installing esbuild with npm, make sure that you don't specify the
+"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
+of "package.json" is used by esbuild to install the correct binary executable
+for your current platform.`);
+ }
+ throw e;
+ }
+ }
+ if (/\.zip\//.test(binPath)) {
+ let pnpapi;
+ try {
+ pnpapi = require("pnpapi");
+ } catch (e) {
+ }
+ if (pnpapi) {
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
+ const binTargetPath = path.join(
+ root,
+ "node_modules",
+ ".cache",
+ "esbuild",
+ `pnpapi-${pkg.replace("/", "-")}-${"0.25.11"}-${path.basename(subpath)}`
+ );
+ if (!fs.existsSync(binTargetPath)) {
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
+ fs.copyFileSync(binPath, binTargetPath);
+ fs.chmodSync(binTargetPath, 493);
+ }
+ return { binPath: binTargetPath, isWASM };
+ }
+ }
+ return { binPath, isWASM };
+}
+
+// lib/npm/node.ts
+var child_process = require("child_process");
+var crypto = require("crypto");
+var path2 = require("path");
+var fs2 = require("fs");
+var os2 = require("os");
+var tty = require("tty");
+var worker_threads;
+if (process.env.ESBUILD_WORKER_THREADS !== "0") {
+ try {
+ worker_threads = require("worker_threads");
+ } catch {
+ }
+ let [major, minor] = process.versions.node.split(".");
+ if (
+ // <v12.17.0 does not work
+ +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
+ ) {
+ worker_threads = void 0;
+ }
+}
+var _a;
+var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.25.11";
+var esbuildCommandAndArgs = () => {
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
+ throw new Error(
+ `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
+
+More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`
+ );
+ }
+ if (false) {
+ return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
+ } else {
+ const { binPath, isWASM } = generateBinPath();
+ if (isWASM) {
+ return ["node", [binPath]];
+ } else {
+ return [binPath, []];
+ }
+ }
+};
+var isTTY = () => tty.isatty(2);
+var fsSync = {
+ readFile(tempFile, callback) {
+ try {
+ let contents = fs2.readFileSync(tempFile, "utf8");
+ try {
+ fs2.unlinkSync(tempFile);
+ } catch {
+ }
+ callback(null, contents);
+ } catch (err) {
+ callback(err, null);
+ }
+ },
+ writeFile(contents, callback) {
+ try {
+ let tempFile = randomFileName();
+ fs2.writeFileSync(tempFile, contents);
+ callback(tempFile);
+ } catch {
+ callback(null);
+ }
+ }
+};
+var fsAsync = {
+ readFile(tempFile, callback) {
+ try {
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
+ try {
+ fs2.unlink(tempFile, () => callback(err, contents));
+ } catch {
+ callback(err, contents);
+ }
+ });
+ } catch (err) {
+ callback(err, null);
+ }
+ },
+ writeFile(contents, callback) {
+ try {
+ let tempFile = randomFileName();
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
+ } catch {
+ callback(null);
+ }
+ }
+};
+var version = "0.25.11";
+var build = (options) => ensureServiceIsRunning().build(options);
+var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
+var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
+var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
+var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
+var buildSync = (options) => {
+ if (worker_threads && !isInternalWorkerThread) {
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
+ return workerThreadService.buildSync(options);
+ }
+ let result;
+ runServiceSync((service) => service.buildOrContext({
+ callName: "buildSync",
+ refs: null,
+ options,
+ isTTY: isTTY(),
+ defaultWD,
+ callback: (err, res) => {
+ if (err) throw err;
+ result = res;
+ }
+ }));
+ return result;
+};
+var transformSync = (input, options) => {
+ if (worker_threads && !isInternalWorkerThread) {
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
+ return workerThreadService.transformSync(input, options);
+ }
+ let result;
+ runServiceSync((service) => service.transform({
+ callName: "transformSync",
+ refs: null,
+ input,
+ options: options || {},
+ isTTY: isTTY(),
+ fs: fsSync,
+ callback: (err, res) => {
+ if (err) throw err;
+ result = res;
+ }
+ }));
+ return result;
+};
+var formatMessagesSync = (messages, options) => {
+ if (worker_threads && !isInternalWorkerThread) {
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
+ return workerThreadService.formatMessagesSync(messages, options);
+ }
+ let result;
+ runServiceSync((service) => service.formatMessages({
+ callName: "formatMessagesSync",
+ refs: null,
+ messages,
+ options,
+ callback: (err, res) => {
+ if (err) throw err;
+ result = res;
+ }
+ }));
+ return result;
+};
+var analyzeMetafileSync = (metafile, options) => {
+ if (worker_threads && !isInternalWorkerThread) {
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
+ return workerThreadService.analyzeMetafileSync(metafile, options);
+ }
+ let result;
+ runServiceSync((service) => service.analyzeMetafile({
+ callName: "analyzeMetafileSync",
+ refs: null,
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
+ options,
+ callback: (err, res) => {
+ if (err) throw err;
+ result = res;
+ }
+ }));
+ return result;
+};
+var stop = () => {
+ if (stopService) stopService();
+ if (workerThreadService) workerThreadService.stop();
+ return Promise.resolve();
+};
+var initializeWasCalled = false;
+var initialize = (options) => {
+ options = validateInitializeOptions(options || {});
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
+ if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
+ ensureServiceIsRunning();
+ initializeWasCalled = true;
+ return Promise.resolve();
+};
+var defaultWD = process.cwd();
+var longLivedService;
+var stopService;
+var ensureServiceIsRunning = () => {
+ if (longLivedService) return longLivedService;
+ let [command, args] = esbuildCommandAndArgs();
+ let child = child_process.spawn(command, args.concat(`--service=${"0.25.11"}`, "--ping"), {
+ windowsHide: true,
+ stdio: ["pipe", "pipe", "inherit"],
+ cwd: defaultWD
+ });
+ let { readFromStdout, afterClose, service } = createChannel({
+ writeToStdin(bytes) {
+ child.stdin.write(bytes, (err) => {
+ if (err) afterClose(err);
+ });
+ },
+ readFileSync: fs2.readFileSync,
+ isSync: false,
+ hasFS: true,
+ esbuild: node_exports
+ });
+ child.stdin.on("error", afterClose);
+ child.on("error", afterClose);
+ const stdin = child.stdin;
+ const stdout = child.stdout;
+ stdout.on("data", readFromStdout);
+ stdout.on("end", afterClose);
+ stopService = () => {
+ stdin.destroy();
+ stdout.destroy();
+ child.kill();
+ initializeWasCalled = false;
+ longLivedService = void 0;
+ stopService = void 0;
+ };
+ let refCount = 0;
+ child.unref();
+ if (stdin.unref) {
+ stdin.unref();
+ }
+ if (stdout.unref) {
+ stdout.unref();
+ }
+ const refs = {
+ ref() {
+ if (++refCount === 1) child.ref();
+ },
+ unref() {
+ if (--refCount === 0) child.unref();
+ }
+ };
+ longLivedService = {
+ build: (options) => new Promise((resolve, reject) => {
+ service.buildOrContext({
+ callName: "build",
+ refs,
+ options,
+ isTTY: isTTY(),
+ defaultWD,
+ callback: (err, res) => err ? reject(err) : resolve(res)
+ });
+ }),
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
+ callName: "context",
+ refs,
+ options,
+ isTTY: isTTY(),
+ defaultWD,
+ callback: (err, res) => err ? reject(err) : resolve(res)
+ })),
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
+ callName: "transform",
+ refs,
+ input,
+ options: options || {},
+ isTTY: isTTY(),
+ fs: fsAsync,
+ callback: (err, res) => err ? reject(err) : resolve(res)
+ })),
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
+ callName: "formatMessages",
+ refs,
+ messages,
+ options,
+ callback: (err, res) => err ? reject(err) : resolve(res)
+ })),
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
+ callName: "analyzeMetafile",
+ refs,
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
+ options,
+ callback: (err, res) => err ? reject(err) : resolve(res)
+ }))
+ };
+ return longLivedService;
+};
+var runServiceSync = (callback) => {
+ let [command, args] = esbuildCommandAndArgs();
+ let stdin = new Uint8Array();
+ let { readFromStdout, afterClose, service } = createChannel({
+ writeToStdin(bytes) {
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
+ stdin = bytes;
+ },
+ isSync: true,
+ hasFS: true,
+ esbuild: node_exports
+ });
+ callback(service);
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.25.11"}`), {
+ cwd: defaultWD,
+ windowsHide: true,
+ input: stdin,
+ // We don't know how large the output could be. If it's too large, the
+ // command will fail with ENOBUFS. Reserve 16mb for now since that feels
+ // like it should be enough. Also allow overriding this with an environment
+ // variable.
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
+ });
+ readFromStdout(stdout);
+ afterClose(null);
+};
+var randomFileName = () => {
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
+};
+var workerThreadService = null;
+var startWorkerThreadService = (worker_threads2) => {
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
+ let worker = new worker_threads2.Worker(__filename, {
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.25.11" },
+ transferList: [workerPort],
+ // From node's documentation: https://nodejs.org/api/worker_threads.html
+ //
+ // Take care when launching worker threads from preload scripts (scripts loaded
+ // and run using the `-r` command line flag). Unless the `execArgv` option is
+ // explicitly set, new Worker threads automatically inherit the command line flags
+ // from the running process and will preload the same preload scripts as the main
+ // thread. If the preload script unconditionally launches a worker thread, every
+ // thread spawned will spawn another until the application crashes.
+ //
+ execArgv: []
+ });
+ let nextID = 0;
+ let fakeBuildError = (text) => {
+ let error = new Error(`Build failed with 1 error:
+error: ${text}`);
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
+ error.errors = errors;
+ error.warnings = [];
+ return error;
+ };
+ let validateBuildSyncOptions = (options) => {
+ if (!options) return;
+ let plugins = options.plugins;
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
+ };
+ let applyProperties = (object, properties) => {
+ for (let key in properties) {
+ object[key] = properties[key];
+ }
+ };
+ let runCallSync = (command, args) => {
+ let id = nextID++;
+ let sharedBuffer = new SharedArrayBuffer(8);
+ let sharedBufferView = new Int32Array(sharedBuffer);
+ let msg = { sharedBuffer, id, command, args };
+ worker.postMessage(msg);
+ let status = Atomics.wait(sharedBufferView, 0, 0);
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
+ if (reject) {
+ applyProperties(reject, properties);
+ throw reject;
+ }
+ return resolve;
+ };
+ worker.unref();
+ return {
+ buildSync(options) {
+ validateBuildSyncOptions(options);
+ return runCallSync("build", [options]);
+ },
+ transformSync(input, options) {
+ return runCallSync("transform", [input, options]);
+ },
+ formatMessagesSync(messages, options) {
+ return runCallSync("formatMessages", [messages, options]);
+ },
+ analyzeMetafileSync(metafile, options) {
+ return runCallSync("analyzeMetafile", [metafile, options]);
+ },
+ stop() {
+ worker.terminate();
+ workerThreadService = null;
+ }
+ };
+};
+var startSyncServiceWorker = () => {
+ let workerPort = worker_threads.workerData.workerPort;
+ let parentPort = worker_threads.parentPort;
+ let extractProperties = (object) => {
+ let properties = {};
+ if (object && typeof object === "object") {
+ for (let key in object) {
+ properties[key] = object[key];
+ }
+ }
+ return properties;
+ };
+ try {
+ let service = ensureServiceIsRunning();
+ defaultWD = worker_threads.workerData.defaultWD;
+ parentPort.on("message", (msg) => {
+ (async () => {
+ let { sharedBuffer, id, command, args } = msg;
+ let sharedBufferView = new Int32Array(sharedBuffer);
+ try {
+ switch (command) {
+ case "build":
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
+ break;
+ case "transform":
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
+ break;
+ case "formatMessages":
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
+ break;
+ case "analyzeMetafile":
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
+ break;
+ default:
+ throw new Error(`Invalid command: ${command}`);
+ }
+ } catch (reject) {
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
+ }
+ Atomics.add(sharedBufferView, 0, 1);
+ Atomics.notify(sharedBufferView, 0, Infinity);
+ })();
+ });
+ } catch (reject) {
+ parentPort.on("message", (msg) => {
+ let { sharedBuffer, id } = msg;
+ let sharedBufferView = new Int32Array(sharedBuffer);
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
+ Atomics.add(sharedBufferView, 0, 1);
+ Atomics.notify(sharedBufferView, 0, Infinity);
+ });
+ }
+};
+if (isInternalWorkerThread) {
+ startSyncServiceWorker();
+}
+var node_default = node_exports;
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+ analyzeMetafile,
+ analyzeMetafileSync,
+ build,
+ buildSync,
+ context,
+ formatMessages,
+ formatMessagesSync,
+ initialize,
+ stop,
+ transform,
+ transformSync,
+ version
+});
diff --git a/frontend/node_modules/esbuild/package.json b/frontend/node_modules/esbuild/package.json
new file mode 100644
index 0000000..db3a4d5
--- /dev/null
+++ b/frontend/node_modules/esbuild/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "esbuild",
+ "version": "0.25.11",
+ "description": "An extremely fast JavaScript and CSS bundler and minifier.",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/evanw/esbuild.git"
+ },
+ "scripts": {
+ "postinstall": "node install.js"
+ },
+ "main": "lib/main.js",
+ "types": "lib/main.d.ts",
+ "engines": {
+ "node": ">=18"
+ },
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.11",
+ "@esbuild/android-arm": "0.25.11",
+ "@esbuild/android-arm64": "0.25.11",
+ "@esbuild/android-x64": "0.25.11",
+ "@esbuild/darwin-arm64": "0.25.11",
+ "@esbuild/darwin-x64": "0.25.11",
+ "@esbuild/freebsd-arm64": "0.25.11",
+ "@esbuild/freebsd-x64": "0.25.11",
+ "@esbuild/linux-arm": "0.25.11",
+ "@esbuild/linux-arm64": "0.25.11",
+ "@esbuild/linux-ia32": "0.25.11",
+ "@esbuild/linux-loong64": "0.25.11",
+ "@esbuild/linux-mips64el": "0.25.11",
+ "@esbuild/linux-ppc64": "0.25.11",
+ "@esbuild/linux-riscv64": "0.25.11",
+ "@esbuild/linux-s390x": "0.25.11",
+ "@esbuild/linux-x64": "0.25.11",
+ "@esbuild/netbsd-arm64": "0.25.11",
+ "@esbuild/netbsd-x64": "0.25.11",
+ "@esbuild/openbsd-arm64": "0.25.11",
+ "@esbuild/openbsd-x64": "0.25.11",
+ "@esbuild/openharmony-arm64": "0.25.11",
+ "@esbuild/sunos-x64": "0.25.11",
+ "@esbuild/win32-arm64": "0.25.11",
+ "@esbuild/win32-ia32": "0.25.11",
+ "@esbuild/win32-x64": "0.25.11"
+ },
+ "license": "MIT"
+}
diff --git a/frontend/node_modules/fdir/LICENSE b/frontend/node_modules/fdir/LICENSE
new file mode 100644
index 0000000..bb7fdee
--- /dev/null
+++ b/frontend/node_modules/fdir/LICENSE
@@ -0,0 +1,7 @@
+Copyright 2023 Abdullah Atta
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/frontend/node_modules/fdir/README.md b/frontend/node_modules/fdir/README.md
new file mode 100644
index 0000000..5c70530
--- /dev/null
+++ b/frontend/node_modules/fdir/README.md
@@ -0,0 +1,91 @@
+<p align="center">
+<img src="https://github.com/thecodrr/fdir/raw/master/assets/fdir.gif" width="75%"/>
+
+<h1 align="center">The Fastest Directory Crawler & Globber for NodeJS</h1>
+<p align="center">
+ <a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/npm/v/fdir?style=for-the-badge"/></a>
+ <a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/npm/dw/fdir?style=for-the-badge"/></a>
+ <a href="https://codeclimate.com/github/thecodrr/fdir/maintainability"><img src="https://img.shields.io/codeclimate/maintainability-percentage/thecodrr/fdir?style=for-the-badge"/></a>
+ <a href="https://coveralls.io/github/thecodrr/fdir?branch=master"><img src="https://img.shields.io/coveralls/github/thecodrr/fdir?style=for-the-badge"/></a>
+ <a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/bundlephobia/minzip/fdir?style=for-the-badge"/></a>
+ <a href="https://www.producthunt.com/posts/fdir-every-millisecond-matters"><img src="https://img.shields.io/badge/ProductHunt-Upvote-red?style=for-the-badge&logo=product-hunt"/></a>
+ <a href="https://dev.to/thecodrr/how-i-wrote-the-fastest-directory-crawler-ever-3p9c"><img src="https://img.shields.io/badge/dev.to-Read%20Blog-black?style=for-the-badge&logo=dev.to"/></a>
+ <a href="./LICENSE"><img src="https://img.shields.io/github/license/thecodrr/fdir?style=for-the-badge"/></a>
+</p>
+</p>
+
+⚡ **The Fastest:** Nothing similar (in the NodeJS world) beats `fdir` in speed. It can easily crawl a directory containing **1 million files in < 1 second.**
+
+💡 **Stupidly Easy:** `fdir` uses expressive Builder pattern to build the crawler increasing code readability.
+
+🤖 **Zero Dependencies\*:** `fdir` only uses NodeJS `fs` & `path` modules.
+
+🕺 **Astonishingly Small:** < 2KB in size gzipped & minified.
+
+🖮 **Hackable:** Extending `fdir` is extremely simple now that the new Builder API is here. Feel free to experiment around.
+
+_\* `picomatch` must be installed manually by the user to support globbing._
+
+## 🚄 Quickstart
+
+### Installation
+
+You can install using `npm`:
+
+```sh
+$ npm i fdir
+```
+
+or Yarn:
+
+```sh
+$ yarn add fdir
+```
+
+### Usage
+
+```ts
+import { fdir } from "fdir";
+
+// create the builder
+const api = new fdir().withFullPaths().crawl("path/to/dir");
+
+// get all files in a directory synchronously
+const files = api.sync();
+
+// or asynchronously
+api.withPromise().then((files) => {
+ // do something with the result here.
+});
+```
+
+## Documentation:
+
+Documentation for all methods is available [here](/documentation.md).
+
+## 📊 Benchmarks:
+
+Please check the benchmark against the latest version [here](/BENCHMARKS.md).
+
+## 🙏Used by:
+
+`fdir` is downloaded over 200k+ times a week by projects around the world. Here's a list of some notable projects using `fdir` in production:
+
+> Note: if you think your project should be here, feel free to open an issue. Notable is anything with a considerable amount of GitHub stars.
+
+1. [rollup/plugins](https://github.com/rollup/plugins)
+2. [SuperchupuDev/tinyglobby](https://github.com/SuperchupuDev/tinyglobby)
+3. [pulumi/pulumi](https://github.com/pulumi/pulumi)
+4. [dotenvx/dotenvx](https://github.com/dotenvx/dotenvx)
+5. [mdn/yari](https://github.com/mdn/yari)
+6. [streetwriters/notesnook](https://github.com/streetwriters/notesnook)
+7. [imba/imba](https://github.com/imba/imba)
+8. [moroshko/react-scanner](https://github.com/moroshko/react-scanner)
+9. [netlify/build](https://github.com/netlify/build)
+10. [yassinedoghri/astro-i18next](https://github.com/yassinedoghri/astro-i18next)
+11. [selfrefactor/rambda](https://github.com/selfrefactor/rambda)
+12. [whyboris/Video-Hub-App](https://github.com/whyboris/Video-Hub-App)
+
+## 🦮 LICENSE
+
+Copyright &copy; 2024 Abdullah Atta under MIT. [Read full text here.](https://github.com/thecodrr/fdir/raw/master/LICENSE)
diff --git a/frontend/node_modules/fdir/package.json b/frontend/node_modules/fdir/package.json
new file mode 100644
index 0000000..e229dff
--- /dev/null
+++ b/frontend/node_modules/fdir/package.json
@@ -0,0 +1,103 @@
+{
+ "name": "fdir",
+ "version": "6.5.0",
+ "description": "The fastest directory crawler & globbing alternative to glob, fast-glob, & tiny-glob. Crawls 1m files in < 1s",
+ "main": "./dist/index.cjs",
+ "types": "./dist/index.d.cts",
+ "type": "module",
+ "scripts": {
+ "prepublishOnly": "npm run test && npm run build",
+ "build": "tsdown",
+ "format": "prettier --write src __tests__ benchmarks",
+ "test": "vitest run __tests__/",
+ "test:coverage": "vitest run --coverage __tests__/",
+ "test:watch": "vitest __tests__/",
+ "bench": "ts-node benchmarks/benchmark.js",
+ "bench:glob": "ts-node benchmarks/glob-benchmark.ts",
+ "bench:fdir": "ts-node benchmarks/fdir-benchmark.ts",
+ "release": "./scripts/release.sh"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/thecodrr/fdir.git"
+ },
+ "keywords": [
+ "util",
+ "os",
+ "sys",
+ "fs",
+ "walk",
+ "crawler",
+ "directory",
+ "files",
+ "io",
+ "tiny-glob",
+ "glob",
+ "fast-glob",
+ "speed",
+ "javascript",
+ "nodejs"
+ ],
+ "author": "thecodrr <[email protected]>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/thecodrr/fdir/issues"
+ },
+ "homepage": "https://github.com/thecodrr/fdir#readme",
+ "devDependencies": {
+ "@types/glob": "^8.1.0",
+ "@types/mock-fs": "^4.13.4",
+ "@types/node": "^20.9.4",
+ "@types/picomatch": "^4.0.0",
+ "@types/tap": "^15.0.11",
+ "@vitest/coverage-v8": "^0.34.6",
+ "all-files-in-tree": "^1.1.2",
+ "benny": "^3.7.1",
+ "csv-to-markdown-table": "^1.3.1",
+ "expect": "^29.7.0",
+ "fast-glob": "^3.3.2",
+ "fdir1": "npm:[email protected]",
+ "fdir2": "npm:[email protected]",
+ "fdir3": "npm:[email protected]",
+ "fdir4": "npm:[email protected]",
+ "fdir5": "npm:[email protected]",
+ "fs-readdir-recursive": "^1.1.0",
+ "get-all-files": "^4.1.0",
+ "glob": "^10.3.10",
+ "klaw-sync": "^6.0.0",
+ "mock-fs": "^5.2.0",
+ "picomatch": "^4.0.2",
+ "prettier": "^3.5.3",
+ "recur-readdir": "0.0.1",
+ "recursive-files": "^1.0.2",
+ "recursive-fs": "^2.1.0",
+ "recursive-readdir": "^2.2.3",
+ "rrdir": "^12.1.0",
+ "systeminformation": "^5.21.17",
+ "tiny-glob": "^0.2.9",
+ "ts-node": "^10.9.1",
+ "tsdown": "^0.12.5",
+ "typescript": "^5.3.2",
+ "vitest": "^0.34.6",
+ "walk-sync": "^3.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ },
+ "module": "./dist/index.mjs",
+ "exports": {
+ ".": {
+ "import": "./dist/index.mjs",
+ "require": "./dist/index.cjs"
+ },
+ "./package.json": "./package.json"
+ }
+}
diff --git a/frontend/node_modules/nanoid/LICENSE b/frontend/node_modules/nanoid/LICENSE
new file mode 100644
index 0000000..37f56aa
--- /dev/null
+++ b/frontend/node_modules/nanoid/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright 2017 Andrey Sitnik <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/frontend/node_modules/nanoid/README.md b/frontend/node_modules/nanoid/README.md
new file mode 100644
index 0000000..35abb57
--- /dev/null
+++ b/frontend/node_modules/nanoid/README.md
@@ -0,0 +1,39 @@
+# Nano ID
+
+<img src="https://ai.github.io/nanoid/logo.svg" align="right"
+ alt="Nano ID logo by Anton Lovchikov" width="180" height="94">
+
+**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
+
+A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
+
+> “An amazing level of senseless perfectionism,
+> which is simply impossible not to respect.”
+
+* **Small.** 130 bytes (minified and gzipped). No dependencies.
+ [Size Limit] controls the size.
+* **Fast.** It is 2 times faster than UUID.
+* **Safe.** It uses hardware random generator. Can be used in clusters.
+* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
+ So ID size was reduced from 36 to 21 symbols.
+* **Portable.** Nano ID was ported
+ to [20 programming languages](#other-programming-languages).
+
+```js
+import { nanoid } from 'nanoid'
+model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
+```
+
+Supports modern browsers, IE [with Babel], Node.js and React Native.
+
+[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/
+[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
+[Size Limit]: https://github.com/ai/size-limit
+
+<a href="https://evilmartians.com/?utm_source=nanoid">
+ <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
+ alt="Sponsored by Evil Martians" width="236" height="54">
+</a>
+
+## Docs
+Read full docs **[here](https://github.com/ai/nanoid#readme)**.
diff --git a/frontend/node_modules/nanoid/async/index.browser.cjs b/frontend/node_modules/nanoid/async/index.browser.cjs
new file mode 100644
index 0000000..80d1871
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.browser.cjs
@@ -0,0 +1,69 @@
+let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+ // values closer to the alphabet size. The bitmask calculates the closest
+ // `2^31 - 1` number, which exceeds the alphabet size.
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+ // `Math.clz32` is not used, because it is not available in browsers.
+ let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+ // Though, the bitmask solution is not perfect since the bytes exceeding
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
+ // the random bytes redundancy has to be satisfied.
+
+ // Note: every hardware random generator call is performance expensive,
+ // because the system call for entropy collection takes a lot of time.
+ // So, to avoid additional system calls, extra bytes are requested in advance.
+
+ // Next, a step determines how many random bytes to generate.
+ // The number of random bytes gets decided upon the ID size, mask,
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+ // according to benchmarks).
+
+ // `-~f => Math.ceil(f)` if f is a float
+ // `-~i => i + 1` if i is an integer
+ let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+
+ return async (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = crypto.getRandomValues(new Uint8Array(step))
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ let i = step | 0
+ while (i--) {
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+
+let nanoid = async (size = 21) => {
+ let id = ''
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
+
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ while (size--) {
+ // It is incorrect to use bytes exceeding the alphabet size.
+ // The following mask reduces the random byte in the 0-255 value
+ // range to the 0-63 value range. Therefore, adding hacks, such
+ // as empty string fallback or magic numbers, is unneccessary because
+ // the bitmask trims bytes down to the alphabet size.
+ let byte = bytes[size] & 63
+ if (byte < 36) {
+ // `0-9a-z`
+ id += byte.toString(36)
+ } else if (byte < 62) {
+ // `A-Z`
+ id += (byte - 26).toString(36).toUpperCase()
+ } else if (byte < 63) {
+ id += '_'
+ } else {
+ id += '-'
+ }
+ }
+ return id
+}
+
+module.exports = { nanoid, customAlphabet, random }
diff --git a/frontend/node_modules/nanoid/async/index.browser.js b/frontend/node_modules/nanoid/async/index.browser.js
new file mode 100644
index 0000000..fbaa230
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.browser.js
@@ -0,0 +1,34 @@
+let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+ let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+ return async (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = crypto.getRandomValues(new Uint8Array(step))
+ let i = step | 0
+ while (i--) {
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+let nanoid = async (size = 21) => {
+ let id = ''
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
+ while (size--) {
+ let byte = bytes[size] & 63
+ if (byte < 36) {
+ id += byte.toString(36)
+ } else if (byte < 62) {
+ id += (byte - 26).toString(36).toUpperCase()
+ } else if (byte < 63) {
+ id += '_'
+ } else {
+ id += '-'
+ }
+ }
+ return id
+}
+export { nanoid, customAlphabet, random }
diff --git a/frontend/node_modules/nanoid/async/index.cjs b/frontend/node_modules/nanoid/async/index.cjs
new file mode 100644
index 0000000..f1b0ad0
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.cjs
@@ -0,0 +1,71 @@
+let crypto = require('crypto')
+
+let { urlAlphabet } = require('../url-alphabet/index.cjs')
+
+// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
+// because it is possible to use in combination with `Buffer.allocUnsafe()`.
+let random = bytes =>
+ new Promise((resolve, reject) => {
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
+ // Memory flushing is unnecessary since the buffer allocation itself resets
+ // the memory with the new bytes.
+ crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(buf)
+ }
+ })
+ })
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+ // values closer to the alphabet size. The bitmask calculates the closest
+ // `2^31 - 1` number, which exceeds the alphabet size.
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+ let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+ // Though, the bitmask solution is not perfect since the bytes exceeding
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
+ // the random bytes redundancy has to be satisfied.
+
+ // Note: every hardware random generator call is performance expensive,
+ // because the system call for entropy collection takes a lot of time.
+ // So, to avoid additional system calls, extra bytes are requested in advance.
+
+ // Next, a step determines how many random bytes to generate.
+ // The number of random bytes gets decided upon the ID size, mask,
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+ // according to benchmarks).
+ let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+
+ let tick = (id, size = defaultSize) =>
+ random(step).then(bytes => {
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ let i = step
+ while (i--) {
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length >= size) return id
+ }
+ return tick(id, size)
+ })
+
+ return size => tick('', size)
+}
+
+let nanoid = (size = 21) =>
+ random((size |= 0)).then(bytes => {
+ let id = ''
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ while (size--) {
+ // It is incorrect to use bytes exceeding the alphabet size.
+ // The following mask reduces the random byte in the 0-255 value
+ // range to the 0-63 value range. Therefore, adding hacks, such
+ // as empty string fallback or magic numbers, is unneccessary because
+ // the bitmask trims bytes down to the alphabet size.
+ id += urlAlphabet[bytes[size] & 63]
+ }
+ return id
+ })
+
+module.exports = { nanoid, customAlphabet, random }
diff --git a/frontend/node_modules/nanoid/async/index.d.ts b/frontend/node_modules/nanoid/async/index.d.ts
new file mode 100644
index 0000000..9e91965
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.d.ts
@@ -0,0 +1,56 @@
+/**
+ * Generate secure URL-friendly unique ID. The non-blocking version.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid/async'
+ * nanoid().then(id => {
+ * model.id = id
+ * })
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A promise with a random string.
+ */
+export function nanoid(size?: number): Promise<string>
+
+/**
+ * A low-level function.
+ * Generate secure unique ID with custom alphabet. The non-blocking version.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A function that returns a promise with a random string.
+ *
+ * ```js
+ * import { customAlphabet } from 'nanoid/async'
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid().then(id => {
+ * model.id = id //=> "8ё56а"
+ * })
+ * ```
+ */
+export function customAlphabet(
+ alphabet: string,
+ defaultSize?: number
+): (size?: number) => Promise<string>
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { random } from 'nanoid/async'
+ * random(5).then(bytes => {
+ * bytes //=> [10, 67, 212, 67, 89]
+ * })
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns A promise with a random bytes array.
+ */
+export function random(bytes: number): Promise<Uint8Array>
diff --git a/frontend/node_modules/nanoid/async/index.js b/frontend/node_modules/nanoid/async/index.js
new file mode 100644
index 0000000..cec454a
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.js
@@ -0,0 +1,35 @@
+import crypto from 'crypto'
+import { urlAlphabet } from '../url-alphabet/index.js'
+let random = bytes =>
+ new Promise((resolve, reject) => {
+ crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(buf)
+ }
+ })
+ })
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+ let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+ let tick = (id, size = defaultSize) =>
+ random(step).then(bytes => {
+ let i = step
+ while (i--) {
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length >= size) return id
+ }
+ return tick(id, size)
+ })
+ return size => tick('', size)
+}
+let nanoid = (size = 21) =>
+ random((size |= 0)).then(bytes => {
+ let id = ''
+ while (size--) {
+ id += urlAlphabet[bytes[size] & 63]
+ }
+ return id
+ })
+export { nanoid, customAlphabet, random }
diff --git a/frontend/node_modules/nanoid/async/index.native.js b/frontend/node_modules/nanoid/async/index.native.js
new file mode 100644
index 0000000..7c1d6f3
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/index.native.js
@@ -0,0 +1,26 @@
+import { getRandomBytesAsync } from 'expo-random'
+import { urlAlphabet } from '../url-alphabet/index.js'
+let random = getRandomBytesAsync
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+ let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+ let tick = (id, size = defaultSize) =>
+ random(step).then(bytes => {
+ let i = step
+ while (i--) {
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length >= size) return id
+ }
+ return tick(id, size)
+ })
+ return size => tick('', size)
+}
+let nanoid = (size = 21) =>
+ random((size |= 0)).then(bytes => {
+ let id = ''
+ while (size--) {
+ id += urlAlphabet[bytes[size] & 63]
+ }
+ return id
+ })
+export { nanoid, customAlphabet, random }
diff --git a/frontend/node_modules/nanoid/async/package.json b/frontend/node_modules/nanoid/async/package.json
new file mode 100644
index 0000000..578cdb4
--- /dev/null
+++ b/frontend/node_modules/nanoid/async/package.json
@@ -0,0 +1,12 @@
+{
+ "type": "module",
+ "main": "index.cjs",
+ "module": "index.js",
+ "react-native": {
+ "./index.js": "./index.native.js"
+ },
+ "browser": {
+ "./index.js": "./index.browser.js",
+ "./index.cjs": "./index.browser.cjs"
+ }
+}
\ No newline at end of file
diff --git a/frontend/node_modules/nanoid/bin/nanoid.cjs b/frontend/node_modules/nanoid/bin/nanoid.cjs
new file mode 100644
index 0000000..c76db0f
--- /dev/null
+++ b/frontend/node_modules/nanoid/bin/nanoid.cjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+
+let { nanoid, customAlphabet } = require('..')
+
+function print(msg) {
+ process.stdout.write(msg + '\n')
+}
+
+function error(msg) {
+ process.stderr.write(msg + '\n')
+ process.exit(1)
+}
+
+if (process.argv.includes('--help') || process.argv.includes('-h')) {
+ print(`
+ Usage
+ $ nanoid [options]
+
+ Options
+ -s, --size Generated ID size
+ -a, --alphabet Alphabet to use
+ -h, --help Show this help
+
+ Examples
+ $ nanoid --s 15
+ S9sBF77U6sDB8Yg
+
+ $ nanoid --size 10 --alphabet abc
+ bcabababca`)
+ process.exit()
+}
+
+let alphabet, size
+for (let i = 2; i < process.argv.length; i++) {
+ let arg = process.argv[i]
+ if (arg === '--size' || arg === '-s') {
+ size = Number(process.argv[i + 1])
+ i += 1
+ if (Number.isNaN(size) || size <= 0) {
+ error('Size must be positive integer')
+ }
+ } else if (arg === '--alphabet' || arg === '-a') {
+ alphabet = process.argv[i + 1]
+ i += 1
+ } else {
+ error('Unknown argument ' + arg)
+ }
+}
+
+if (alphabet) {
+ let customNanoid = customAlphabet(alphabet, size)
+ print(customNanoid())
+} else {
+ print(nanoid(size))
+}
diff --git a/frontend/node_modules/nanoid/index.browser.cjs b/frontend/node_modules/nanoid/index.browser.cjs
new file mode 100644
index 0000000..d21a91f
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.browser.cjs
@@ -0,0 +1,72 @@
+// This file replaces `index.js` in bundlers like webpack or Rollup,
+// according to `browser` config in `package.json`.
+
+let { urlAlphabet } = require('./url-alphabet/index.cjs')
+
+let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
+
+let customRandom = (alphabet, defaultSize, getRandom) => {
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+ // values closer to the alphabet size. The bitmask calculates the closest
+ // `2^31 - 1` number, which exceeds the alphabet size.
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+ // `Math.clz32` is not used, because it is not available in browsers.
+ let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+ // Though, the bitmask solution is not perfect since the bytes exceeding
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
+ // the random bytes redundancy has to be satisfied.
+
+ // Note: every hardware random generator call is performance expensive,
+ // because the system call for entropy collection takes a lot of time.
+ // So, to avoid additional system calls, extra bytes are requested in advance.
+
+ // Next, a step determines how many random bytes to generate.
+ // The number of random bytes gets decided upon the ID size, mask,
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+ // according to benchmarks).
+
+ // `-~f => Math.ceil(f)` if f is a float
+ // `-~i => i + 1` if i is an integer
+ let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+
+ return (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = getRandom(step)
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ let j = step | 0
+ while (j--) {
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+ id += alphabet[bytes[j] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+
+let customAlphabet = (alphabet, size = 21) =>
+ customRandom(alphabet, size, random)
+
+let nanoid = (size = 21) =>
+ crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
+ // It is incorrect to use bytes exceeding the alphabet size.
+ // The following mask reduces the random byte in the 0-255 value
+ // range to the 0-63 value range. Therefore, adding hacks, such
+ // as empty string fallback or magic numbers, is unneccessary because
+ // the bitmask trims bytes down to the alphabet size.
+ byte &= 63
+ if (byte < 36) {
+ // `0-9a-z`
+ id += byte.toString(36)
+ } else if (byte < 62) {
+ // `A-Z`
+ id += (byte - 26).toString(36).toUpperCase()
+ } else if (byte > 62) {
+ id += '-'
+ } else {
+ id += '_'
+ }
+ return id
+ }, '')
+
+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/frontend/node_modules/nanoid/index.browser.js b/frontend/node_modules/nanoid/index.browser.js
new file mode 100644
index 0000000..7d3b876
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.browser.js
@@ -0,0 +1,34 @@
+import { urlAlphabet } from './url-alphabet/index.js'
+let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
+let customRandom = (alphabet, defaultSize, getRandom) => {
+ let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+ let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+ return (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = getRandom(step)
+ let j = step | 0
+ while (j--) {
+ id += alphabet[bytes[j] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+let customAlphabet = (alphabet, size = 21) =>
+ customRandom(alphabet, size, random)
+let nanoid = (size = 21) =>
+ crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
+ byte &= 63
+ if (byte < 36) {
+ id += byte.toString(36)
+ } else if (byte < 62) {
+ id += (byte - 26).toString(36).toUpperCase()
+ } else if (byte > 62) {
+ id += '-'
+ } else {
+ id += '_'
+ }
+ return id
+ }, '')
+export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/frontend/node_modules/nanoid/index.cjs b/frontend/node_modules/nanoid/index.cjs
new file mode 100644
index 0000000..c20e374
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.cjs
@@ -0,0 +1,85 @@
+let crypto = require('crypto')
+
+let { urlAlphabet } = require('./url-alphabet/index.cjs')
+
+// It is best to make fewer, larger requests to the crypto module to
+// avoid system call overhead. So, random numbers are generated in a
+// pool. The pool is a Buffer that is larger than the initial random
+// request size by this multiplier. The pool is enlarged if subsequent
+// requests exceed the maximum buffer size.
+const POOL_SIZE_MULTIPLIER = 128
+let pool, poolOffset
+
+let fillPool = bytes => {
+ if (!pool || pool.length < bytes) {
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
+ crypto.randomFillSync(pool)
+ poolOffset = 0
+ } else if (poolOffset + bytes > pool.length) {
+ crypto.randomFillSync(pool)
+ poolOffset = 0
+ }
+ poolOffset += bytes
+}
+
+let random = bytes => {
+ // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
+ fillPool((bytes |= 0))
+ return pool.subarray(poolOffset - bytes, poolOffset)
+}
+
+let customRandom = (alphabet, defaultSize, getRandom) => {
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+ // values closer to the alphabet size. The bitmask calculates the closest
+ // `2^31 - 1` number, which exceeds the alphabet size.
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+ let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+ // Though, the bitmask solution is not perfect since the bytes exceeding
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
+ // the random bytes redundancy has to be satisfied.
+
+ // Note: every hardware random generator call is performance expensive,
+ // because the system call for entropy collection takes a lot of time.
+ // So, to avoid additional system calls, extra bytes are requested in advance.
+
+ // Next, a step determines how many random bytes to generate.
+ // The number of random bytes gets decided upon the ID size, mask,
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+ // according to benchmarks).
+ let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+
+ return (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = getRandom(step)
+ // A compact alternative for `for (let i = 0; i < step; i++)`.
+ let i = step
+ while (i--) {
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+
+let customAlphabet = (alphabet, size = 21) =>
+ customRandom(alphabet, size, random)
+
+let nanoid = (size = 21) => {
+ // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
+ fillPool((size |= 0))
+ let id = ''
+ // We are reading directly from the random pool to avoid creating new array
+ for (let i = poolOffset - size; i < poolOffset; i++) {
+ // It is incorrect to use bytes exceeding the alphabet size.
+ // The following mask reduces the random byte in the 0-255 value
+ // range to the 0-63 value range. Therefore, adding hacks, such
+ // as empty string fallback or magic numbers, is unneccessary because
+ // the bitmask trims bytes down to the alphabet size.
+ id += urlAlphabet[pool[i] & 63]
+ }
+ return id
+}
+
+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/frontend/node_modules/nanoid/index.d.cts b/frontend/node_modules/nanoid/index.d.cts
new file mode 100644
index 0000000..3e111a3
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.d.cts
@@ -0,0 +1,91 @@
+/**
+ * Generate secure URL-friendly unique ID.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate secure unique ID with custom alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * const { customAlphabet } = require('nanoid')
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid() //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+ alphabet: string,
+ defaultSize?: number
+): (size?: number) => string
+
+/**
+ * Generate unique ID with custom random generator and alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * ```js
+ * import { customRandom } from 'nanoid/format'
+ *
+ * const nanoid = customRandom('abcdef', 5, size => {
+ * const random = []
+ * for (let i = 0; i < size; i++) {
+ * random.push(randomByte())
+ * }
+ * return random
+ * })
+ *
+ * nanoid() //=> "fbaef"
+ * ```
+ *
+ * @param alphabet Alphabet used to generate a random string.
+ * @param size Size of the random string.
+ * @param random A random bytes generator.
+ * @returns A random string generator.
+ */
+export function customRandom(
+ alphabet: string,
+ size: number,
+ random: (bytes: number) => Uint8Array
+): () => string
+
+/**
+ * URL safe symbols.
+ *
+ * ```js
+ * import { urlAlphabet } from 'nanoid'
+ * const nanoid = customAlphabet(urlAlphabet, 10)
+ * nanoid() //=> "Uakgb_J5m9"
+ * ```
+ */
+export const urlAlphabet: string
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { customRandom, random } from 'nanoid'
+ * const nanoid = customRandom("abcdef", 5, random)
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns An array of random bytes.
+ */
+export function random(bytes: number): Uint8Array
diff --git a/frontend/node_modules/nanoid/index.d.ts b/frontend/node_modules/nanoid/index.d.ts
new file mode 100644
index 0000000..3e111a3
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.d.ts
@@ -0,0 +1,91 @@
+/**
+ * Generate secure URL-friendly unique ID.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate secure unique ID with custom alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * const { customAlphabet } = require('nanoid')
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid() //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+ alphabet: string,
+ defaultSize?: number
+): (size?: number) => string
+
+/**
+ * Generate unique ID with custom random generator and alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * ```js
+ * import { customRandom } from 'nanoid/format'
+ *
+ * const nanoid = customRandom('abcdef', 5, size => {
+ * const random = []
+ * for (let i = 0; i < size; i++) {
+ * random.push(randomByte())
+ * }
+ * return random
+ * })
+ *
+ * nanoid() //=> "fbaef"
+ * ```
+ *
+ * @param alphabet Alphabet used to generate a random string.
+ * @param size Size of the random string.
+ * @param random A random bytes generator.
+ * @returns A random string generator.
+ */
+export function customRandom(
+ alphabet: string,
+ size: number,
+ random: (bytes: number) => Uint8Array
+): () => string
+
+/**
+ * URL safe symbols.
+ *
+ * ```js
+ * import { urlAlphabet } from 'nanoid'
+ * const nanoid = customAlphabet(urlAlphabet, 10)
+ * nanoid() //=> "Uakgb_J5m9"
+ * ```
+ */
+export const urlAlphabet: string
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { customRandom, random } from 'nanoid'
+ * const nanoid = customRandom("abcdef", 5, random)
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns An array of random bytes.
+ */
+export function random(bytes: number): Uint8Array
diff --git a/frontend/node_modules/nanoid/index.js b/frontend/node_modules/nanoid/index.js
new file mode 100644
index 0000000..9bc909d
--- /dev/null
+++ b/frontend/node_modules/nanoid/index.js
@@ -0,0 +1,45 @@
+import crypto from 'crypto'
+import { urlAlphabet } from './url-alphabet/index.js'
+const POOL_SIZE_MULTIPLIER = 128
+let pool, poolOffset
+let fillPool = bytes => {
+ if (!pool || pool.length < bytes) {
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
+ crypto.randomFillSync(pool)
+ poolOffset = 0
+ } else if (poolOffset + bytes > pool.length) {
+ crypto.randomFillSync(pool)
+ poolOffset = 0
+ }
+ poolOffset += bytes
+}
+let random = bytes => {
+ fillPool((bytes |= 0))
+ return pool.subarray(poolOffset - bytes, poolOffset)
+}
+let customRandom = (alphabet, defaultSize, getRandom) => {
+ let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+ let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+ return (size = defaultSize) => {
+ let id = ''
+ while (true) {
+ let bytes = getRandom(step)
+ let i = step
+ while (i--) {
+ id += alphabet[bytes[i] & mask] || ''
+ if (id.length === size) return id
+ }
+ }
+ }
+}
+let customAlphabet = (alphabet, size = 21) =>
+ customRandom(alphabet, size, random)
+let nanoid = (size = 21) => {
+ fillPool((size |= 0))
+ let id = ''
+ for (let i = poolOffset - size; i < poolOffset; i++) {
+ id += urlAlphabet[pool[i] & 63]
+ }
+ return id
+}
+export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/frontend/node_modules/nanoid/nanoid.js b/frontend/node_modules/nanoid/nanoid.js
new file mode 100644
index 0000000..ec242ea
--- /dev/null
+++ b/frontend/node_modules/nanoid/nanoid.js
@@ -0,0 +1 @@
+export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),"");
\ No newline at end of file
diff --git a/frontend/node_modules/nanoid/non-secure/index.cjs b/frontend/node_modules/nanoid/non-secure/index.cjs
new file mode 100644
index 0000000..d51fcb6
--- /dev/null
+++ b/frontend/node_modules/nanoid/non-secure/index.cjs
@@ -0,0 +1,34 @@
+// This alphabet uses `A-Za-z0-9_-` symbols.
+// The order of characters is optimized for better gzip and brotli compression.
+// References to the same file (works both for gzip and brotli):
+// `'use`, `andom`, and `rict'`
+// References to the brotli default dictionary:
+// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
+let urlAlphabet =
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ return (size = defaultSize) => {
+ let id = ''
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ let i = size | 0
+ while (i--) {
+ // `| 0` is more compact and faster than `Math.floor()`.
+ id += alphabet[(Math.random() * alphabet.length) | 0]
+ }
+ return id
+ }
+}
+
+let nanoid = (size = 21) => {
+ let id = ''
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
+ let i = size | 0
+ while (i--) {
+ // `| 0` is more compact and faster than `Math.floor()`.
+ id += urlAlphabet[(Math.random() * 64) | 0]
+ }
+ return id
+}
+
+module.exports = { nanoid, customAlphabet }
diff --git a/frontend/node_modules/nanoid/non-secure/index.d.ts b/frontend/node_modules/nanoid/non-secure/index.d.ts
new file mode 100644
index 0000000..4965322
--- /dev/null
+++ b/frontend/node_modules/nanoid/non-secure/index.d.ts
@@ -0,0 +1,33 @@
+/**
+ * Generate URL-friendly unique ID. This method uses the non-secure
+ * predictable random generator with bigger collision probability.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid/non-secure'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate a unique ID based on a custom alphabet.
+ * This method uses the non-secure predictable random generator
+ * with bigger collision probability.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * import { customAlphabet } from 'nanoid/non-secure'
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * model.id = //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+ alphabet: string,
+ defaultSize?: number
+): (size?: number) => string
diff --git a/frontend/node_modules/nanoid/non-secure/index.js b/frontend/node_modules/nanoid/non-secure/index.js
new file mode 100644
index 0000000..2ea5827
--- /dev/null
+++ b/frontend/node_modules/nanoid/non-secure/index.js
@@ -0,0 +1,21 @@
+let urlAlphabet =
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+let customAlphabet = (alphabet, defaultSize = 21) => {
+ return (size = defaultSize) => {
+ let id = ''
+ let i = size | 0
+ while (i--) {
+ id += alphabet[(Math.random() * alphabet.length) | 0]
+ }
+ return id
+ }
+}
+let nanoid = (size = 21) => {
+ let id = ''
+ let i = size | 0
+ while (i--) {
+ id += urlAlphabet[(Math.random() * 64) | 0]
+ }
+ return id
+}
+export { nanoid, customAlphabet }
diff --git a/frontend/node_modules/nanoid/non-secure/package.json b/frontend/node_modules/nanoid/non-secure/package.json
new file mode 100644
index 0000000..9930d6a
--- /dev/null
+++ b/frontend/node_modules/nanoid/non-secure/package.json
@@ -0,0 +1,6 @@
+{
+ "type": "module",
+ "main": "index.cjs",
+ "module": "index.js",
+ "react-native": "index.js"
+}
\ No newline at end of file
diff --git a/frontend/node_modules/nanoid/package.json b/frontend/node_modules/nanoid/package.json
new file mode 100644
index 0000000..a3d3f44
--- /dev/null
+++ b/frontend/node_modules/nanoid/package.json
@@ -0,0 +1,89 @@
+{
+ "name": "nanoid",
+ "version": "3.3.11",
+ "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
+ "keywords": [
+ "uuid",
+ "random",
+ "id",
+ "url"
+ ],
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ },
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "author": "Andrey Sitnik <[email protected]>",
+ "license": "MIT",
+ "repository": "ai/nanoid",
+ "browser": {
+ "./index.js": "./index.browser.js",
+ "./async/index.js": "./async/index.browser.js",
+ "./async/index.cjs": "./async/index.browser.cjs",
+ "./index.cjs": "./index.browser.cjs"
+ },
+ "react-native": "index.js",
+ "bin": "./bin/nanoid.cjs",
+ "sideEffects": false,
+ "types": "./index.d.ts",
+ "type": "module",
+ "main": "index.cjs",
+ "module": "index.js",
+ "exports": {
+ ".": {
+ "react-native": "./index.browser.js",
+ "browser": "./index.browser.js",
+ "require": {
+ "types": "./index.d.cts",
+ "default": "./index.cjs"
+ },
+ "import": {
+ "types": "./index.d.ts",
+ "default": "./index.js"
+ },
+ "default": "./index.js"
+ },
+ "./package.json": "./package.json",
+ "./async/package.json": "./async/package.json",
+ "./async": {
+ "browser": "./async/index.browser.js",
+ "require": {
+ "types": "./index.d.cts",
+ "default": "./async/index.cjs"
+ },
+ "import": {
+ "types": "./index.d.ts",
+ "default": "./async/index.js"
+ },
+ "default": "./async/index.js"
+ },
+ "./non-secure/package.json": "./non-secure/package.json",
+ "./non-secure": {
+ "require": {
+ "types": "./index.d.cts",
+ "default": "./non-secure/index.cjs"
+ },
+ "import": {
+ "types": "./index.d.ts",
+ "default": "./non-secure/index.js"
+ },
+ "default": "./non-secure/index.js"
+ },
+ "./url-alphabet/package.json": "./url-alphabet/package.json",
+ "./url-alphabet": {
+ "require": {
+ "types": "./index.d.cts",
+ "default": "./url-alphabet/index.cjs"
+ },
+ "import": {
+ "types": "./index.d.ts",
+ "default": "./url-alphabet/index.js"
+ },
+ "default": "./url-alphabet/index.js"
+ }
+ }
+}
diff --git a/frontend/node_modules/nanoid/url-alphabet/index.cjs b/frontend/node_modules/nanoid/url-alphabet/index.cjs
new file mode 100644
index 0000000..a332f0b
--- /dev/null
+++ b/frontend/node_modules/nanoid/url-alphabet/index.cjs
@@ -0,0 +1,7 @@
+// This alphabet uses `A-Za-z0-9_-` symbols.
+// The order of characters is optimized for better gzip and brotli compression.
+// Same as in non-secure/index.js
+let urlAlphabet =
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+
+module.exports = { urlAlphabet }
diff --git a/frontend/node_modules/nanoid/url-alphabet/index.js b/frontend/node_modules/nanoid/url-alphabet/index.js
new file mode 100644
index 0000000..c2782e5
--- /dev/null
+++ b/frontend/node_modules/nanoid/url-alphabet/index.js
@@ -0,0 +1,3 @@
+let urlAlphabet =
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+export { urlAlphabet }
diff --git a/frontend/node_modules/nanoid/url-alphabet/package.json b/frontend/node_modules/nanoid/url-alphabet/package.json
new file mode 100644
index 0000000..9930d6a
--- /dev/null
+++ b/frontend/node_modules/nanoid/url-alphabet/package.json
@@ -0,0 +1,6 @@
+{
+ "type": "module",
+ "main": "index.cjs",
+ "module": "index.js",
+ "react-native": "index.js"
+}
\ No newline at end of file
diff --git a/frontend/node_modules/picocolors/LICENSE b/frontend/node_modules/picocolors/LICENSE
new file mode 100644
index 0000000..46c9b95
--- /dev/null
+++ b/frontend/node_modules/picocolors/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/frontend/node_modules/picocolors/README.md b/frontend/node_modules/picocolors/README.md
new file mode 100644
index 0000000..8e47aa8
--- /dev/null
+++ b/frontend/node_modules/picocolors/README.md
@@ -0,0 +1,21 @@
+# picocolors
+
+The tiniest and the fastest library for terminal output formatting with ANSI colors.
+
+```javascript
+import pc from "picocolors"
+
+console.log(
+ pc.green(`How are ${pc.italic(`you`)} doing?`)
+)
+```
+
+- **No dependencies.**
+- **14 times** smaller and **2 times** faster than chalk.
+- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist.
+- Node.js v6+ & browsers support. Support for both CJS and ESM projects.
+- TypeScript type declarations included.
+- [`NO_COLOR`](https://no-color.org/) friendly.
+
+## Docs
+Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub.
diff --git a/frontend/node_modules/picocolors/package.json b/frontend/node_modules/picocolors/package.json
new file mode 100644
index 0000000..372d4b6
--- /dev/null
+++ b/frontend/node_modules/picocolors/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "picocolors",
+ "version": "1.1.1",
+ "main": "./picocolors.js",
+ "types": "./picocolors.d.ts",
+ "browser": {
+ "./picocolors.js": "./picocolors.browser.js"
+ },
+ "sideEffects": false,
+ "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors",
+ "files": [
+ "picocolors.*",
+ "types.d.ts"
+ ],
+ "keywords": [
+ "terminal",
+ "colors",
+ "formatting",
+ "cli",
+ "console"
+ ],
+ "author": "Alexey Raspopov",
+ "repository": "alexeyraspopov/picocolors",
+ "license": "ISC"
+}
diff --git a/frontend/node_modules/picocolors/picocolors.browser.js b/frontend/node_modules/picocolors/picocolors.browser.js
new file mode 100644
index 0000000..9dcf637
--- /dev/null
+++ b/frontend/node_modules/picocolors/picocolors.browser.js
@@ -0,0 +1,4 @@
+var x=String;
+var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};
+module.exports=create();
+module.exports.createColors = create;
diff --git a/frontend/node_modules/picocolors/picocolors.d.ts b/frontend/node_modules/picocolors/picocolors.d.ts
new file mode 100644
index 0000000..94e146a
--- /dev/null
+++ b/frontend/node_modules/picocolors/picocolors.d.ts
@@ -0,0 +1,5 @@
+import { Colors } from "./types"
+
+declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors }
+
+export = picocolors
diff --git a/frontend/node_modules/picocolors/picocolors.js b/frontend/node_modules/picocolors/picocolors.js
new file mode 100644
index 0000000..e32df85
--- /dev/null
+++ b/frontend/node_modules/picocolors/picocolors.js
@@ -0,0 +1,75 @@
+let p = process || {}, argv = p.argv || [], env = p.env || {}
+let isColorSupported =
+ !(!!env.NO_COLOR || argv.includes("--no-color")) &&
+ (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI)
+
+let formatter = (open, close, replace = open) =>
+ input => {
+ let string = "" + input, index = string.indexOf(close, open.length)
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
+ }
+
+let replaceClose = (string, close, replace, index) => {
+ let result = "", cursor = 0
+ do {
+ result += string.substring(cursor, index) + replace
+ cursor = index + close.length
+ index = string.indexOf(close, cursor)
+ } while (~index)
+ return result + string.substring(cursor)
+}
+
+let createColors = (enabled = isColorSupported) => {
+ let f = enabled ? formatter : () => String
+ return {
+ isColorSupported: enabled,
+ reset: f("\x1b[0m", "\x1b[0m"),
+ bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
+ dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
+ italic: f("\x1b[3m", "\x1b[23m"),
+ underline: f("\x1b[4m", "\x1b[24m"),
+ inverse: f("\x1b[7m", "\x1b[27m"),
+ hidden: f("\x1b[8m", "\x1b[28m"),
+ strikethrough: f("\x1b[9m", "\x1b[29m"),
+
+ black: f("\x1b[30m", "\x1b[39m"),
+ red: f("\x1b[31m", "\x1b[39m"),
+ green: f("\x1b[32m", "\x1b[39m"),
+ yellow: f("\x1b[33m", "\x1b[39m"),
+ blue: f("\x1b[34m", "\x1b[39m"),
+ magenta: f("\x1b[35m", "\x1b[39m"),
+ cyan: f("\x1b[36m", "\x1b[39m"),
+ white: f("\x1b[37m", "\x1b[39m"),
+ gray: f("\x1b[90m", "\x1b[39m"),
+
+ bgBlack: f("\x1b[40m", "\x1b[49m"),
+ bgRed: f("\x1b[41m", "\x1b[49m"),
+ bgGreen: f("\x1b[42m", "\x1b[49m"),
+ bgYellow: f("\x1b[43m", "\x1b[49m"),
+ bgBlue: f("\x1b[44m", "\x1b[49m"),
+ bgMagenta: f("\x1b[45m", "\x1b[49m"),
+ bgCyan: f("\x1b[46m", "\x1b[49m"),
+ bgWhite: f("\x1b[47m", "\x1b[49m"),
+
+ blackBright: f("\x1b[90m", "\x1b[39m"),
+ redBright: f("\x1b[91m", "\x1b[39m"),
+ greenBright: f("\x1b[92m", "\x1b[39m"),
+ yellowBright: f("\x1b[93m", "\x1b[39m"),
+ blueBright: f("\x1b[94m", "\x1b[39m"),
+ magentaBright: f("\x1b[95m", "\x1b[39m"),
+ cyanBright: f("\x1b[96m", "\x1b[39m"),
+ whiteBright: f("\x1b[97m", "\x1b[39m"),
+
+ bgBlackBright: f("\x1b[100m", "\x1b[49m"),
+ bgRedBright: f("\x1b[101m", "\x1b[49m"),
+ bgGreenBright: f("\x1b[102m", "\x1b[49m"),
+ bgYellowBright: f("\x1b[103m", "\x1b[49m"),
+ bgBlueBright: f("\x1b[104m", "\x1b[49m"),
+ bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
+ bgCyanBright: f("\x1b[106m", "\x1b[49m"),
+ bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
+ }
+}
+
+module.exports = createColors()
+module.exports.createColors = createColors
diff --git a/frontend/node_modules/picocolors/types.d.ts b/frontend/node_modules/picocolors/types.d.ts
new file mode 100644
index 0000000..cd1aec4
--- /dev/null
+++ b/frontend/node_modules/picocolors/types.d.ts
@@ -0,0 +1,51 @@
+export type Formatter = (input: string | number | null | undefined) => string
+
+export interface Colors {
+ isColorSupported: boolean
+
+ reset: Formatter
+ bold: Formatter
+ dim: Formatter
+ italic: Formatter
+ underline: Formatter
+ inverse: Formatter
+ hidden: Formatter
+ strikethrough: Formatter
+
+ black: Formatter
+ red: Formatter
+ green: Formatter
+ yellow: Formatter
+ blue: Formatter
+ magenta: Formatter
+ cyan: Formatter
+ white: Formatter
+ gray: Formatter
+
+ bgBlack: Formatter
+ bgRed: Formatter
+ bgGreen: Formatter
+ bgYellow: Formatter
+ bgBlue: Formatter
+ bgMagenta: Formatter
+ bgCyan: Formatter
+ bgWhite: Formatter
+
+ blackBright: Formatter
+ redBright: Formatter
+ greenBright: Formatter
+ yellowBright: Formatter
+ blueBright: Formatter
+ magentaBright: Formatter
+ cyanBright: Formatter
+ whiteBright: Formatter
+
+ bgBlackBright: Formatter
+ bgRedBright: Formatter
+ bgGreenBright: Formatter
+ bgYellowBright: Formatter
+ bgBlueBright: Formatter
+ bgMagentaBright: Formatter
+ bgCyanBright: Formatter
+ bgWhiteBright: Formatter
+}
diff --git a/frontend/node_modules/picomatch/LICENSE b/frontend/node_modules/picomatch/LICENSE
new file mode 100644
index 0000000..3608dca
--- /dev/null
+++ b/frontend/node_modules/picomatch/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2017-present, Jon Schlinkert.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/frontend/node_modules/picomatch/README.md b/frontend/node_modules/picomatch/README.md
new file mode 100644
index 0000000..0764496
--- /dev/null
+++ b/frontend/node_modules/picomatch/README.md
@@ -0,0 +1,738 @@
+<h1 align="center">Picomatch</h1>
+
+<p align="center">
+<a href="https://npmjs.org/package/picomatch">
+<img src="https://img.shields.io/npm/v/picomatch.svg" alt="version">
+</a>
+<a href="https://github.com/micromatch/picomatch/actions?workflow=Tests">
+<img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status">
+</a>
+<a href="https://coveralls.io/github/micromatch/picomatch">
+<img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status">
+</a>
+<a href="https://npmjs.org/package/picomatch">
+<img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads">
+</a>
+</p>
+
+<br>
+<br>
+
+<p align="center">
+<strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br>
+<em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em>
+</p>
+
+<br>
+<br>
+
+## Why picomatch?
+
+* **Lightweight** - No dependencies
+* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
+* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
+* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
+* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
+* **Well tested** - Thousands of unit tests
+
+See the [library comparison](#library-comparisons) to other libraries.
+
+<br>
+<br>
+
+## Table of Contents
+
+<details><summary> Click to expand </summary>
+
+- [Install](#install)
+- [Usage](#usage)
+- [API](#api)
+ * [picomatch](#picomatch)
+ * [.test](#test)
+ * [.matchBase](#matchbase)
+ * [.isMatch](#ismatch)
+ * [.parse](#parse)
+ * [.scan](#scan)
+ * [.compileRe](#compilere)
+ * [.makeRe](#makere)
+ * [.toRegex](#toregex)
+- [Options](#options)
+ * [Picomatch options](#picomatch-options)
+ * [Scan Options](#scan-options)
+ * [Options Examples](#options-examples)
+- [Globbing features](#globbing-features)
+ * [Basic globbing](#basic-globbing)
+ * [Advanced globbing](#advanced-globbing)
+ * [Braces](#braces)
+ * [Matching special characters as literals](#matching-special-characters-as-literals)
+- [Library Comparisons](#library-comparisons)
+- [Benchmarks](#benchmarks)
+- [Philosophies](#philosophies)
+- [About](#about)
+ * [Author](#author)
+ * [License](#license)
+
+_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
+
+</details>
+
+<br>
+<br>
+
+## Install
+
+Install with [npm](https://www.npmjs.com/):
+
+```sh
+npm install --save picomatch
+```
+
+<br>
+
+## Usage
+
+The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
+
+```js
+const pm = require('picomatch');
+const isMatch = pm('*.js');
+
+console.log(isMatch('abcd')); //=> false
+console.log(isMatch('a.js')); //=> true
+console.log(isMatch('a.md')); //=> false
+console.log(isMatch('a/b.js')); //=> false
+```
+
+<br>
+
+## API
+
+### [picomatch](lib/picomatch.js#L31)
+
+Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.
+
+**Params**
+
+* `globs` **{String|Array}**: One or more glob patterns.
+* `options` **{Object=}**
+* `returns` **{Function=}**: Returns a matcher function.
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch(glob[, options]);
+
+const isMatch = picomatch('*.!(*a)');
+console.log(isMatch('a.a')); //=> false
+console.log(isMatch('a.b')); //=> true
+```
+
+**Example without node.js**
+
+For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
+
+```js
+const picomatch = require('picomatch/posix');
+// the same API, defaulting to posix paths
+const isMatch = picomatch('a/*');
+console.log(isMatch('a\\b')); //=> false
+console.log(isMatch('a/b')); //=> true
+
+// you can still configure the matcher function to accept windows paths
+const isMatch = picomatch('a/*', { options: windows });
+console.log(isMatch('a\\b')); //=> true
+console.log(isMatch('a/b')); //=> true
+```
+
+### [.test](lib/picomatch.js#L116)
+
+Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
+
+**Params**
+
+* `input` **{String}**: String to test.
+* `regex` **{RegExp}**
+* `returns` **{Object}**: Returns an object with matching info.
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch.test(input, regex[, options]);
+
+console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
+// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
+```
+
+### [.matchBase](lib/picomatch.js#L160)
+
+Match the basename of a filepath.
+
+**Params**
+
+* `input` **{String}**: String to test.
+* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
+* `returns` **{Boolean}**
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch.matchBase(input, glob[, options]);
+console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
+```
+
+### [.isMatch](lib/picomatch.js#L182)
+
+Returns true if **any** of the given glob `patterns` match the specified `string`.
+
+**Params**
+
+* **{String|Array}**: str The string to test.
+* **{String|Array}**: patterns One or more glob patterns to use for matching.
+* **{Object}**: See available [options](#options).
+* `returns` **{Boolean}**: Returns true if any patterns match `str`
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch.isMatch(string, patterns[, options]);
+
+console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
+console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
+```
+
+### [.parse](lib/picomatch.js#L198)
+
+Parse a glob pattern to create the source string for a regular expression.
+
+**Params**
+
+* `pattern` **{String}**
+* `options` **{Object}**
+* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+const result = picomatch.parse(pattern[, options]);
+```
+
+### [.scan](lib/picomatch.js#L230)
+
+Scan a glob pattern to separate the pattern into segments.
+
+**Params**
+
+* `input` **{String}**: Glob pattern to scan.
+* `options` **{Object}**
+* `returns` **{Object}**: Returns an object with
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch.scan(input[, options]);
+
+const result = picomatch.scan('!./foo/*.js');
+console.log(result);
+{ prefix: '!./',
+ input: '!./foo/*.js',
+ start: 3,
+ base: 'foo',
+ glob: '*.js',
+ isBrace: false,
+ isBracket: false,
+ isGlob: true,
+ isExtglob: false,
+ isGlobstar: false,
+ negated: true }
+```
+
+### [.compileRe](lib/picomatch.js#L244)
+
+Compile a regular expression from the `state` object returned by the
+[parse()](#parse) method.
+
+**Params**
+
+* `state` **{Object}**
+* `options` **{Object}**
+* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
+* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
+* `returns` **{RegExp}**
+
+### [.makeRe](lib/picomatch.js#L285)
+
+Create a regular expression from a parsed glob pattern.
+
+**Params**
+
+* `state` **{String}**: The object returned from the `.parse` method.
+* `options` **{Object}**
+* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
+* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
+* `returns` **{RegExp}**: Returns a regex created from the given pattern.
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+const state = picomatch.parse('*.js');
+// picomatch.compileRe(state[, options]);
+
+console.log(picomatch.compileRe(state));
+//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+```
+
+### [.toRegex](lib/picomatch.js#L320)
+
+Create a regular expression from the given regex source string.
+
+**Params**
+
+* `source` **{String}**: Regular expression source string.
+* `options` **{Object}**
+* `returns` **{RegExp}**
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+// picomatch.toRegex(source[, options]);
+
+const { output } = picomatch.parse('*.js');
+console.log(picomatch.toRegex(output));
+//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+```
+
+<br>
+
+## Options
+
+### Picomatch options
+
+The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
+
+| **Option** | **Type** | **Default value** | **Description** |
+| --- | --- | --- | --- |
+| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
+| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
+| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
+| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
+| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` |
+| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
+| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
+| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
+| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. |
+| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
+| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
+| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
+| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
+| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
+| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
+| `matchBase` | `boolean` | `false` | Alias for `basename` |
+| `maxLength` | `number` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
+| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
+| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
+| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
+| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. |
+| `noext` | `boolean` | `false` | Alias for `noextglob` |
+| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
+| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
+| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
+| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. |
+| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
+| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
+| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
+| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
+| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself |
+| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
+| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
+| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
+| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
+| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
+| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. |
+| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. |
+
+### Scan Options
+
+In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
+
+| **Option** | **Type** | **Default value** | **Description** |
+| --- | --- | --- | --- |
+| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
+| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
+
+**Example**
+
+```js
+const picomatch = require('picomatch');
+const result = picomatch.scan('!./foo/*.js', { tokens: true });
+console.log(result);
+// {
+// prefix: '!./',
+// input: '!./foo/*.js',
+// start: 3,
+// base: 'foo',
+// glob: '*.js',
+// isBrace: false,
+// isBracket: false,
+// isGlob: true,
+// isExtglob: false,
+// isGlobstar: false,
+// negated: true,
+// maxDepth: 2,
+// tokens: [
+// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
+// { value: 'foo', depth: 1, isGlob: false },
+// { value: '*.js', depth: 1, isGlob: true }
+// ],
+// slashes: [ 2, 6 ],
+// parts: [ 'foo', '*.js' ]
+// }
+```
+
+<br>
+
+### Options Examples
+
+#### options.expandRange
+
+**Type**: `function`
+
+**Default**: `undefined`
+
+Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
+
+**Example**
+
+The following example shows how to create a glob that matches a folder
+
+```js
+const fill = require('fill-range');
+const regex = pm.makeRe('foo/{01..25}/bar', {
+ expandRange(a, b) {
+ return `(${fill(a, b, { toRegex: true })})`;
+ }
+});
+
+console.log(regex);
+//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
+
+console.log(regex.test('foo/00/bar')) // false
+console.log(regex.test('foo/01/bar')) // true
+console.log(regex.test('foo/10/bar')) // true
+console.log(regex.test('foo/22/bar')) // true
+console.log(regex.test('foo/25/bar')) // true
+console.log(regex.test('foo/26/bar')) // false
+```
+
+#### options.format
+
+**Type**: `function`
+
+**Default**: `undefined`
+
+Custom function for formatting strings before they're matched.
+
+**Example**
+
+```js
+// strip leading './' from strings
+const format = str => str.replace(/^\.\//, '');
+const isMatch = picomatch('foo/*.js', { format });
+console.log(isMatch('./foo/bar.js')); //=> true
+```
+
+#### options.onMatch
+
+```js
+const onMatch = ({ glob, regex, input, output }) => {
+ console.log({ glob, regex, input, output });
+};
+
+const isMatch = picomatch('*', { onMatch });
+isMatch('foo');
+isMatch('bar');
+isMatch('baz');
+```
+
+#### options.onIgnore
+
+```js
+const onIgnore = ({ glob, regex, input, output }) => {
+ console.log({ glob, regex, input, output });
+};
+
+const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
+isMatch('foo');
+isMatch('bar');
+isMatch('baz');
+```
+
+#### options.onResult
+
+```js
+const onResult = ({ glob, regex, input, output }) => {
+ console.log({ glob, regex, input, output });
+};
+
+const isMatch = picomatch('*', { onResult, ignore: 'f*' });
+isMatch('foo');
+isMatch('bar');
+isMatch('baz');
+```
+
+<br>
+<br>
+
+## Globbing features
+
+* [Basic globbing](#basic-globbing) (Wildcard matching)
+* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
+
+### Basic globbing
+
+| **Character** | **Description** |
+| --- | --- |
+| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
+| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
+| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
+| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
+
+#### Matching behavior vs. Bash
+
+Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
+
+* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
+* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
+
+<br>
+
+### Advanced globbing
+
+* [extglobs](#extglobs)
+* [POSIX brackets](#posix-brackets)
+* [Braces](#brace-expansion)
+
+#### Extglobs
+
+| **Pattern** | **Description** |
+| --- | --- |
+| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
+| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
+| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
+| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
+| `!(pattern)` | Match _anything but_ `pattern` |
+
+**Examples**
+
+```js
+const pm = require('picomatch');
+
+// *(pattern) matches ZERO or more of "pattern"
+console.log(pm.isMatch('a', 'a*(z)')); // true
+console.log(pm.isMatch('az', 'a*(z)')); // true
+console.log(pm.isMatch('azzz', 'a*(z)')); // true
+
+// +(pattern) matches ONE or more of "pattern"
+console.log(pm.isMatch('a', 'a+(z)')); // false
+console.log(pm.isMatch('az', 'a+(z)')); // true
+console.log(pm.isMatch('azzz', 'a+(z)')); // true
+
+// supports multiple extglobs
+console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
+
+// supports nested extglobs
+console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
+```
+
+#### POSIX brackets
+
+POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
+
+**Enable POSIX bracket support**
+
+```js
+console.log(pm.makeRe('[[:word:]]+', { posix: true }));
+//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
+```
+
+**Supported POSIX classes**
+
+The following named POSIX bracket expressions are supported:
+
+* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
+* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
+* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
+* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
+* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
+* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
+* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
+* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
+* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
+* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
+* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
+* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
+* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
+* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
+
+See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
+
+### Braces
+
+Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces.
+
+### Matching special characters as literals
+
+If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
+
+**Special Characters**
+
+Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
+
+To match any of the following characters as literals: `$^*+?()[]
+
+Examples:
+
+```js
+console.log(pm.makeRe('foo/bar \\(1\\)'));
+console.log(pm.makeRe('foo/bar \\(1\\)'));
+```
+
+<br>
+<br>
+
+## Library Comparisons
+
+The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
+
+| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
+| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
+| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
+| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
+| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
+| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
+| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
+| File system operations | - | - | - | - | - | - | - |
+
+<br>
+<br>
+
+## Benchmarks
+
+Performance comparison of picomatch and minimatch.
+
+_(Pay special attention to the last three benchmarks. Minimatch freezes on long ranges.)_
+
+```
+# .makeRe star (*)
+ picomatch x 4,449,159 ops/sec ±0.24% (97 runs sampled)
+ minimatch x 632,772 ops/sec ±0.14% (98 runs sampled)
+
+# .makeRe star; dot=true (*)
+ picomatch x 3,500,079 ops/sec ±0.26% (99 runs sampled)
+ minimatch x 564,916 ops/sec ±0.23% (96 runs sampled)
+
+# .makeRe globstar (**)
+ picomatch x 3,261,000 ops/sec ±0.27% (98 runs sampled)
+ minimatch x 1,664,766 ops/sec ±0.20% (100 runs sampled)
+
+# .makeRe globstars (**/**/**)
+ picomatch x 3,284,469 ops/sec ±0.18% (97 runs sampled)
+ minimatch x 1,435,880 ops/sec ±0.34% (95 runs sampled)
+
+# .makeRe with leading star (*.txt)
+ picomatch x 3,100,197 ops/sec ±0.35% (99 runs sampled)
+ minimatch x 428,347 ops/sec ±0.42% (94 runs sampled)
+
+# .makeRe - basic braces ({a,b,c}*.txt)
+ picomatch x 443,578 ops/sec ±1.33% (89 runs sampled)
+ minimatch x 107,143 ops/sec ±0.35% (94 runs sampled)
+
+# .makeRe - short ranges ({a..z}*.txt)
+ picomatch x 415,484 ops/sec ±0.76% (96 runs sampled)
+ minimatch x 14,299 ops/sec ±0.26% (96 runs sampled)
+
+# .makeRe - medium ranges ({1..100000}*.txt)
+ picomatch x 395,020 ops/sec ±0.87% (89 runs sampled)
+ minimatch x 2 ops/sec ±4.59% (10 runs sampled)
+
+# .makeRe - long ranges ({1..10000000}*.txt)
+ picomatch x 400,036 ops/sec ±0.83% (90 runs sampled)
+ minimatch (FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory)
+```
+
+<br>
+<br>
+
+## Philosophies
+
+The goal of this library is to be blazing fast, without compromising on accuracy.
+
+**Accuracy**
+
+The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
+
+Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
+
+**Performance**
+
+Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
+
+<br>
+<br>
+
+## About
+
+<details>
+<summary><strong>Contributing</strong></summary>
+
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
+
+Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
+
+</details>
+
+<details>
+<summary><strong>Running Tests</strong></summary>
+
+Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
+
+```sh
+npm install && npm test
+```
+
+</details>
+
+<details>
+<summary><strong>Building docs</strong></summary>
+
+_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
+
+To generate the readme, run the following command:
+
+```sh
+npm install -g verbose/verb#dev verb-generate-readme && verb
+```
+
+</details>
+
+### Author
+
+**Jon Schlinkert**
+
+* [GitHub Profile](https://github.com/jonschlinkert)
+* [Twitter Profile](https://twitter.com/jonschlinkert)
+* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
+
+### License
+
+Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
+Released under the [MIT License](LICENSE).
diff --git a/frontend/node_modules/picomatch/index.js b/frontend/node_modules/picomatch/index.js
new file mode 100644
index 0000000..a753b1d
--- /dev/null
+++ b/frontend/node_modules/picomatch/index.js
@@ -0,0 +1,17 @@
+'use strict';
+
+const pico = require('./lib/picomatch');
+const utils = require('./lib/utils');
+
+function picomatch(glob, options, returnState = false) {
+ // default to os.platform()
+ if (options && (options.windows === null || options.windows === undefined)) {
+ // don't mutate the original options object
+ options = { ...options, windows: utils.isWindows() };
+ }
+
+ return pico(glob, options, returnState);
+}
+
+Object.assign(picomatch, pico);
+module.exports = picomatch;
diff --git a/frontend/node_modules/picomatch/lib/constants.js b/frontend/node_modules/picomatch/lib/constants.js
new file mode 100644
index 0000000..3f7ef7e
--- /dev/null
+++ b/frontend/node_modules/picomatch/lib/constants.js
@@ -0,0 +1,180 @@
+'use strict';
+
+const WIN_SLASH = '\\\\/';
+const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
+
+/**
+ * Posix glob regex
+ */
+
+const DOT_LITERAL = '\\.';
+const PLUS_LITERAL = '\\+';
+const QMARK_LITERAL = '\\?';
+const SLASH_LITERAL = '\\/';
+const ONE_CHAR = '(?=.)';
+const QMARK = '[^/]';
+const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
+const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
+const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
+const NO_DOT = `(?!${DOT_LITERAL})`;
+const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
+const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
+const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
+const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
+const STAR = `${QMARK}*?`;
+const SEP = '/';
+
+const POSIX_CHARS = {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ QMARK_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ QMARK,
+ END_ANCHOR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR,
+ SEP
+};
+
+/**
+ * Windows glob regex
+ */
+
+const WINDOWS_CHARS = {
+ ...POSIX_CHARS,
+
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
+ QMARK: WIN_NO_SLASH,
+ STAR: `${WIN_NO_SLASH}*?`,
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
+ NO_DOT: `(?!${DOT_LITERAL})`,
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
+ SEP: '\\'
+};
+
+/**
+ * POSIX Bracket Regex
+ */
+
+const POSIX_REGEX_SOURCE = {
+ 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'
+};
+
+module.exports = {
+ MAX_LENGTH: 1024 * 64,
+ POSIX_REGEX_SOURCE,
+
+ // regular expressions
+ 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,
+
+ // Replace globs with equivalent patterns to reduce parsing time.
+ REPLACEMENTS: {
+ __proto__: null,
+ '***': '*',
+ '**/**': '**',
+ '**/**/**': '**'
+ },
+
+ // Digits
+ CHAR_0: 48, /* 0 */
+ CHAR_9: 57, /* 9 */
+
+ // Alphabet chars.
+ CHAR_UPPERCASE_A: 65, /* A */
+ CHAR_LOWERCASE_A: 97, /* a */
+ CHAR_UPPERCASE_Z: 90, /* Z */
+ CHAR_LOWERCASE_Z: 122, /* z */
+
+ CHAR_LEFT_PARENTHESES: 40, /* ( */
+ CHAR_RIGHT_PARENTHESES: 41, /* ) */
+
+ CHAR_ASTERISK: 42, /* * */
+
+ // Non-alphabetic chars.
+ CHAR_AMPERSAND: 38, /* & */
+ CHAR_AT: 64, /* @ */
+ CHAR_BACKWARD_SLASH: 92, /* \ */
+ CHAR_CARRIAGE_RETURN: 13, /* \r */
+ 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, /* \f */
+ 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, /* \n */
+ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
+ 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, /* \t */
+ CHAR_UNDERSCORE: 95, /* _ */
+ CHAR_VERTICAL_LINE: 124, /* | */
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
+
+ /**
+ * Create EXTGLOB_CHARS
+ */
+
+ extglobChars(chars) {
+ return {
+ '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
+ '?': { type: 'qmark', open: '(?:', close: ')?' },
+ '+': { type: 'plus', open: '(?:', close: ')+' },
+ '*': { type: 'star', open: '(?:', close: ')*' },
+ '@': { type: 'at', open: '(?:', close: ')' }
+ };
+ },
+
+ /**
+ * Create GLOB_CHARS
+ */
+
+ globChars(win32) {
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
+ }
+};
diff --git a/frontend/node_modules/picomatch/lib/parse.js b/frontend/node_modules/picomatch/lib/parse.js
new file mode 100644
index 0000000..8fd8ff4
--- /dev/null
+++ b/frontend/node_modules/picomatch/lib/parse.js
@@ -0,0 +1,1085 @@
+'use strict';
+
+const constants = require('./constants');
+const utils = require('./utils');
+
+/**
+ * Constants
+ */
+
+const {
+ MAX_LENGTH,
+ POSIX_REGEX_SOURCE,
+ REGEX_NON_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_BACKREF,
+ REPLACEMENTS
+} = constants;
+
+/**
+ * Helpers
+ */
+
+const expandRange = (args, options) => {
+ if (typeof options.expandRange === 'function') {
+ return options.expandRange(...args, options);
+ }
+
+ args.sort();
+ const value = `[${args.join('-')}]`;
+
+ try {
+ /* eslint-disable-next-line no-new */
+ new RegExp(value);
+ } catch (ex) {
+ return args.map(v => utils.escapeRegex(v)).join('..');
+ }
+
+ return value;
+};
+
+/**
+ * Create the message for a syntax error
+ */
+
+const syntaxError = (type, char) => {
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
+};
+
+/**
+ * Parse the given input string.
+ * @param {String} input
+ * @param {Object} options
+ * @return {Object}
+ */
+
+const parse = (input, options) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected a string');
+ }
+
+ input = REPLACEMENTS[input] || input;
+
+ const opts = { ...options };
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+
+ let len = input.length;
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ }
+
+ const bos = { type: 'bos', value: '', output: opts.prepend || '' };
+ const tokens = [bos];
+
+ const capture = opts.capture ? '' : '?:';
+
+ // create constants based on platform, for windows or posix
+ const PLATFORM_CHARS = constants.globChars(opts.windows);
+ const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
+
+ const {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR
+ } = PLATFORM_CHARS;
+
+ const globstar = opts => {
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
+
+ const nodot = opts.dot ? '' : NO_DOT;
+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
+ let star = opts.bash === true ? globstar(opts) : STAR;
+
+ if (opts.capture) {
+ star = `(${star})`;
+ }
+
+ // minimatch options support
+ if (typeof opts.noext === 'boolean') {
+ opts.noextglob = opts.noext;
+ }
+
+ const state = {
+ input,
+ index: -1,
+ start: 0,
+ dot: opts.dot === true,
+ consumed: '',
+ output: '',
+ prefix: '',
+ backtrack: false,
+ negated: false,
+ brackets: 0,
+ braces: 0,
+ parens: 0,
+ quotes: 0,
+ globstar: false,
+ tokens
+ };
+
+ input = utils.removePrefix(input, state);
+ len = input.length;
+
+ const extglobs = [];
+ const braces = [];
+ const stack = [];
+ let prev = bos;
+ let value;
+
+ /**
+ * Tokenizing helpers
+ */
+
+ const eos = () => state.index === len - 1;
+ const peek = state.peek = (n = 1) => input[state.index + n];
+ const advance = state.advance = () => input[++state.index] || '';
+ const remaining = () => input.slice(state.index + 1);
+ const consume = (value = '', num = 0) => {
+ state.consumed += value;
+ state.index += num;
+ };
+
+ const append = token => {
+ state.output += token.output != null ? token.output : token.value;
+ consume(token.value);
+ };
+
+ const negate = () => {
+ let count = 1;
+
+ while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
+ advance();
+ state.start++;
+ count++;
+ }
+
+ if (count % 2 === 0) {
+ return false;
+ }
+
+ state.negated = true;
+ state.start++;
+ return true;
+ };
+
+ const increment = type => {
+ state[type]++;
+ stack.push(type);
+ };
+
+ const decrement = type => {
+ state[type]--;
+ stack.pop();
+ };
+
+ /**
+ * Push tokens onto the tokens array. This helper speeds up
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
+ * and 2) helping us avoid creating extra tokens when consecutive
+ * characters are plain text. This improves performance and simplifies
+ * lookbehinds.
+ */
+
+ const push = tok => {
+ if (prev.type === 'globstar') {
+ const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
+ const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
+
+ if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
+ state.output = state.output.slice(0, -prev.output.length);
+ prev.type = 'star';
+ prev.value = '*';
+ prev.output = star;
+ state.output += prev.output;
+ }
+ }
+
+ if (extglobs.length && tok.type !== 'paren') {
+ extglobs[extglobs.length - 1].inner += tok.value;
+ }
+
+ if (tok.value || tok.output) append(tok);
+ if (prev && prev.type === 'text' && tok.type === 'text') {
+ prev.output = (prev.output || prev.value) + tok.value;
+ prev.value += tok.value;
+ return;
+ }
+
+ tok.prev = prev;
+ tokens.push(tok);
+ prev = tok;
+ };
+
+ const extglobOpen = (type, value) => {
+ const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
+
+ token.prev = prev;
+ token.parens = state.parens;
+ token.output = state.output;
+ const output = (opts.capture ? '(' : '') + token.open;
+
+ increment('parens');
+ push({ type, value, output: state.output ? '' : ONE_CHAR });
+ push({ type: 'paren', extglob: true, value: advance(), output });
+ extglobs.push(token);
+ };
+
+ const extglobClose = token => {
+ let output = token.close + (opts.capture ? ')' : '');
+ let rest;
+
+ if (token.type === 'negate') {
+ let extglobStar = star;
+
+ if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
+ extglobStar = globstar(opts);
+ }
+
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
+ output = token.close = `)$))${extglobStar}`;
+ }
+
+ if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
+ // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
+ // In this case, we need to parse the string and use it in the output of the original pattern.
+ // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
+ //
+ // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
+ const expression = parse(rest, { ...options, fastpaths: false }).output;
+
+ output = token.close = `)${expression})${extglobStar})`;
+ }
+
+ if (token.prev.type === 'bos') {
+ state.negatedExtglob = true;
+ }
+ }
+
+ push({ type: 'paren', extglob: true, value, output });
+ decrement('parens');
+ };
+
+ /**
+ * Fast paths
+ */
+
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
+ let backslashes = false;
+
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
+ if (first === '\\') {
+ backslashes = true;
+ return m;
+ }
+
+ if (first === '?') {
+ if (esc) {
+ return esc + first + (rest ? QMARK.repeat(rest.length) : '');
+ }
+ if (index === 0) {
+ return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
+ }
+ return QMARK.repeat(chars.length);
+ }
+
+ if (first === '.') {
+ return DOT_LITERAL.repeat(chars.length);
+ }
+
+ if (first === '*') {
+ if (esc) {
+ return esc + first + (rest ? star : '');
+ }
+ return star;
+ }
+ return esc ? m : `\\${m}`;
+ });
+
+ if (backslashes === true) {
+ if (opts.unescape === true) {
+ output = output.replace(/\\/g, '');
+ } else {
+ output = output.replace(/\\+/g, m => {
+ return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
+ });
+ }
+ }
+
+ if (output === input && opts.contains === true) {
+ state.output = input;
+ return state;
+ }
+
+ state.output = utils.wrapOutput(output, state, options);
+ return state;
+ }
+
+ /**
+ * Tokenize input until we reach end-of-string
+ */
+
+ while (!eos()) {
+ value = advance();
+
+ if (value === '\u0000') {
+ continue;
+ }
+
+ /**
+ * Escaped characters
+ */
+
+ if (value === '\\') {
+ const next = peek();
+
+ if (next === '/' && opts.bash !== true) {
+ continue;
+ }
+
+ if (next === '.' || next === ';') {
+ continue;
+ }
+
+ if (!next) {
+ value += '\\';
+ push({ type: 'text', value });
+ continue;
+ }
+
+ // collapse slashes to reduce potential for exploits
+ const match = /^\\+/.exec(remaining());
+ let slashes = 0;
+
+ if (match && match[0].length > 2) {
+ slashes = match[0].length;
+ state.index += slashes;
+ if (slashes % 2 !== 0) {
+ value += '\\';
+ }
+ }
+
+ if (opts.unescape === true) {
+ value = advance();
+ } else {
+ value += advance();
+ }
+
+ if (state.brackets === 0) {
+ push({ type: 'text', value });
+ continue;
+ }
+ }
+
+ /**
+ * If we're inside a regex character class, continue
+ * until we reach the closing bracket.
+ */
+
+ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
+ if (opts.posix !== false && value === ':') {
+ const inner = prev.value.slice(1);
+ if (inner.includes('[')) {
+ prev.posix = true;
+
+ if (inner.includes(':')) {
+ const idx = prev.value.lastIndexOf('[');
+ const pre = prev.value.slice(0, idx);
+ const rest = prev.value.slice(idx + 2);
+ const posix = POSIX_REGEX_SOURCE[rest];
+ if (posix) {
+ prev.value = pre + posix;
+ state.backtrack = true;
+ advance();
+
+ if (!bos.output && tokens.indexOf(prev) === 1) {
+ bos.output = ONE_CHAR;
+ }
+ continue;
+ }
+ }
+ }
+ }
+
+ if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
+ value = `\\${value}`;
+ }
+
+ if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
+ value = `\\${value}`;
+ }
+
+ if (opts.posix === true && value === '!' && prev.value === '[') {
+ value = '^';
+ }
+
+ prev.value += value;
+ append({ value });
+ continue;
+ }
+
+ /**
+ * If we're inside a quoted string, continue
+ * until we reach the closing double quote.
+ */
+
+ if (state.quotes === 1 && value !== '"') {
+ value = utils.escapeRegex(value);
+ prev.value += value;
+ append({ value });
+ continue;
+ }
+
+ /**
+ * Double quotes
+ */
+
+ if (value === '"') {
+ state.quotes = state.quotes === 1 ? 0 : 1;
+ if (opts.keepQuotes === true) {
+ push({ type: 'text', value });
+ }
+ continue;
+ }
+
+ /**
+ * Parentheses
+ */
+
+ if (value === '(') {
+ increment('parens');
+ push({ type: 'paren', value });
+ continue;
+ }
+
+ if (value === ')') {
+ if (state.parens === 0 && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '('));
+ }
+
+ const extglob = extglobs[extglobs.length - 1];
+ if (extglob && state.parens === extglob.parens + 1) {
+ extglobClose(extglobs.pop());
+ continue;
+ }
+
+ push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
+ decrement('parens');
+ continue;
+ }
+
+ /**
+ * Square brackets
+ */
+
+ if (value === '[') {
+ if (opts.nobracket === true || !remaining().includes(']')) {
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('closing', ']'));
+ }
+
+ value = `\\${value}`;
+ } else {
+ increment('brackets');
+ }
+
+ push({ type: 'bracket', value });
+ continue;
+ }
+
+ if (value === ']') {
+ if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
+ push({ type: 'text', value, output: `\\${value}` });
+ continue;
+ }
+
+ if (state.brackets === 0) {
+ if (opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '['));
+ }
+
+ push({ type: 'text', value, output: `\\${value}` });
+ continue;
+ }
+
+ decrement('brackets');
+
+ const prevValue = prev.value.slice(1);
+ if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
+ value = `/${value}`;
+ }
+
+ prev.value += value;
+ append({ value });
+
+ // when literal brackets are explicitly disabled
+ // assume we should match with a regex character class
+ if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
+ continue;
+ }
+
+ const escaped = utils.escapeRegex(prev.value);
+ state.output = state.output.slice(0, -prev.value.length);
+
+ // when literal brackets are explicitly enabled
+ // assume we should escape the brackets to match literal characters
+ if (opts.literalBrackets === true) {
+ state.output += escaped;
+ prev.value = escaped;
+ continue;
+ }
+
+ // when the user specifies nothing, try to match both
+ prev.value = `(${capture}${escaped}|${prev.value})`;
+ state.output += prev.value;
+ continue;
+ }
+
+ /**
+ * Braces
+ */
+
+ if (value === '{' && opts.nobrace !== true) {
+ increment('braces');
+
+ const open = {
+ type: 'brace',
+ value,
+ output: '(',
+ outputIndex: state.output.length,
+ tokensIndex: state.tokens.length
+ };
+
+ braces.push(open);
+ push(open);
+ continue;
+ }
+
+ if (value === '}') {
+ const brace = braces[braces.length - 1];
+
+ if (opts.nobrace === true || !brace) {
+ push({ type: 'text', value, output: value });
+ continue;
+ }
+
+ let output = ')';
+
+ if (brace.dots === true) {
+ const arr = tokens.slice();
+ const range = [];
+
+ for (let i = arr.length - 1; i >= 0; i--) {
+ tokens.pop();
+ if (arr[i].type === 'brace') {
+ break;
+ }
+ if (arr[i].type !== 'dots') {
+ range.unshift(arr[i].value);
+ }
+ }
+
+ output = expandRange(range, opts);
+ state.backtrack = true;
+ }
+
+ if (brace.comma !== true && brace.dots !== true) {
+ const out = state.output.slice(0, brace.outputIndex);
+ const toks = state.tokens.slice(brace.tokensIndex);
+ brace.value = brace.output = '\\{';
+ value = output = '\\}';
+ state.output = out;
+ for (const t of toks) {
+ state.output += (t.output || t.value);
+ }
+ }
+
+ push({ type: 'brace', value, output });
+ decrement('braces');
+ braces.pop();
+ continue;
+ }
+
+ /**
+ * Pipes
+ */
+
+ if (value === '|') {
+ if (extglobs.length > 0) {
+ extglobs[extglobs.length - 1].conditions++;
+ }
+ push({ type: 'text', value });
+ continue;
+ }
+
+ /**
+ * Commas
+ */
+
+ if (value === ',') {
+ let output = value;
+
+ const brace = braces[braces.length - 1];
+ if (brace && stack[stack.length - 1] === 'braces') {
+ brace.comma = true;
+ output = '|';
+ }
+
+ push({ type: 'comma', value, output });
+ continue;
+ }
+
+ /**
+ * Slashes
+ */
+
+ if (value === '/') {
+ // if the beginning of the glob is "./", advance the start
+ // to the current index, and don't add the "./" characters
+ // to the state. This greatly simplifies lookbehinds when
+ // checking for BOS characters like "!" and "." (not "./")
+ if (prev.type === 'dot' && state.index === state.start + 1) {
+ state.start = state.index + 1;
+ state.consumed = '';
+ state.output = '';
+ tokens.pop();
+ prev = bos; // reset "prev" to the first token
+ continue;
+ }
+
+ push({ type: 'slash', value, output: SLASH_LITERAL });
+ continue;
+ }
+
+ /**
+ * Dots
+ */
+
+ if (value === '.') {
+ if (state.braces > 0 && prev.type === 'dot') {
+ if (prev.value === '.') prev.output = DOT_LITERAL;
+ const brace = braces[braces.length - 1];
+ prev.type = 'dots';
+ prev.output += value;
+ prev.value += value;
+ brace.dots = true;
+ continue;
+ }
+
+ if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
+ push({ type: 'text', value, output: DOT_LITERAL });
+ continue;
+ }
+
+ push({ type: 'dot', value, output: DOT_LITERAL });
+ continue;
+ }
+
+ /**
+ * Question marks
+ */
+
+ if (value === '?') {
+ const isGroup = prev && prev.value === '(';
+ if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('qmark', value);
+ continue;
+ }
+
+ if (prev && prev.type === 'paren') {
+ const next = peek();
+ let output = value;
+
+ if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
+ output = `\\${value}`;
+ }
+
+ push({ type: 'text', value, output });
+ continue;
+ }
+
+ if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
+ push({ type: 'qmark', value, output: QMARK_NO_DOT });
+ continue;
+ }
+
+ push({ type: 'qmark', value, output: QMARK });
+ continue;
+ }
+
+ /**
+ * Exclamation
+ */
+
+ if (value === '!') {
+ if (opts.noextglob !== true && peek() === '(') {
+ if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
+ extglobOpen('negate', value);
+ continue;
+ }
+ }
+
+ if (opts.nonegate !== true && state.index === 0) {
+ negate();
+ continue;
+ }
+ }
+
+ /**
+ * Plus
+ */
+
+ if (value === '+') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('plus', value);
+ continue;
+ }
+
+ if ((prev && prev.value === '(') || opts.regex === false) {
+ push({ type: 'plus', value, output: PLUS_LITERAL });
+ continue;
+ }
+
+ if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
+ push({ type: 'plus', value });
+ continue;
+ }
+
+ push({ type: 'plus', value: PLUS_LITERAL });
+ continue;
+ }
+
+ /**
+ * Plain text
+ */
+
+ if (value === '@') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ push({ type: 'at', extglob: true, value, output: '' });
+ continue;
+ }
+
+ push({ type: 'text', value });
+ continue;
+ }
+
+ /**
+ * Plain text
+ */
+
+ if (value !== '*') {
+ if (value === '$' || value === '^') {
+ value = `\\${value}`;
+ }
+
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
+ if (match) {
+ value += match[0];
+ state.index += match[0].length;
+ }
+
+ push({ type: 'text', value });
+ continue;
+ }
+
+ /**
+ * Stars
+ */
+
+ if (prev && (prev.type === 'globstar' || prev.star === true)) {
+ prev.type = 'star';
+ prev.star = true;
+ prev.value += value;
+ prev.output = star;
+ state.backtrack = true;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
+
+ let rest = remaining();
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
+ extglobOpen('star', value);
+ continue;
+ }
+
+ if (prev.type === 'star') {
+ if (opts.noglobstar === true) {
+ consume(value);
+ continue;
+ }
+
+ const prior = prev.prev;
+ const before = prior.prev;
+ const isStart = prior.type === 'slash' || prior.type === 'bos';
+ const afterStar = before && (before.type === 'star' || before.type === 'globstar');
+
+ if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
+ push({ type: 'star', value, output: '' });
+ continue;
+ }
+
+ const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
+ const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
+ if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
+ push({ type: 'star', value, output: '' });
+ continue;
+ }
+
+ // strip consecutive `/**/`
+ while (rest.slice(0, 3) === '/**') {
+ const after = input[state.index + 4];
+ if (after && after !== '/') {
+ break;
+ }
+ rest = rest.slice(3);
+ consume('/**', 3);
+ }
+
+ if (prior.type === 'bos' && eos()) {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = globstar(opts);
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
+
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
+
+ prev.type = 'globstar';
+ prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
+ prev.value += value;
+ state.globstar = true;
+ state.output += prior.output + prev.output;
+ consume(value);
+ continue;
+ }
+
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
+ const end = rest[1] !== void 0 ? '|$' : '';
+
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
+
+ prev.type = 'globstar';
+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
+ prev.value += value;
+
+ state.output += prior.output + prev.output;
+ state.globstar = true;
+
+ consume(value + advance());
+
+ push({ type: 'slash', value: '/', output: '' });
+ continue;
+ }
+
+ if (prior.type === 'bos' && rest[0] === '/') {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value + advance());
+ push({ type: 'slash', value: '/', output: '' });
+ continue;
+ }
+
+ // remove single star from output
+ state.output = state.output.slice(0, -prev.output.length);
+
+ // reset previous token to globstar
+ prev.type = 'globstar';
+ prev.output = globstar(opts);
+ prev.value += value;
+
+ // reset output with globstar
+ state.output += prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
+
+ const token = { type: 'star', value, output: star };
+
+ if (opts.bash === true) {
+ token.output = '.*?';
+ if (prev.type === 'bos' || prev.type === 'slash') {
+ token.output = nodot + token.output;
+ }
+ push(token);
+ continue;
+ }
+
+ if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
+ token.output = value;
+ push(token);
+ continue;
+ }
+
+ if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
+ if (prev.type === 'dot') {
+ state.output += NO_DOT_SLASH;
+ prev.output += NO_DOT_SLASH;
+
+ } else if (opts.dot === true) {
+ state.output += NO_DOTS_SLASH;
+ prev.output += NO_DOTS_SLASH;
+
+ } else {
+ state.output += nodot;
+ prev.output += nodot;
+ }
+
+ if (peek() !== '*') {
+ state.output += ONE_CHAR;
+ prev.output += ONE_CHAR;
+ }
+ }
+
+ push(token);
+ }
+
+ while (state.brackets > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
+ state.output = utils.escapeLast(state.output, '[');
+ decrement('brackets');
+ }
+
+ while (state.parens > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
+ state.output = utils.escapeLast(state.output, '(');
+ decrement('parens');
+ }
+
+ while (state.braces > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
+ state.output = utils.escapeLast(state.output, '{');
+ decrement('braces');
+ }
+
+ if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
+ push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
+ }
+
+ // rebuild the output if we had to backtrack at any point
+ if (state.backtrack === true) {
+ state.output = '';
+
+ for (const token of state.tokens) {
+ state.output += token.output != null ? token.output : token.value;
+
+ if (token.suffix) {
+ state.output += token.suffix;
+ }
+ }
+ }
+
+ return state;
+};
+
+/**
+ * Fast paths for creating regular expressions for common glob patterns.
+ * This can significantly speed up processing and has very little downside
+ * impact when none of the fast paths match.
+ */
+
+parse.fastpaths = (input, options) => {
+ const opts = { ...options };
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+ const len = input.length;
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ }
+
+ input = REPLACEMENTS[input] || input;
+
+ // create constants based on platform, for windows or posix
+ const {
+ DOT_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOTS_SLASH,
+ STAR,
+ START_ANCHOR
+ } = constants.globChars(opts.windows);
+
+ const nodot = opts.dot ? NO_DOTS : NO_DOT;
+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
+ const capture = opts.capture ? '' : '?:';
+ const state = { negated: false, prefix: '' };
+ let star = opts.bash === true ? '.*?' : STAR;
+
+ if (opts.capture) {
+ star = `(${star})`;
+ }
+
+ const globstar = opts => {
+ if (opts.noglobstar === true) return star;
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
+
+ const create = str => {
+ switch (str) {
+ case '*':
+ return `${nodot}${ONE_CHAR}${star}`;
+
+ case '.*':
+ return `${DOT_LITERAL}${ONE_CHAR}${star}`;
+
+ case '*.*':
+ return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
+
+ case '*/*':
+ return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
+
+ case '**':
+ return nodot + globstar(opts);
+
+ case '**/*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
+
+ case '**/*.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
+
+ case '**/.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
+
+ default: {
+ const match = /^(.*?)\.(\w+)$/.exec(str);
+ if (!match) return;
+
+ const source = create(match[1]);
+ if (!source) return;
+
+ return source + DOT_LITERAL + match[2];
+ }
+ }
+ };
+
+ const output = utils.removePrefix(input, state);
+ let source = create(output);
+
+ if (source && opts.strictSlashes !== true) {
+ source += `${SLASH_LITERAL}?`;
+ }
+
+ return source;
+};
+
+module.exports = parse;
diff --git a/frontend/node_modules/picomatch/lib/picomatch.js b/frontend/node_modules/picomatch/lib/picomatch.js
new file mode 100644
index 0000000..d0ebd9f
--- /dev/null
+++ b/frontend/node_modules/picomatch/lib/picomatch.js
@@ -0,0 +1,341 @@
+'use strict';
+
+const scan = require('./scan');
+const parse = require('./parse');
+const utils = require('./utils');
+const constants = require('./constants');
+const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
+
+/**
+ * Creates a matcher function from one or more glob patterns. The
+ * returned function takes a string to match as its first argument,
+ * and returns true if the string is a match. The returned matcher
+ * function also takes a boolean as the second argument that, when true,
+ * returns an object with additional information.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch(glob[, options]);
+ *
+ * const isMatch = picomatch('*.!(*a)');
+ * console.log(isMatch('a.a')); //=> false
+ * console.log(isMatch('a.b')); //=> true
+ * ```
+ * @name picomatch
+ * @param {String|Array} `globs` One or more glob patterns.
+ * @param {Object=} `options`
+ * @return {Function=} Returns a matcher function.
+ * @api public
+ */
+
+const picomatch = (glob, options, returnState = false) => {
+ if (Array.isArray(glob)) {
+ const fns = glob.map(input => picomatch(input, options, returnState));
+ const arrayMatcher = str => {
+ for (const isMatch of fns) {
+ const state = isMatch(str);
+ if (state) return state;
+ }
+ return false;
+ };
+ return arrayMatcher;
+ }
+
+ const isState = isObject(glob) && glob.tokens && glob.input;
+
+ if (glob === '' || (typeof glob !== 'string' && !isState)) {
+ throw new TypeError('Expected pattern to be a non-empty string');
+ }
+
+ const opts = options || {};
+ const posix = opts.windows;
+ const regex = isState
+ ? picomatch.compileRe(glob, options)
+ : picomatch.makeRe(glob, options, false, true);
+
+ const state = regex.state;
+ delete regex.state;
+
+ let isIgnored = () => false;
+ if (opts.ignore) {
+ const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
+ isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
+ }
+
+ const matcher = (input, returnObject = false) => {
+ const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
+ const result = { glob, state, regex, posix, input, output, match, isMatch };
+
+ if (typeof opts.onResult === 'function') {
+ opts.onResult(result);
+ }
+
+ if (isMatch === false) {
+ result.isMatch = false;
+ return returnObject ? result : false;
+ }
+
+ if (isIgnored(input)) {
+ if (typeof opts.onIgnore === 'function') {
+ opts.onIgnore(result);
+ }
+ result.isMatch = false;
+ return returnObject ? result : false;
+ }
+
+ if (typeof opts.onMatch === 'function') {
+ opts.onMatch(result);
+ }
+ return returnObject ? result : true;
+ };
+
+ if (returnState) {
+ matcher.state = state;
+ }
+
+ return matcher;
+};
+
+/**
+ * Test `input` with the given `regex`. This is used by the main
+ * `picomatch()` function to test the input string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.test(input, regex[, options]);
+ *
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp} `regex`
+ * @return {Object} Returns an object with matching info.
+ * @api public
+ */
+
+picomatch.test = (input, regex, options, { glob, posix } = {}) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected input to be a string');
+ }
+
+ if (input === '') {
+ return { isMatch: false, output: '' };
+ }
+
+ const opts = options || {};
+ const format = opts.format || (posix ? utils.toPosixSlashes : null);
+ let match = input === glob;
+ let output = (match && format) ? format(input) : input;
+
+ if (match === false) {
+ output = format ? format(input) : input;
+ match = output === glob;
+ }
+
+ if (match === false || opts.capture === true) {
+ if (opts.matchBase === true || opts.basename === true) {
+ match = picomatch.matchBase(input, regex, options, posix);
+ } else {
+ match = regex.exec(output);
+ }
+ }
+
+ return { isMatch: Boolean(match), match, output };
+};
+
+/**
+ * Match the basename of a filepath.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.matchBase(input, glob[, options]);
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
+ * @return {Boolean}
+ * @api public
+ */
+
+picomatch.matchBase = (input, glob, options) => {
+ const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
+ return regex.test(utils.basename(input));
+};
+
+/**
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.isMatch(string, patterns[, options]);
+ *
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
+ * ```
+ * @param {String|Array} str The string to test.
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
+ * @param {Object} [options] See available [options](#options).
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
+
+picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
+
+/**
+ * Parse a glob pattern to create the source string for a regular
+ * expression.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const result = picomatch.parse(pattern[, options]);
+ * ```
+ * @param {String} `pattern`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
+ * @api public
+ */
+
+picomatch.parse = (pattern, options) => {
+ if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
+ return parse(pattern, { ...options, fastpaths: false });
+};
+
+/**
+ * Scan a glob pattern to separate the pattern into segments.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.scan(input[, options]);
+ *
+ * const result = picomatch.scan('!./foo/*.js');
+ * console.log(result);
+ * { prefix: '!./',
+ * input: '!./foo/*.js',
+ * start: 3,
+ * base: 'foo',
+ * glob: '*.js',
+ * isBrace: false,
+ * isBracket: false,
+ * isGlob: true,
+ * isExtglob: false,
+ * isGlobstar: false,
+ * negated: true }
+ * ```
+ * @param {String} `input` Glob pattern to scan.
+ * @param {Object} `options`
+ * @return {Object} Returns an object with
+ * @api public
+ */
+
+picomatch.scan = (input, options) => scan(input, options);
+
+/**
+ * Compile a regular expression from the `state` object returned by the
+ * [parse()](#parse) method.
+ *
+ * @param {Object} `state`
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
+ * @return {RegExp}
+ * @api public
+ */
+
+picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
+ if (returnOutput === true) {
+ return state.output;
+ }
+
+ const opts = options || {};
+ const prepend = opts.contains ? '' : '^';
+ const append = opts.contains ? '' : '$';
+
+ let source = `${prepend}(?:${state.output})${append}`;
+ if (state && state.negated === true) {
+ source = `^(?!${source}).*$`;
+ }
+
+ const regex = picomatch.toRegex(source, options);
+ if (returnState === true) {
+ regex.state = state;
+ }
+
+ return regex;
+};
+
+/**
+ * Create a regular expression from a parsed glob pattern.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const state = picomatch.parse('*.js');
+ * // picomatch.compileRe(state[, options]);
+ *
+ * console.log(picomatch.compileRe(state));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `state` The object returned from the `.parse` method.
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
+ * @return {RegExp} Returns a regex created from the given pattern.
+ * @api public
+ */
+
+picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
+ if (!input || typeof input !== 'string') {
+ throw new TypeError('Expected a non-empty string');
+ }
+
+ let parsed = { negated: false, fastpaths: true };
+
+ if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
+ parsed.output = parse.fastpaths(input, options);
+ }
+
+ if (!parsed.output) {
+ parsed = parse(input, options);
+ }
+
+ return picomatch.compileRe(parsed, options, returnOutput, returnState);
+};
+
+/**
+ * Create a regular expression from the given regex source string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.toRegex(source[, options]);
+ *
+ * const { output } = picomatch.parse('*.js');
+ * console.log(picomatch.toRegex(output));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `source` Regular expression source string.
+ * @param {Object} `options`
+ * @return {RegExp}
+ * @api public
+ */
+
+picomatch.toRegex = (source, options) => {
+ try {
+ const opts = options || {};
+ return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
+ } catch (err) {
+ if (options && options.debug === true) throw err;
+ return /$^/;
+ }
+};
+
+/**
+ * Picomatch constants.
+ * @return {Object}
+ */
+
+picomatch.constants = constants;
+
+/**
+ * Expose "picomatch"
+ */
+
+module.exports = picomatch;
diff --git a/frontend/node_modules/picomatch/lib/scan.js b/frontend/node_modules/picomatch/lib/scan.js
new file mode 100644
index 0000000..e59cd7a
--- /dev/null
+++ b/frontend/node_modules/picomatch/lib/scan.js
@@ -0,0 +1,391 @@
+'use strict';
+
+const utils = require('./utils');
+const {
+ CHAR_ASTERISK, /* * */
+ CHAR_AT, /* @ */
+ CHAR_BACKWARD_SLASH, /* \ */
+ CHAR_COMMA, /* , */
+ CHAR_DOT, /* . */
+ CHAR_EXCLAMATION_MARK, /* ! */
+ CHAR_FORWARD_SLASH, /* / */
+ CHAR_LEFT_CURLY_BRACE, /* { */
+ CHAR_LEFT_PARENTHESES, /* ( */
+ CHAR_LEFT_SQUARE_BRACKET, /* [ */
+ CHAR_PLUS, /* + */
+ CHAR_QUESTION_MARK, /* ? */
+ CHAR_RIGHT_CURLY_BRACE, /* } */
+ CHAR_RIGHT_PARENTHESES, /* ) */
+ CHAR_RIGHT_SQUARE_BRACKET /* ] */
+} = require('./constants');
+
+const isPathSeparator = code => {
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
+};
+
+const depth = token => {
+ if (token.isPrefix !== true) {
+ token.depth = token.isGlobstar ? Infinity : 1;
+ }
+};
+
+/**
+ * Quickly scans a glob pattern and returns an object with a handful of
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
+ *
+ * ```js
+ * const pm = require('picomatch');
+ * console.log(pm.scan('foo/bar/*.js'));
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
+ * ```
+ * @param {String} `str`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with tokens and regex source string.
+ * @api public
+ */
+
+const scan = (input, options) => {
+ const opts = options || {};
+
+ const length = input.length - 1;
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
+ const slashes = [];
+ const tokens = [];
+ const parts = [];
+
+ let str = input;
+ let index = -1;
+ let start = 0;
+ let lastIndex = 0;
+ let isBrace = false;
+ let isBracket = false;
+ let isGlob = false;
+ let isExtglob = false;
+ let isGlobstar = false;
+ let braceEscaped = false;
+ let backslashes = false;
+ let negated = false;
+ let negatedExtglob = false;
+ let finished = false;
+ let braces = 0;
+ let prev;
+ let code;
+ let token = { value: '', depth: 0, isGlob: false };
+
+ const eos = () => index >= length;
+ const peek = () => str.charCodeAt(index + 1);
+ const advance = () => {
+ prev = code;
+ return str.charCodeAt(++index);
+ };
+
+ while (index < length) {
+ code = advance();
+ let next;
+
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
+
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braceEscaped = true;
+ }
+ continue;
+ }
+
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
+
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
+
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
+ continue;
+ }
+
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (braceEscaped !== true && code === CHAR_COMMA) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
+ braces--;
+
+ if (braces === 0) {
+ braceEscaped = false;
+ isBrace = token.isBrace = true;
+ finished = true;
+ break;
+ }
+ }
+ }
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (code === CHAR_FORWARD_SLASH) {
+ slashes.push(index);
+ tokens.push(token);
+ token = { value: '', depth: 0, isGlob: false };
+
+ if (finished === true) continue;
+ if (prev === CHAR_DOT && index === (start + 1)) {
+ start += 2;
+ continue;
+ }
+
+ lastIndex = index + 1;
+ continue;
+ }
+
+ if (opts.noext !== true) {
+ const isExtglobChar = code === CHAR_PLUS
+ || code === CHAR_AT
+ || code === CHAR_ASTERISK
+ || code === CHAR_QUESTION_MARK
+ || code === CHAR_EXCLAMATION_MARK;
+
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ isExtglob = token.isExtglob = true;
+ finished = true;
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
+ negatedExtglob = true;
+ }
+
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
+
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
+ continue;
+ }
+ break;
+ }
+ }
+
+ if (code === CHAR_ASTERISK) {
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
+
+ if (code === CHAR_QUESTION_MARK) {
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
+
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
+ while (eos() !== true && (next = advance())) {
+ if (next === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
+
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
+ isBracket = token.isBracket = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
+ negated = token.negated = true;
+ start++;
+ continue;
+ }
+
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_LEFT_PARENTHESES) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
+
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ finished = true;
+ break;
+ }
+ }
+ continue;
+ }
+ break;
+ }
+
+ if (isGlob === true) {
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+ }
+
+ if (opts.noext === true) {
+ isExtglob = false;
+ isGlob = false;
+ }
+
+ let base = str;
+ let prefix = '';
+ let glob = '';
+
+ if (start > 0) {
+ prefix = str.slice(0, start);
+ str = str.slice(start);
+ lastIndex -= start;
+ }
+
+ if (base && isGlob === true && lastIndex > 0) {
+ base = str.slice(0, lastIndex);
+ glob = str.slice(lastIndex);
+ } else if (isGlob === true) {
+ base = '';
+ glob = str;
+ } else {
+ base = str;
+ }
+
+ if (base && base !== '' && base !== '/' && base !== str) {
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
+ base = base.slice(0, -1);
+ }
+ }
+
+ if (opts.unescape === true) {
+ if (glob) glob = utils.removeBackslashes(glob);
+
+ if (base && backslashes === true) {
+ base = utils.removeBackslashes(base);
+ }
+ }
+
+ const state = {
+ prefix,
+ input,
+ start,
+ base,
+ glob,
+ isBrace,
+ isBracket,
+ isGlob,
+ isExtglob,
+ isGlobstar,
+ negated,
+ negatedExtglob
+ };
+
+ if (opts.tokens === true) {
+ state.maxDepth = 0;
+ if (!isPathSeparator(code)) {
+ tokens.push(token);
+ }
+ state.tokens = tokens;
+ }
+
+ if (opts.parts === true || opts.tokens === true) {
+ let prevIndex;
+
+ for (let idx = 0; idx < slashes.length; idx++) {
+ const n = prevIndex ? prevIndex + 1 : start;
+ const i = slashes[idx];
+ const value = input.slice(n, i);
+ if (opts.tokens) {
+ if (idx === 0 && start !== 0) {
+ tokens[idx].isPrefix = true;
+ tokens[idx].value = prefix;
+ } else {
+ tokens[idx].value = value;
+ }
+ depth(tokens[idx]);
+ state.maxDepth += tokens[idx].depth;
+ }
+ if (idx !== 0 || value !== '') {
+ parts.push(value);
+ }
+ prevIndex = i;
+ }
+
+ if (prevIndex && prevIndex + 1 < input.length) {
+ const value = input.slice(prevIndex + 1);
+ parts.push(value);
+
+ if (opts.tokens) {
+ tokens[tokens.length - 1].value = value;
+ depth(tokens[tokens.length - 1]);
+ state.maxDepth += tokens[tokens.length - 1].depth;
+ }
+ }
+
+ state.slashes = slashes;
+ state.parts = parts;
+ }
+
+ return state;
+};
+
+module.exports = scan;
diff --git a/frontend/node_modules/picomatch/lib/utils.js b/frontend/node_modules/picomatch/lib/utils.js
new file mode 100644
index 0000000..9c97cae
--- /dev/null
+++ b/frontend/node_modules/picomatch/lib/utils.js
@@ -0,0 +1,72 @@
+/*global navigator*/
+'use strict';
+
+const {
+ REGEX_BACKSLASH,
+ REGEX_REMOVE_BACKSLASH,
+ REGEX_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_GLOBAL
+} = require('./constants');
+
+exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
+exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
+exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
+exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
+
+exports.isWindows = () => {
+ if (typeof navigator !== 'undefined' && navigator.platform) {
+ const platform = navigator.platform.toLowerCase();
+ return platform === 'win32' || platform === 'windows';
+ }
+
+ if (typeof process !== 'undefined' && process.platform) {
+ return process.platform === 'win32';
+ }
+
+ return false;
+};
+
+exports.removeBackslashes = str => {
+ return str.replace(REGEX_REMOVE_BACKSLASH, match => {
+ return match === '\\' ? '' : match;
+ });
+};
+
+exports.escapeLast = (input, char, lastIdx) => {
+ const idx = input.lastIndexOf(char, lastIdx);
+ if (idx === -1) return input;
+ if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
+};
+
+exports.removePrefix = (input, state = {}) => {
+ let output = input;
+ if (output.startsWith('./')) {
+ output = output.slice(2);
+ state.prefix = './';
+ }
+ return output;
+};
+
+exports.wrapOutput = (input, state = {}, options = {}) => {
+ const prepend = options.contains ? '' : '^';
+ const append = options.contains ? '' : '$';
+
+ let output = `${prepend}(?:${input})${append}`;
+ if (state.negated === true) {
+ output = `(?:^(?!${output}).*$)`;
+ }
+ return output;
+};
+
+exports.basename = (path, { windows } = {}) => {
+ const segs = path.split(windows ? /[\\/]/ : '/');
+ const last = segs[segs.length - 1];
+
+ if (last === '') {
+ return segs[segs.length - 2];
+ }
+
+ return last;
+};
diff --git a/frontend/node_modules/picomatch/package.json b/frontend/node_modules/picomatch/package.json
new file mode 100644
index 0000000..372e27e
--- /dev/null
+++ b/frontend/node_modules/picomatch/package.json
@@ -0,0 +1,83 @@
+{
+ "name": "picomatch",
+ "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.",
+ "version": "4.0.3",
+ "homepage": "https://github.com/micromatch/picomatch",
+ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
+ "funding": "https://github.com/sponsors/jonschlinkert",
+ "repository": "micromatch/picomatch",
+ "bugs": {
+ "url": "https://github.com/micromatch/picomatch/issues"
+ },
+ "license": "MIT",
+ "files": [
+ "index.js",
+ "posix.js",
+ "lib"
+ ],
+ "sideEffects": false,
+ "main": "index.js",
+ "engines": {
+ "node": ">=12"
+ },
+ "scripts": {
+ "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .",
+ "mocha": "mocha --reporter dot",
+ "test": "npm run lint && npm run mocha",
+ "test:ci": "npm run test:cover",
+ "test:cover": "nyc npm run mocha"
+ },
+ "devDependencies": {
+ "eslint": "^8.57.0",
+ "fill-range": "^7.0.1",
+ "gulp-format-md": "^2.0.0",
+ "mocha": "^10.4.0",
+ "nyc": "^15.1.0",
+ "time-require": "github:jonschlinkert/time-require"
+ },
+ "keywords": [
+ "glob",
+ "match",
+ "picomatch"
+ ],
+ "nyc": {
+ "reporter": [
+ "html",
+ "lcov",
+ "text-summary"
+ ]
+ },
+ "verb": {
+ "toc": {
+ "render": true,
+ "method": "preWrite",
+ "maxdepth": 3
+ },
+ "layout": "empty",
+ "tasks": [
+ "readme"
+ ],
+ "plugins": [
+ "gulp-format-md"
+ ],
+ "lint": {
+ "reflinks": true
+ },
+ "related": {
+ "list": [
+ "braces",
+ "micromatch"
+ ]
+ },
+ "reflinks": [
+ "braces",
+ "expand-brackets",
+ "extglob",
+ "fill-range",
+ "micromatch",
+ "minimatch",
+ "nanomatch",
+ "picomatch"
+ ]
+ }
+}
diff --git a/frontend/node_modules/picomatch/posix.js b/frontend/node_modules/picomatch/posix.js
new file mode 100644
index 0000000..d2f2bc5
--- /dev/null
+++ b/frontend/node_modules/picomatch/posix.js
@@ -0,0 +1,3 @@
+'use strict';
+
+module.exports = require('./lib/picomatch');
diff --git a/frontend/node_modules/postcss/LICENSE b/frontend/node_modules/postcss/LICENSE
new file mode 100644
index 0000000..da057b4
--- /dev/null
+++ b/frontend/node_modules/postcss/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright 2013 Andrey Sitnik <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/frontend/node_modules/postcss/README.md b/frontend/node_modules/postcss/README.md
new file mode 100644
index 0000000..05fed07
--- /dev/null
+++ b/frontend/node_modules/postcss/README.md
@@ -0,0 +1,29 @@
+# PostCSS
+
+<img align="right" width="95" height="95"
+ alt="Philosopher’s stone, logo of PostCSS"
+ src="https://postcss.org/logo.svg">
+
+PostCSS is a tool for transforming styles with JS plugins.
+These plugins can lint your CSS, support variables and mixins,
+transpile future CSS syntax, inline images, and more.
+
+PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
+and JetBrains. The [Autoprefixer] and [Stylelint] PostCSS plugins are some of the most popular CSS tools.
+
+---
+
+<img src="https://cdn.evilmartians.com/badges/logo-no-label.svg" alt="" width="22" height="16" />  Built by
+ <b><a href="https://evilmartians.com/devtools?utm_source=postcss&utm_campaign=devtools-button&utm_medium=github">Evil Martians</a></b>, go-to agency for <b>developer tools</b>.
+
+---
+
+[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
+[Evil Martians]: https://evilmartians.com/?utm_source=postcss
+[Autoprefixer]: https://github.com/postcss/autoprefixer
+[Stylelint]: https://stylelint.io/
+[plugins]: https://github.com/postcss/postcss#plugins
+
+
+## Docs
+Read full docs **[here](https://postcss.org/)**.
diff --git a/frontend/node_modules/postcss/lib/at-rule.d.ts b/frontend/node_modules/postcss/lib/at-rule.d.ts
new file mode 100644
index 0000000..89fb505
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/at-rule.d.ts
@@ -0,0 +1,140 @@
+import Container, {
+ ContainerProps,
+ ContainerWithChildren
+} from './container.js'
+
+declare namespace AtRule {
+ export interface AtRuleRaws extends Record<string, unknown> {
+ /**
+ * The space symbols after the last child of the node to the end of the node.
+ */
+ after?: string
+
+ /**
+ * The space between the at-rule name and its parameters.
+ */
+ afterName?: string
+
+ /**
+ * The space symbols before the node. It also stores `*`
+ * and `_` symbols before the declaration (IE hack).
+ */
+ before?: string
+
+ /**
+ * The symbols between the last parameter and `{` for rules.
+ */
+ between?: string
+
+ /**
+ * The rule’s selector with comments.
+ */
+ params?: {
+ raw: string
+ value: string
+ }
+
+ /**
+ * Contains `true` if the last child has an (optional) semicolon.
+ */
+ semicolon?: boolean
+ }
+
+ export interface AtRuleProps extends ContainerProps {
+ /** Name of the at-rule. */
+ name: string
+ /** Parameters following the name of the at-rule. */
+ params?: number | string
+ /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
+ raws?: AtRuleRaws
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { AtRule_ as default }
+}
+
+/**
+ * Represents an at-rule.
+ *
+ * ```js
+ * Once (root, { AtRule }) {
+ * let media = new AtRule({ name: 'media', params: 'print' })
+ * media.append(…)
+ * root.append(media)
+ * }
+ * ```
+ *
+ * If it’s followed in the CSS by a `{}` block, this node will have
+ * a nodes property representing its children.
+ *
+ * ```js
+ * const root = postcss.parse('@charset "UTF-8"; @media print {}')
+ *
+ * const charset = root.first
+ * charset.type //=> 'atrule'
+ * charset.nodes //=> undefined
+ *
+ * const media = root.last
+ * media.nodes //=> []
+ * ```
+ */
+declare class AtRule_ extends Container {
+ /**
+ * An array containing the layer’s children.
+ *
+ * ```js
+ * const root = postcss.parse('@layer example { a { color: black } }')
+ * const layer = root.first
+ * layer.nodes.length //=> 1
+ * layer.nodes[0].selector //=> 'a'
+ * ```
+ *
+ * Can be `undefinded` if the at-rule has no body.
+ *
+ * ```js
+ * const root = postcss.parse('@layer a, b, c;')
+ * const layer = root.first
+ * layer.nodes //=> undefined
+ * ```
+ */
+ nodes: Container['nodes'] | undefined
+ parent: ContainerWithChildren | undefined
+
+ raws: AtRule.AtRuleRaws
+ type: 'atrule'
+ /**
+ * The at-rule’s name immediately follows the `@`.
+ *
+ * ```js
+ * const root = postcss.parse('@media print {}')
+ * const media = root.first
+ * media.name //=> 'media'
+ * ```
+ */
+ get name(): string
+ set name(value: string)
+
+ /**
+ * The at-rule’s parameters, the values that follow the at-rule’s name
+ * but precede any `{}` block.
+ *
+ * ```js
+ * const root = postcss.parse('@media print, screen {}')
+ * const media = root.first
+ * media.params //=> 'print, screen'
+ * ```
+ */
+ get params(): string
+
+ set params(value: string)
+
+ constructor(defaults?: AtRule.AtRuleProps)
+ assign(overrides: AtRule.AtRuleProps | object): this
+ clone(overrides?: Partial<AtRule.AtRuleProps>): this
+ cloneAfter(overrides?: Partial<AtRule.AtRuleProps>): this
+ cloneBefore(overrides?: Partial<AtRule.AtRuleProps>): this
+}
+
+declare class AtRule extends AtRule_ {}
+
+export = AtRule
diff --git a/frontend/node_modules/postcss/lib/at-rule.js b/frontend/node_modules/postcss/lib/at-rule.js
new file mode 100644
index 0000000..9486447
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/at-rule.js
@@ -0,0 +1,25 @@
+'use strict'
+
+let Container = require('./container')
+
+class AtRule extends Container {
+ constructor(defaults) {
+ super(defaults)
+ this.type = 'atrule'
+ }
+
+ append(...children) {
+ if (!this.proxyOf.nodes) this.nodes = []
+ return super.append(...children)
+ }
+
+ prepend(...children) {
+ if (!this.proxyOf.nodes) this.nodes = []
+ return super.prepend(...children)
+ }
+}
+
+module.exports = AtRule
+AtRule.default = AtRule
+
+Container.registerAtRule(AtRule)
diff --git a/frontend/node_modules/postcss/lib/comment.d.ts b/frontend/node_modules/postcss/lib/comment.d.ts
new file mode 100644
index 0000000..6f1f66f
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/comment.d.ts
@@ -0,0 +1,68 @@
+import Container from './container.js'
+import Node, { NodeProps } from './node.js'
+
+declare namespace Comment {
+ export interface CommentRaws extends Record<string, unknown> {
+ /**
+ * The space symbols before the node.
+ */
+ before?: string
+
+ /**
+ * The space symbols between `/*` and the comment’s text.
+ */
+ left?: string
+
+ /**
+ * The space symbols between the comment’s text.
+ */
+ right?: string
+ }
+
+ export interface CommentProps extends NodeProps {
+ /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
+ raws?: CommentRaws
+ /** Content of the comment. */
+ text: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Comment_ as default }
+}
+
+/**
+ * It represents a class that handles
+ * [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
+ *
+ * ```js
+ * Once (root, { Comment }) {
+ * const note = new Comment({ text: 'Note: …' })
+ * root.append(note)
+ * }
+ * ```
+ *
+ * Remember that CSS comments inside selectors, at-rule parameters,
+ * or declaration values will be stored in the `raws` properties
+ * explained above.
+ */
+declare class Comment_ extends Node {
+ parent: Container | undefined
+ raws: Comment.CommentRaws
+ type: 'comment'
+ /**
+ * The comment's text.
+ */
+ get text(): string
+
+ set text(value: string)
+
+ constructor(defaults?: Comment.CommentProps)
+ assign(overrides: Comment.CommentProps | object): this
+ clone(overrides?: Partial<Comment.CommentProps>): this
+ cloneAfter(overrides?: Partial<Comment.CommentProps>): this
+ cloneBefore(overrides?: Partial<Comment.CommentProps>): this
+}
+
+declare class Comment extends Comment_ {}
+
+export = Comment
diff --git a/frontend/node_modules/postcss/lib/comment.js b/frontend/node_modules/postcss/lib/comment.js
new file mode 100644
index 0000000..c566506
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/comment.js
@@ -0,0 +1,13 @@
+'use strict'
+
+let Node = require('./node')
+
+class Comment extends Node {
+ constructor(defaults) {
+ super(defaults)
+ this.type = 'comment'
+ }
+}
+
+module.exports = Comment
+Comment.default = Comment
diff --git a/frontend/node_modules/postcss/lib/container.d.ts b/frontend/node_modules/postcss/lib/container.d.ts
new file mode 100644
index 0000000..c2b310b
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/container.d.ts
@@ -0,0 +1,483 @@
+import AtRule from './at-rule.js'
+import Comment from './comment.js'
+import Declaration from './declaration.js'
+import Node, { ChildNode, ChildProps, NodeProps } from './node.js'
+import { Root } from './postcss.js'
+import Rule from './rule.js'
+
+declare namespace Container {
+ export type ContainerWithChildren<Child extends Node = ChildNode> = {
+ nodes: Child[]
+ } & (
+ | AtRule
+ | Root
+ | Rule
+ )
+
+ export interface ValueOptions {
+ /**
+ * String that’s used to narrow down values and speed up the regexp search.
+ */
+ fast?: string
+
+ /**
+ * An array of property names.
+ */
+ props?: readonly string[]
+ }
+
+ export interface ContainerProps extends NodeProps {
+ nodes?: readonly (ChildProps | Node)[]
+ }
+
+ /**
+ * All types that can be passed into container methods to create or add a new
+ * child node.
+ */
+ export type NewChild =
+ | ChildProps
+ | Node
+ | readonly ChildProps[]
+ | readonly Node[]
+ | readonly string[]
+ | string
+ | undefined
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Container_ as default }
+}
+
+/**
+ * The `Root`, `AtRule`, and `Rule` container nodes
+ * inherit some common methods to help work with their children.
+ *
+ * Note that all containers can store any content. If you write a rule inside
+ * a rule, PostCSS will parse it.
+ */
+declare abstract class Container_<Child extends Node = ChildNode> extends Node {
+ /**
+ * An array containing the container’s children.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black }')
+ * root.nodes.length //=> 1
+ * root.nodes[0].selector //=> 'a'
+ * root.nodes[0].nodes[0].prop //=> 'color'
+ * ```
+ */
+ nodes: Child[] | undefined
+
+ /**
+ * The container’s first child.
+ *
+ * ```js
+ * rule.first === rules.nodes[0]
+ * ```
+ */
+ get first(): Child | undefined
+
+ /**
+ * The container’s last child.
+ *
+ * ```js
+ * rule.last === rule.nodes[rule.nodes.length - 1]
+ * ```
+ */
+ get last(): Child | undefined
+ /**
+ * Inserts new nodes to the end of the container.
+ *
+ * ```js
+ * const decl1 = new Declaration({ prop: 'color', value: 'black' })
+ * const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
+ * rule.append(decl1, decl2)
+ *
+ * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
+ * root.append({ selector: 'a' }) // rule
+ * rule.append({ prop: 'color', value: 'black' }) // declaration
+ * rule.append({ text: 'Comment' }) // comment
+ *
+ * root.append('a {}')
+ * root.first.append('color: black; z-index: 1')
+ * ```
+ *
+ * @param nodes New nodes.
+ * @return This node for methods chain.
+ */
+ append(...nodes: Container.NewChild[]): this
+ assign(overrides: Container.ContainerProps | object): this
+ clone(overrides?: Partial<Container.ContainerProps>): this
+
+ cloneAfter(overrides?: Partial<Container.ContainerProps>): this
+
+ cloneBefore(overrides?: Partial<Container.ContainerProps>): this
+ /**
+ * Iterates through the container’s immediate children,
+ * calling `callback` for each child.
+ *
+ * Returning `false` in the callback will break iteration.
+ *
+ * This method only iterates through the container’s immediate children.
+ * If you need to recursively iterate through all the container’s descendant
+ * nodes, use `Container#walk`.
+ *
+ * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
+ * if you are mutating the array of child nodes during iteration.
+ * PostCSS will adjust the current index to match the mutations.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black; z-index: 1 }')
+ * const rule = root.first
+ *
+ * for (const decl of rule.nodes) {
+ * decl.cloneBefore({ prop: '-webkit-' + decl.prop })
+ * // Cycle will be infinite, because cloneBefore moves the current node
+ * // to the next index
+ * }
+ *
+ * rule.each(decl => {
+ * decl.cloneBefore({ prop: '-webkit-' + decl.prop })
+ * // Will be executed only for color and z-index
+ * })
+ * ```
+ *
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+ each(
+ callback: (node: Child, index: number) => false | void
+ ): false | undefined
+
+ /**
+ * Returns `true` if callback returns `true`
+ * for all of the container’s children.
+ *
+ * ```js
+ * const noPrefixes = rule.every(i => i.prop[0] !== '-')
+ * ```
+ *
+ * @param condition Iterator returns true or false.
+ * @return Is every child pass condition.
+ */
+ every(
+ condition: (node: Child, index: number, nodes: Child[]) => boolean
+ ): boolean
+ /**
+ * Returns a `child`’s index within the `Container#nodes` array.
+ *
+ * ```js
+ * rule.index( rule.nodes[2] ) //=> 2
+ * ```
+ *
+ * @param child Child of the current container.
+ * @return Child index.
+ */
+ index(child: Child | number): number
+
+ /**
+ * Insert new node after old node within the container.
+ *
+ * @param oldNode Child or child’s index.
+ * @param newNode New node.
+ * @return This node for methods chain.
+ */
+ insertAfter(oldNode: Child | number, newNode: Container.NewChild): this
+
+ /**
+ * Traverses the container’s descendant nodes, calling callback
+ * for each comment node.
+ *
+ * Like `Container#each`, this method is safe
+ * to use if you are mutating arrays during iteration.
+ *
+ * ```js
+ * root.walkComments(comment => {
+ * comment.remove()
+ * })
+ * ```
+ *
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+
+ /**
+ * Insert new node before old node within the container.
+ *
+ * ```js
+ * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
+ * ```
+ *
+ * @param oldNode Child or child’s index.
+ * @param newNode New node.
+ * @return This node for methods chain.
+ */
+ insertBefore(oldNode: Child | number, newNode: Container.NewChild): this
+ /**
+ * Inserts new nodes to the start of the container.
+ *
+ * ```js
+ * const decl1 = new Declaration({ prop: 'color', value: 'black' })
+ * const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
+ * rule.prepend(decl1, decl2)
+ *
+ * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
+ * root.append({ selector: 'a' }) // rule
+ * rule.append({ prop: 'color', value: 'black' }) // declaration
+ * rule.append({ text: 'Comment' }) // comment
+ *
+ * root.append('a {}')
+ * root.first.append('color: black; z-index: 1')
+ * ```
+ *
+ * @param nodes New nodes.
+ * @return This node for methods chain.
+ */
+ prepend(...nodes: Container.NewChild[]): this
+
+ /**
+ * Add child to the end of the node.
+ *
+ * ```js
+ * rule.push(new Declaration({ prop: 'color', value: 'black' }))
+ * ```
+ *
+ * @param child New node.
+ * @return This node for methods chain.
+ */
+ push(child: Child): this
+
+ /**
+ * Removes all children from the container
+ * and cleans their parent properties.
+ *
+ * ```js
+ * rule.removeAll()
+ * rule.nodes.length //=> 0
+ * ```
+ *
+ * @return This node for methods chain.
+ */
+ removeAll(): this
+
+ /**
+ * Removes node from the container and cleans the parent properties
+ * from the node and its children.
+ *
+ * ```js
+ * rule.nodes.length //=> 5
+ * rule.removeChild(decl)
+ * rule.nodes.length //=> 4
+ * decl.parent //=> undefined
+ * ```
+ *
+ * @param child Child or child’s index.
+ * @return This node for methods chain.
+ */
+ removeChild(child: Child | number): this
+
+ replaceValues(
+ pattern: RegExp | string,
+ replaced: { (substring: string, ...args: any[]): string } | string
+ ): this
+ /**
+ * Passes all declaration values within the container that match pattern
+ * through callback, replacing those values with the returned result
+ * of callback.
+ *
+ * This method is useful if you are using a custom unit or function
+ * and need to iterate through all values.
+ *
+ * ```js
+ * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
+ * return 15 * parseInt(string) + 'px'
+ * })
+ * ```
+ *
+ * @param pattern Replace pattern.
+ * @param {object} options Options to speed up the search.
+ * @param replaced String to replace pattern or callback
+ * that returns a new value. The callback
+ * will receive the same arguments
+ * as those passed to a function parameter
+ * of `String#replace`.
+ * @return This node for methods chain.
+ */
+ replaceValues(
+ pattern: RegExp | string,
+ options: Container.ValueOptions,
+ replaced: { (substring: string, ...args: any[]): string } | string
+ ): this
+
+ /**
+ * Returns `true` if callback returns `true` for (at least) one
+ * of the container’s children.
+ *
+ * ```js
+ * const hasPrefix = rule.some(i => i.prop[0] === '-')
+ * ```
+ *
+ * @param condition Iterator returns true or false.
+ * @return Is some child pass condition.
+ */
+ some(
+ condition: (node: Child, index: number, nodes: Child[]) => boolean
+ ): boolean
+
+ /**
+ * Traverses the container’s descendant nodes, calling callback
+ * for each node.
+ *
+ * Like container.each(), this method is safe to use
+ * if you are mutating arrays during iteration.
+ *
+ * If you only need to iterate through the container’s immediate children,
+ * use `Container#each`.
+ *
+ * ```js
+ * root.walk(node => {
+ * // Traverses all descendant nodes.
+ * })
+ * ```
+ *
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+ walk(
+ callback: (node: ChildNode, index: number) => false | void
+ ): false | undefined
+
+ /**
+ * Traverses the container’s descendant nodes, calling callback
+ * for each at-rule node.
+ *
+ * If you pass a filter, iteration will only happen over at-rules
+ * that have matching names.
+ *
+ * Like `Container#each`, this method is safe
+ * to use if you are mutating arrays during iteration.
+ *
+ * ```js
+ * root.walkAtRules(rule => {
+ * if (isOld(rule.name)) rule.remove()
+ * })
+ *
+ * let first = false
+ * root.walkAtRules('charset', rule => {
+ * if (!first) {
+ * first = true
+ * } else {
+ * rule.remove()
+ * }
+ * })
+ * ```
+ *
+ * @param name String or regular expression to filter at-rules by name.
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+ walkAtRules(
+ nameFilter: RegExp | string,
+ callback: (atRule: AtRule, index: number) => false | void
+ ): false | undefined
+ walkAtRules(
+ callback: (atRule: AtRule, index: number) => false | void
+ ): false | undefined
+
+ walkComments(
+ callback: (comment: Comment, indexed: number) => false | void
+ ): false | undefined
+ walkComments(
+ callback: (comment: Comment, indexed: number) => false | void
+ ): false | undefined
+
+ /**
+ * Traverses the container’s descendant nodes, calling callback
+ * for each declaration node.
+ *
+ * If you pass a filter, iteration will only happen over declarations
+ * with matching properties.
+ *
+ * ```js
+ * root.walkDecls(decl => {
+ * checkPropertySupport(decl.prop)
+ * })
+ *
+ * root.walkDecls('border-radius', decl => {
+ * decl.remove()
+ * })
+ *
+ * root.walkDecls(/^background/, decl => {
+ * decl.value = takeFirstColorFromGradient(decl.value)
+ * })
+ * ```
+ *
+ * Like `Container#each`, this method is safe
+ * to use if you are mutating arrays during iteration.
+ *
+ * @param prop String or regular expression to filter declarations
+ * by property name.
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+ walkDecls(
+ propFilter: RegExp | string,
+ callback: (decl: Declaration, index: number) => false | void
+ ): false | undefined
+ walkDecls(
+ callback: (decl: Declaration, index: number) => false | void
+ ): false | undefined
+ /**
+ * Traverses the container’s descendant nodes, calling callback
+ * for each rule node.
+ *
+ * If you pass a filter, iteration will only happen over rules
+ * with matching selectors.
+ *
+ * Like `Container#each`, this method is safe
+ * to use if you are mutating arrays during iteration.
+ *
+ * ```js
+ * const selectors = []
+ * root.walkRules(rule => {
+ * selectors.push(rule.selector)
+ * })
+ * console.log(`Your CSS uses ${ selectors.length } selectors`)
+ * ```
+ *
+ * @param selector String or regular expression to filter rules by selector.
+ * @param callback Iterator receives each node and index.
+ * @return Returns `false` if iteration was broke.
+ */
+ walkRules(
+ selectorFilter: RegExp | string,
+ callback: (rule: Rule, index: number) => false | void
+ ): false | undefined
+ walkRules(
+ callback: (rule: Rule, index: number) => false | void
+ ): false | undefined
+ /**
+ * An internal method that converts a {@link NewChild} into a list of actual
+ * child nodes that can then be added to this container.
+ *
+ * This ensures that the nodes' parent is set to this container, that they use
+ * the correct prototype chain, and that they're marked as dirty.
+ *
+ * @param mnodes The new node or nodes to add.
+ * @param sample A node from whose raws the new node's `before` raw should be
+ * taken.
+ * @param type This should be set to `'prepend'` if the new nodes will be
+ * inserted at the beginning of the container.
+ * @hidden
+ */
+ protected normalize(
+ nodes: Container.NewChild,
+ sample: Node | undefined,
+ type?: 'prepend' | false
+ ): Child[]
+}
+
+declare class Container<
+ Child extends Node = ChildNode
+> extends Container_<Child> {}
+
+export = Container
diff --git a/frontend/node_modules/postcss/lib/container.js b/frontend/node_modules/postcss/lib/container.js
new file mode 100644
index 0000000..edb07cc
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/container.js
@@ -0,0 +1,447 @@
+'use strict'
+
+let Comment = require('./comment')
+let Declaration = require('./declaration')
+let Node = require('./node')
+let { isClean, my } = require('./symbols')
+
+let AtRule, parse, Root, Rule
+
+function cleanSource(nodes) {
+ return nodes.map(i => {
+ if (i.nodes) i.nodes = cleanSource(i.nodes)
+ delete i.source
+ return i
+ })
+}
+
+function markTreeDirty(node) {
+ node[isClean] = false
+ if (node.proxyOf.nodes) {
+ for (let i of node.proxyOf.nodes) {
+ markTreeDirty(i)
+ }
+ }
+}
+
+class Container extends Node {
+ get first() {
+ if (!this.proxyOf.nodes) return undefined
+ return this.proxyOf.nodes[0]
+ }
+
+ get last() {
+ if (!this.proxyOf.nodes) return undefined
+ return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
+ }
+
+ append(...children) {
+ for (let child of children) {
+ let nodes = this.normalize(child, this.last)
+ for (let node of nodes) this.proxyOf.nodes.push(node)
+ }
+
+ this.markDirty()
+
+ return this
+ }
+
+ cleanRaws(keepBetween) {
+ super.cleanRaws(keepBetween)
+ if (this.nodes) {
+ for (let node of this.nodes) node.cleanRaws(keepBetween)
+ }
+ }
+
+ each(callback) {
+ if (!this.proxyOf.nodes) return undefined
+ let iterator = this.getIterator()
+
+ let index, result
+ while (this.indexes[iterator] < this.proxyOf.nodes.length) {
+ index = this.indexes[iterator]
+ result = callback(this.proxyOf.nodes[index], index)
+ if (result === false) break
+
+ this.indexes[iterator] += 1
+ }
+
+ delete this.indexes[iterator]
+ return result
+ }
+
+ every(condition) {
+ return this.nodes.every(condition)
+ }
+
+ getIterator() {
+ if (!this.lastEach) this.lastEach = 0
+ if (!this.indexes) this.indexes = {}
+
+ this.lastEach += 1
+ let iterator = this.lastEach
+ this.indexes[iterator] = 0
+
+ return iterator
+ }
+
+ getProxyProcessor() {
+ return {
+ get(node, prop) {
+ if (prop === 'proxyOf') {
+ return node
+ } else if (!node[prop]) {
+ return node[prop]
+ } else if (
+ prop === 'each' ||
+ (typeof prop === 'string' && prop.startsWith('walk'))
+ ) {
+ return (...args) => {
+ return node[prop](
+ ...args.map(i => {
+ if (typeof i === 'function') {
+ return (child, index) => i(child.toProxy(), index)
+ } else {
+ return i
+ }
+ })
+ )
+ }
+ } else if (prop === 'every' || prop === 'some') {
+ return cb => {
+ return node[prop]((child, ...other) =>
+ cb(child.toProxy(), ...other)
+ )
+ }
+ } else if (prop === 'root') {
+ return () => node.root().toProxy()
+ } else if (prop === 'nodes') {
+ return node.nodes.map(i => i.toProxy())
+ } else if (prop === 'first' || prop === 'last') {
+ return node[prop].toProxy()
+ } else {
+ return node[prop]
+ }
+ },
+
+ set(node, prop, value) {
+ if (node[prop] === value) return true
+ node[prop] = value
+ if (prop === 'name' || prop === 'params' || prop === 'selector') {
+ node.markDirty()
+ }
+ return true
+ }
+ }
+ }
+
+ index(child) {
+ if (typeof child === 'number') return child
+ if (child.proxyOf) child = child.proxyOf
+ return this.proxyOf.nodes.indexOf(child)
+ }
+
+ insertAfter(exist, add) {
+ let existIndex = this.index(exist)
+ let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse()
+ existIndex = this.index(exist)
+ for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node)
+
+ let index
+ for (let id in this.indexes) {
+ index = this.indexes[id]
+ if (existIndex < index) {
+ this.indexes[id] = index + nodes.length
+ }
+ }
+
+ this.markDirty()
+
+ return this
+ }
+
+ insertBefore(exist, add) {
+ let existIndex = this.index(exist)
+ let type = existIndex === 0 ? 'prepend' : false
+ let nodes = this.normalize(
+ add,
+ this.proxyOf.nodes[existIndex],
+ type
+ ).reverse()
+ existIndex = this.index(exist)
+ for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node)
+
+ let index
+ for (let id in this.indexes) {
+ index = this.indexes[id]
+ if (existIndex <= index) {
+ this.indexes[id] = index + nodes.length
+ }
+ }
+
+ this.markDirty()
+
+ return this
+ }
+
+ normalize(nodes, sample) {
+ if (typeof nodes === 'string') {
+ nodes = cleanSource(parse(nodes).nodes)
+ } else if (typeof nodes === 'undefined') {
+ nodes = []
+ } else if (Array.isArray(nodes)) {
+ nodes = nodes.slice(0)
+ for (let i of nodes) {
+ if (i.parent) i.parent.removeChild(i, 'ignore')
+ }
+ } else if (nodes.type === 'root' && this.type !== 'document') {
+ nodes = nodes.nodes.slice(0)
+ for (let i of nodes) {
+ if (i.parent) i.parent.removeChild(i, 'ignore')
+ }
+ } else if (nodes.type) {
+ nodes = [nodes]
+ } else if (nodes.prop) {
+ if (typeof nodes.value === 'undefined') {
+ throw new Error('Value field is missed in node creation')
+ } else if (typeof nodes.value !== 'string') {
+ nodes.value = String(nodes.value)
+ }
+ nodes = [new Declaration(nodes)]
+ } else if (nodes.selector || nodes.selectors) {
+ nodes = [new Rule(nodes)]
+ } else if (nodes.name) {
+ nodes = [new AtRule(nodes)]
+ } else if (nodes.text) {
+ nodes = [new Comment(nodes)]
+ } else {
+ throw new Error('Unknown node type in node creation')
+ }
+
+ let processed = nodes.map(i => {
+ /* c8 ignore next */
+ if (!i[my]) Container.rebuild(i)
+ i = i.proxyOf
+ if (i.parent) i.parent.removeChild(i)
+ if (i[isClean]) markTreeDirty(i)
+
+ if (!i.raws) i.raws = {}
+ if (typeof i.raws.before === 'undefined') {
+ if (sample && typeof sample.raws.before !== 'undefined') {
+ i.raws.before = sample.raws.before.replace(/\S/g, '')
+ }
+ }
+ i.parent = this.proxyOf
+ return i
+ })
+
+ return processed
+ }
+
+ prepend(...children) {
+ children = children.reverse()
+ for (let child of children) {
+ let nodes = this.normalize(child, this.first, 'prepend').reverse()
+ for (let node of nodes) this.proxyOf.nodes.unshift(node)
+ for (let id in this.indexes) {
+ this.indexes[id] = this.indexes[id] + nodes.length
+ }
+ }
+
+ this.markDirty()
+
+ return this
+ }
+
+ push(child) {
+ child.parent = this
+ this.proxyOf.nodes.push(child)
+ return this
+ }
+
+ removeAll() {
+ for (let node of this.proxyOf.nodes) node.parent = undefined
+ this.proxyOf.nodes = []
+
+ this.markDirty()
+
+ return this
+ }
+
+ removeChild(child) {
+ child = this.index(child)
+ this.proxyOf.nodes[child].parent = undefined
+ this.proxyOf.nodes.splice(child, 1)
+
+ let index
+ for (let id in this.indexes) {
+ index = this.indexes[id]
+ if (index >= child) {
+ this.indexes[id] = index - 1
+ }
+ }
+
+ this.markDirty()
+
+ return this
+ }
+
+ replaceValues(pattern, opts, callback) {
+ if (!callback) {
+ callback = opts
+ opts = {}
+ }
+
+ this.walkDecls(decl => {
+ if (opts.props && !opts.props.includes(decl.prop)) return
+ if (opts.fast && !decl.value.includes(opts.fast)) return
+
+ decl.value = decl.value.replace(pattern, callback)
+ })
+
+ this.markDirty()
+
+ return this
+ }
+
+ some(condition) {
+ return this.nodes.some(condition)
+ }
+
+ walk(callback) {
+ return this.each((child, i) => {
+ let result
+ try {
+ result = callback(child, i)
+ } catch (e) {
+ throw child.addToError(e)
+ }
+ if (result !== false && child.walk) {
+ result = child.walk(callback)
+ }
+
+ return result
+ })
+ }
+
+ walkAtRules(name, callback) {
+ if (!callback) {
+ callback = name
+ return this.walk((child, i) => {
+ if (child.type === 'atrule') {
+ return callback(child, i)
+ }
+ })
+ }
+ if (name instanceof RegExp) {
+ return this.walk((child, i) => {
+ if (child.type === 'atrule' && name.test(child.name)) {
+ return callback(child, i)
+ }
+ })
+ }
+ return this.walk((child, i) => {
+ if (child.type === 'atrule' && child.name === name) {
+ return callback(child, i)
+ }
+ })
+ }
+
+ walkComments(callback) {
+ return this.walk((child, i) => {
+ if (child.type === 'comment') {
+ return callback(child, i)
+ }
+ })
+ }
+
+ walkDecls(prop, callback) {
+ if (!callback) {
+ callback = prop
+ return this.walk((child, i) => {
+ if (child.type === 'decl') {
+ return callback(child, i)
+ }
+ })
+ }
+ if (prop instanceof RegExp) {
+ return this.walk((child, i) => {
+ if (child.type === 'decl' && prop.test(child.prop)) {
+ return callback(child, i)
+ }
+ })
+ }
+ return this.walk((child, i) => {
+ if (child.type === 'decl' && child.prop === prop) {
+ return callback(child, i)
+ }
+ })
+ }
+
+ walkRules(selector, callback) {
+ if (!callback) {
+ callback = selector
+
+ return this.walk((child, i) => {
+ if (child.type === 'rule') {
+ return callback(child, i)
+ }
+ })
+ }
+ if (selector instanceof RegExp) {
+ return this.walk((child, i) => {
+ if (child.type === 'rule' && selector.test(child.selector)) {
+ return callback(child, i)
+ }
+ })
+ }
+ return this.walk((child, i) => {
+ if (child.type === 'rule' && child.selector === selector) {
+ return callback(child, i)
+ }
+ })
+ }
+}
+
+Container.registerParse = dependant => {
+ parse = dependant
+}
+
+Container.registerRule = dependant => {
+ Rule = dependant
+}
+
+Container.registerAtRule = dependant => {
+ AtRule = dependant
+}
+
+Container.registerRoot = dependant => {
+ Root = dependant
+}
+
+module.exports = Container
+Container.default = Container
+
+/* c8 ignore start */
+Container.rebuild = node => {
+ if (node.type === 'atrule') {
+ Object.setPrototypeOf(node, AtRule.prototype)
+ } else if (node.type === 'rule') {
+ Object.setPrototypeOf(node, Rule.prototype)
+ } else if (node.type === 'decl') {
+ Object.setPrototypeOf(node, Declaration.prototype)
+ } else if (node.type === 'comment') {
+ Object.setPrototypeOf(node, Comment.prototype)
+ } else if (node.type === 'root') {
+ Object.setPrototypeOf(node, Root.prototype)
+ }
+
+ node[my] = true
+
+ if (node.nodes) {
+ node.nodes.forEach(child => {
+ Container.rebuild(child)
+ })
+ }
+}
+/* c8 ignore stop */
diff --git a/frontend/node_modules/postcss/lib/css-syntax-error.d.ts b/frontend/node_modules/postcss/lib/css-syntax-error.d.ts
new file mode 100644
index 0000000..e540d84
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/css-syntax-error.d.ts
@@ -0,0 +1,248 @@
+import { FilePosition } from './input.js'
+
+declare namespace CssSyntaxError {
+ /**
+ * A position that is part of a range.
+ */
+ export interface RangePosition {
+ /**
+ * The column number in the input.
+ */
+ column: number
+
+ /**
+ * The line number in the input.
+ */
+ line: number
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { CssSyntaxError_ as default }
+}
+
+/**
+ * The CSS parser throws this error for broken CSS.
+ *
+ * Custom parsers can throw this error for broken custom syntax using
+ * the `Node#error` method.
+ *
+ * PostCSS will use the input source map to detect the original error location.
+ * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
+ * PostCSS will show the original position in the Sass file.
+ *
+ * If you need the position in the PostCSS input
+ * (e.g., to debug the previous compiler), use `error.input.file`.
+ *
+ * ```js
+ * // Raising error from plugin
+ * throw node.error('Unknown variable', { plugin: 'postcss-vars' })
+ * ```
+ *
+ * ```js
+ * // Catching and checking syntax error
+ * try {
+ * postcss.parse('a{')
+ * } catch (error) {
+ * if (error.name === 'CssSyntaxError') {
+ * error //=> CssSyntaxError
+ * }
+ * }
+ * ```
+ */
+declare class CssSyntaxError_ extends Error {
+ /**
+ * Source column of the error.
+ *
+ * ```js
+ * error.column //=> 1
+ * error.input.column //=> 4
+ * ```
+ *
+ * PostCSS will use the input source map to detect the original location.
+ * If you need the position in the PostCSS input, use `error.input.column`.
+ */
+ column?: number
+
+ /**
+ * Source column of the error's end, exclusive. Provided if the error pertains
+ * to a range.
+ *
+ * ```js
+ * error.endColumn //=> 1
+ * error.input.endColumn //=> 4
+ * ```
+ *
+ * PostCSS will use the input source map to detect the original location.
+ * If you need the position in the PostCSS input, use `error.input.endColumn`.
+ */
+ endColumn?: number
+
+ /**
+ * Source line of the error's end, exclusive. Provided if the error pertains
+ * to a range.
+ *
+ * ```js
+ * error.endLine //=> 3
+ * error.input.endLine //=> 4
+ * ```
+ *
+ * PostCSS will use the input source map to detect the original location.
+ * If you need the position in the PostCSS input, use `error.input.endLine`.
+ */
+ endLine?: number
+
+ /**
+ * Absolute path to the broken file.
+ *
+ * ```js
+ * error.file //=> 'a.sass'
+ * error.input.file //=> 'a.css'
+ * ```
+ *
+ * PostCSS will use the input source map to detect the original location.
+ * If you need the position in the PostCSS input, use `error.input.file`.
+ */
+ file?: string
+
+ /**
+ * Input object with PostCSS internal information
+ * about input file. If input has source map
+ * from previous tool, PostCSS will use origin
+ * (for example, Sass) source. You can use this
+ * object to get PostCSS input source.
+ *
+ * ```js
+ * error.input.file //=> 'a.css'
+ * error.file //=> 'a.sass'
+ * ```
+ */
+ input?: FilePosition
+
+ /**
+ * Source line of the error.
+ *
+ * ```js
+ * error.line //=> 2
+ * error.input.line //=> 4
+ * ```
+ *
+ * PostCSS will use the input source map to detect the original location.
+ * If you need the position in the PostCSS input, use `error.input.line`.
+ */
+ line?: number
+
+ /**
+ * Full error text in the GNU error format
+ * with plugin, file, line and column.
+ *
+ * ```js
+ * error.message //=> 'a.css:1:1: Unclosed block'
+ * ```
+ */
+ message: string
+
+ /**
+ * Always equal to `'CssSyntaxError'`. You should always check error type
+ * by `error.name === 'CssSyntaxError'`
+ * instead of `error instanceof CssSyntaxError`,
+ * because npm could have several PostCSS versions.
+ *
+ * ```js
+ * if (error.name === 'CssSyntaxError') {
+ * error //=> CssSyntaxError
+ * }
+ * ```
+ */
+ name: 'CssSyntaxError'
+
+ /**
+ * Plugin name, if error came from plugin.
+ *
+ * ```js
+ * error.plugin //=> 'postcss-vars'
+ * ```
+ */
+ plugin?: string
+
+ /**
+ * Error message.
+ *
+ * ```js
+ * error.message //=> 'Unclosed block'
+ * ```
+ */
+ reason: string
+
+ /**
+ * Source code of the broken file.
+ *
+ * ```js
+ * error.source //=> 'a { b {} }'
+ * error.input.source //=> 'a b { }'
+ * ```
+ */
+ source?: string
+
+ stack: string
+
+ /**
+ * Instantiates a CSS syntax error. Can be instantiated for a single position
+ * or for a range.
+ * @param message Error message.
+ * @param lineOrStartPos If for a single position, the line number, or if for
+ * a range, the inclusive start position of the error.
+ * @param columnOrEndPos If for a single position, the column number, or if for
+ * a range, the exclusive end position of the error.
+ * @param source Source code of the broken file.
+ * @param file Absolute path to the broken file.
+ * @param plugin PostCSS plugin name, if error came from plugin.
+ */
+ constructor(
+ message: string,
+ lineOrStartPos?: CssSyntaxError.RangePosition | number,
+ columnOrEndPos?: CssSyntaxError.RangePosition | number,
+ source?: string,
+ file?: string,
+ plugin?: string
+ )
+
+ /**
+ * Returns a few lines of CSS source that caused the error.
+ *
+ * If the CSS has an input source map without `sourceContent`,
+ * this method will return an empty string.
+ *
+ * ```js
+ * error.showSourceCode() //=> " 4 | }
+ * // 5 | a {
+ * // > 6 | bad
+ * // | ^
+ * // 7 | }
+ * // 8 | b {"
+ * ```
+ *
+ * @param color Whether arrow will be colored red by terminal
+ * color codes. By default, PostCSS will detect
+ * color support by `process.stdout.isTTY`
+ * and `process.env.NODE_DISABLE_COLORS`.
+ * @return Few lines of CSS source that caused the error.
+ */
+ showSourceCode(color?: boolean): string
+
+ /**
+ * Returns error position, message and source code of the broken part.
+ *
+ * ```js
+ * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
+ * // > 1 | a {
+ * // | ^"
+ * ```
+ *
+ * @return Error position, message and source code.
+ */
+ toString(): string
+}
+
+declare class CssSyntaxError extends CssSyntaxError_ {}
+
+export = CssSyntaxError
diff --git a/frontend/node_modules/postcss/lib/css-syntax-error.js b/frontend/node_modules/postcss/lib/css-syntax-error.js
new file mode 100644
index 0000000..275a4f6
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/css-syntax-error.js
@@ -0,0 +1,133 @@
+'use strict'
+
+let pico = require('picocolors')
+
+let terminalHighlight = require('./terminal-highlight')
+
+class CssSyntaxError extends Error {
+ constructor(message, line, column, source, file, plugin) {
+ super(message)
+ this.name = 'CssSyntaxError'
+ this.reason = message
+
+ if (file) {
+ this.file = file
+ }
+ if (source) {
+ this.source = source
+ }
+ if (plugin) {
+ this.plugin = plugin
+ }
+ if (typeof line !== 'undefined' && typeof column !== 'undefined') {
+ if (typeof line === 'number') {
+ this.line = line
+ this.column = column
+ } else {
+ this.line = line.line
+ this.column = line.column
+ this.endLine = column.line
+ this.endColumn = column.column
+ }
+ }
+
+ this.setMessage()
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, CssSyntaxError)
+ }
+ }
+
+ setMessage() {
+ this.message = this.plugin ? this.plugin + ': ' : ''
+ this.message += this.file ? this.file : '<css input>'
+ if (typeof this.line !== 'undefined') {
+ this.message += ':' + this.line + ':' + this.column
+ }
+ this.message += ': ' + this.reason
+ }
+
+ showSourceCode(color) {
+ if (!this.source) return ''
+
+ let css = this.source
+ if (color == null) color = pico.isColorSupported
+
+ let aside = text => text
+ let mark = text => text
+ let highlight = text => text
+ if (color) {
+ let { bold, gray, red } = pico.createColors(true)
+ mark = text => bold(red(text))
+ aside = text => gray(text)
+ if (terminalHighlight) {
+ highlight = text => terminalHighlight(text)
+ }
+ }
+
+ let lines = css.split(/\r?\n/)
+ let start = Math.max(this.line - 3, 0)
+ let end = Math.min(this.line + 2, lines.length)
+ let maxWidth = String(end).length
+
+ return lines
+ .slice(start, end)
+ .map((line, index) => {
+ let number = start + 1 + index
+ let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
+ if (number === this.line) {
+ if (line.length > 160) {
+ let padding = 20
+ let subLineStart = Math.max(0, this.column - padding)
+ let subLineEnd = Math.max(
+ this.column + padding,
+ this.endColumn + padding
+ )
+ let subLine = line.slice(subLineStart, subLineEnd)
+
+ let spacing =
+ aside(gutter.replace(/\d/g, ' ')) +
+ line
+ .slice(0, Math.min(this.column - 1, padding - 1))
+ .replace(/[^\t]/g, ' ')
+
+ return (
+ mark('>') +
+ aside(gutter) +
+ highlight(subLine) +
+ '\n ' +
+ spacing +
+ mark('^')
+ )
+ }
+
+ let spacing =
+ aside(gutter.replace(/\d/g, ' ')) +
+ line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
+
+ return (
+ mark('>') +
+ aside(gutter) +
+ highlight(line) +
+ '\n ' +
+ spacing +
+ mark('^')
+ )
+ }
+
+ return ' ' + aside(gutter) + highlight(line)
+ })
+ .join('\n')
+ }
+
+ toString() {
+ let code = this.showSourceCode()
+ if (code) {
+ code = '\n\n' + code + '\n'
+ }
+ return this.name + ': ' + this.message + code
+ }
+}
+
+module.exports = CssSyntaxError
+CssSyntaxError.default = CssSyntaxError
diff --git a/frontend/node_modules/postcss/lib/declaration.d.ts b/frontend/node_modules/postcss/lib/declaration.d.ts
new file mode 100644
index 0000000..d489b42
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/declaration.d.ts
@@ -0,0 +1,151 @@
+import { ContainerWithChildren } from './container.js'
+import Node from './node.js'
+
+declare namespace Declaration {
+ export interface DeclarationRaws extends Record<string, unknown> {
+ /**
+ * The space symbols before the node. It also stores `*`
+ * and `_` symbols before the declaration (IE hack).
+ */
+ before?: string
+
+ /**
+ * The symbols between the property and value for declarations.
+ */
+ between?: string
+
+ /**
+ * The content of the important statement, if it is not just `!important`.
+ */
+ important?: string
+
+ /**
+ * Declaration value with comments.
+ */
+ value?: {
+ raw: string
+ value: string
+ }
+ }
+
+ export interface DeclarationProps {
+ /** Whether the declaration has an `!important` annotation. */
+ important?: boolean
+ /** Name of the declaration. */
+ prop: string
+ /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
+ raws?: DeclarationRaws
+ /** Value of the declaration. */
+ value: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Declaration_ as default }
+}
+
+/**
+ * It represents a class that handles
+ * [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
+ *
+ * ```js
+ * Once (root, { Declaration }) {
+ * const color = new Declaration({ prop: 'color', value: 'black' })
+ * root.append(color)
+ * }
+ * ```
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black }')
+ * const decl = root.first?.first
+ *
+ * decl.type //=> 'decl'
+ * decl.toString() //=> ' color: black'
+ * ```
+ */
+declare class Declaration_ extends Node {
+ parent: ContainerWithChildren | undefined
+ raws: Declaration.DeclarationRaws
+
+ type: 'decl'
+
+ /**
+ * It represents a specificity of the declaration.
+ *
+ * If true, the CSS declaration will have an
+ * [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important)
+ * specifier.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black !important; color: red }')
+ *
+ * root.first.first.important //=> true
+ * root.first.last.important //=> undefined
+ * ```
+ */
+ get important(): boolean
+ set important(value: boolean)
+
+ /**
+ * The property name for a CSS declaration.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black }')
+ * const decl = root.first.first
+ *
+ * decl.prop //=> 'color'
+ * ```
+ */
+ get prop(): string
+
+ set prop(value: string)
+
+ /**
+ * The property value for a CSS declaration.
+ *
+ * Any CSS comments inside the value string will be filtered out.
+ * CSS comments present in the source value will be available in
+ * the `raws` property.
+ *
+ * Assigning new `value` would ignore the comments in `raws`
+ * property while compiling node to string.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black }')
+ * const decl = root.first.first
+ *
+ * decl.value //=> 'black'
+ * ```
+ */
+ get value(): string
+ set value(value: string)
+
+ /**
+ * It represents a getter that returns `true` if a declaration starts with
+ * `--` or `$`, which are used to declare variables in CSS and SASS/SCSS.
+ *
+ * ```js
+ * const root = postcss.parse(':root { --one: 1 }')
+ * const one = root.first.first
+ *
+ * one.variable //=> true
+ * ```
+ *
+ * ```js
+ * const root = postcss.parse('$one: 1')
+ * const one = root.first
+ *
+ * one.variable //=> true
+ * ```
+ */
+ get variable(): boolean
+ constructor(defaults?: Declaration.DeclarationProps)
+
+ assign(overrides: Declaration.DeclarationProps | object): this
+ clone(overrides?: Partial<Declaration.DeclarationProps>): this
+ cloneAfter(overrides?: Partial<Declaration.DeclarationProps>): this
+ cloneBefore(overrides?: Partial<Declaration.DeclarationProps>): this
+}
+
+declare class Declaration extends Declaration_ {}
+
+export = Declaration
diff --git a/frontend/node_modules/postcss/lib/declaration.js b/frontend/node_modules/postcss/lib/declaration.js
new file mode 100644
index 0000000..65a03aa
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/declaration.js
@@ -0,0 +1,24 @@
+'use strict'
+
+let Node = require('./node')
+
+class Declaration extends Node {
+ get variable() {
+ return this.prop.startsWith('--') || this.prop[0] === '$'
+ }
+
+ constructor(defaults) {
+ if (
+ defaults &&
+ typeof defaults.value !== 'undefined' &&
+ typeof defaults.value !== 'string'
+ ) {
+ defaults = { ...defaults, value: String(defaults.value) }
+ }
+ super(defaults)
+ this.type = 'decl'
+ }
+}
+
+module.exports = Declaration
+Declaration.default = Declaration
diff --git a/frontend/node_modules/postcss/lib/document.d.ts b/frontend/node_modules/postcss/lib/document.d.ts
new file mode 100644
index 0000000..f9e8063
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/document.d.ts
@@ -0,0 +1,69 @@
+import Container, { ContainerProps } from './container.js'
+import { ProcessOptions } from './postcss.js'
+import Result from './result.js'
+import Root from './root.js'
+
+declare namespace Document {
+ export interface DocumentProps extends ContainerProps {
+ nodes?: readonly Root[]
+
+ /**
+ * Information to generate byte-to-byte equal node string as it was
+ * in the origin input.
+ *
+ * Every parser saves its own properties.
+ */
+ raws?: Record<string, any>
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Document_ as default }
+}
+
+/**
+ * Represents a file and contains all its parsed nodes.
+ *
+ * **Experimental:** some aspects of this node could change within minor
+ * or patch version releases.
+ *
+ * ```js
+ * const document = htmlParser(
+ * '<html><style>a{color:black}</style><style>b{z-index:2}</style>'
+ * )
+ * document.type //=> 'document'
+ * document.nodes.length //=> 2
+ * ```
+ */
+declare class Document_ extends Container<Root> {
+ nodes: Root[]
+ parent: undefined
+ type: 'document'
+
+ constructor(defaults?: Document.DocumentProps)
+
+ assign(overrides: Document.DocumentProps | object): this
+ clone(overrides?: Partial<Document.DocumentProps>): this
+ cloneAfter(overrides?: Partial<Document.DocumentProps>): this
+ cloneBefore(overrides?: Partial<Document.DocumentProps>): this
+
+ /**
+ * Returns a `Result` instance representing the document’s CSS roots.
+ *
+ * ```js
+ * const root1 = postcss.parse(css1, { from: 'a.css' })
+ * const root2 = postcss.parse(css2, { from: 'b.css' })
+ * const document = postcss.document()
+ * document.append(root1)
+ * document.append(root2)
+ * const result = document.toResult({ to: 'all.css', map: true })
+ * ```
+ *
+ * @param opts Options.
+ * @return Result with current document’s CSS.
+ */
+ toResult(options?: ProcessOptions): Result
+}
+
+declare class Document extends Document_ {}
+
+export = Document
diff --git a/frontend/node_modules/postcss/lib/document.js b/frontend/node_modules/postcss/lib/document.js
new file mode 100644
index 0000000..4468991
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/document.js
@@ -0,0 +1,33 @@
+'use strict'
+
+let Container = require('./container')
+
+let LazyResult, Processor
+
+class Document extends Container {
+ constructor(defaults) {
+ // type needs to be passed to super, otherwise child roots won't be normalized correctly
+ super({ type: 'document', ...defaults })
+
+ if (!this.nodes) {
+ this.nodes = []
+ }
+ }
+
+ toResult(opts = {}) {
+ let lazy = new LazyResult(new Processor(), this, opts)
+
+ return lazy.stringify()
+ }
+}
+
+Document.registerLazyResult = dependant => {
+ LazyResult = dependant
+}
+
+Document.registerProcessor = dependant => {
+ Processor = dependant
+}
+
+module.exports = Document
+Document.default = Document
diff --git a/frontend/node_modules/postcss/lib/fromJSON.d.ts b/frontend/node_modules/postcss/lib/fromJSON.d.ts
new file mode 100644
index 0000000..e1deedb
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/fromJSON.d.ts
@@ -0,0 +1,9 @@
+import { JSONHydrator } from './postcss.js'
+
+interface FromJSON extends JSONHydrator {
+ default: FromJSON
+}
+
+declare const fromJSON: FromJSON
+
+export = fromJSON
diff --git a/frontend/node_modules/postcss/lib/fromJSON.js b/frontend/node_modules/postcss/lib/fromJSON.js
new file mode 100644
index 0000000..c9ac1a8
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/fromJSON.js
@@ -0,0 +1,54 @@
+'use strict'
+
+let AtRule = require('./at-rule')
+let Comment = require('./comment')
+let Declaration = require('./declaration')
+let Input = require('./input')
+let PreviousMap = require('./previous-map')
+let Root = require('./root')
+let Rule = require('./rule')
+
+function fromJSON(json, inputs) {
+ if (Array.isArray(json)) return json.map(n => fromJSON(n))
+
+ let { inputs: ownInputs, ...defaults } = json
+ if (ownInputs) {
+ inputs = []
+ for (let input of ownInputs) {
+ let inputHydrated = { ...input, __proto__: Input.prototype }
+ if (inputHydrated.map) {
+ inputHydrated.map = {
+ ...inputHydrated.map,
+ __proto__: PreviousMap.prototype
+ }
+ }
+ inputs.push(inputHydrated)
+ }
+ }
+ if (defaults.nodes) {
+ defaults.nodes = json.nodes.map(n => fromJSON(n, inputs))
+ }
+ if (defaults.source) {
+ let { inputId, ...source } = defaults.source
+ defaults.source = source
+ if (inputId != null) {
+ defaults.source.input = inputs[inputId]
+ }
+ }
+ if (defaults.type === 'root') {
+ return new Root(defaults)
+ } else if (defaults.type === 'decl') {
+ return new Declaration(defaults)
+ } else if (defaults.type === 'rule') {
+ return new Rule(defaults)
+ } else if (defaults.type === 'comment') {
+ return new Comment(defaults)
+ } else if (defaults.type === 'atrule') {
+ return new AtRule(defaults)
+ } else {
+ throw new Error('Unknown node type: ' + json.type)
+ }
+}
+
+module.exports = fromJSON
+fromJSON.default = fromJSON
diff --git a/frontend/node_modules/postcss/lib/input.d.ts b/frontend/node_modules/postcss/lib/input.d.ts
new file mode 100644
index 0000000..3207da3
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/input.d.ts
@@ -0,0 +1,227 @@
+import { CssSyntaxError, ProcessOptions } from './postcss.js'
+import PreviousMap from './previous-map.js'
+
+declare namespace Input {
+ export interface FilePosition {
+ /**
+ * Column of inclusive start position in source file.
+ */
+ column: number
+
+ /**
+ * Column of exclusive end position in source file.
+ */
+ endColumn?: number
+
+ /**
+ * Line of exclusive end position in source file.
+ */
+ endLine?: number
+
+ /**
+ * Offset of exclusive end position in source file.
+ */
+ endOffset?: number
+
+ /**
+ * Absolute path to the source file.
+ */
+ file?: string
+
+ /**
+ * Line of inclusive start position in source file.
+ */
+ line: number
+
+ /**
+ * Offset of inclusive start position in source file.
+ */
+ offset: number
+
+ /**
+ * Source code.
+ */
+ source?: string
+
+ /**
+ * URL for the source file.
+ */
+ url: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Input_ as default }
+}
+
+/**
+ * Represents the source CSS.
+ *
+ * ```js
+ * const root = postcss.parse(css, { from: file })
+ * const input = root.source.input
+ * ```
+ */
+declare class Input_ {
+ /**
+ * Input CSS source.
+ *
+ * ```js
+ * const input = postcss.parse('a{}', { from: file }).input
+ * input.css //=> "a{}"
+ * ```
+ */
+ css: string
+
+ /**
+ * Input source with support for non-CSS documents.
+ *
+ * ```js
+ * const input = postcss.parse('a{}', { from: file, document: '<style>a {}</style>' }).input
+ * input.document //=> "<style>a {}</style>"
+ * input.css //=> "a{}"
+ * ```
+ */
+ document: string
+
+ /**
+ * The absolute path to the CSS source file defined
+ * with the `from` option.
+ *
+ * ```js
+ * const root = postcss.parse(css, { from: 'a.css' })
+ * root.source.input.file //=> '/home/ai/a.css'
+ * ```
+ */
+ file?: string
+
+ /**
+ * The flag to indicate whether or not the source code has Unicode BOM.
+ */
+ hasBOM: boolean
+
+ /**
+ * The unique ID of the CSS source. It will be created if `from` option
+ * is not provided (because PostCSS does not know the file path).
+ *
+ * ```js
+ * const root = postcss.parse(css)
+ * root.source.input.file //=> undefined
+ * root.source.input.id //=> "<input css 8LZeVF>"
+ * ```
+ */
+ id?: string
+
+ /**
+ * The input source map passed from a compilation step before PostCSS
+ * (for example, from Sass compiler).
+ *
+ * ```js
+ * root.source.input.map.consumer().sources //=> ['a.sass']
+ * ```
+ */
+ map: PreviousMap
+
+ /**
+ * The CSS source identifier. Contains `Input#file` if the user
+ * set the `from` option, or `Input#id` if they did not.
+ *
+ * ```js
+ * const root = postcss.parse(css, { from: 'a.css' })
+ * root.source.input.from //=> "/home/ai/a.css"
+ *
+ * const root = postcss.parse(css)
+ * root.source.input.from //=> "<input css 1>"
+ * ```
+ */
+ get from(): string
+
+ /**
+ * @param css Input CSS source.
+ * @param opts Process options.
+ */
+ constructor(css: string, opts?: ProcessOptions)
+
+ /**
+ * Returns `CssSyntaxError` with information about the error and its position.
+ */
+ error(
+ message: string,
+ start:
+ | {
+ column: number
+ line: number
+ }
+ | {
+ offset: number
+ },
+ end:
+ | {
+ column: number
+ line: number
+ }
+ | {
+ offset: number
+ },
+ opts?: { plugin?: CssSyntaxError['plugin'] }
+ ): CssSyntaxError
+ error(
+ message: string,
+ line: number,
+ column: number,
+ opts?: { plugin?: CssSyntaxError['plugin'] }
+ ): CssSyntaxError
+ error(
+ message: string,
+ offset: number,
+ opts?: { plugin?: CssSyntaxError['plugin'] }
+ ): CssSyntaxError
+
+ /**
+ * Converts source line and column to offset.
+ *
+ * @param line Source line.
+ * @param column Source column.
+ * @return Source offset.
+ */
+ fromLineAndColumn(line: number, column: number): number
+
+ /**
+ * Converts source offset to line and column.
+ *
+ * @param offset Source offset.
+ */
+ fromOffset(offset: number): { col: number; line: number } | null
+
+ /**
+ * Reads the input source map and returns a symbol position
+ * in the input source (e.g., in a Sass file that was compiled
+ * to CSS before being passed to PostCSS). Optionally takes an
+ * end position, exclusive.
+ *
+ * ```js
+ * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
+ * root.source.input.origin(1, 1, 1, 4)
+ * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }
+ * ```
+ *
+ * @param line Line for inclusive start position in input CSS.
+ * @param column Column for inclusive start position in input CSS.
+ * @param endLine Line for exclusive end position in input CSS.
+ * @param endColumn Column for exclusive end position in input CSS.
+ *
+ * @return Position in input source.
+ */
+ origin(
+ line: number,
+ column: number,
+ endLine?: number,
+ endColumn?: number
+ ): false | Input.FilePosition
+
+ /** Converts this to a JSON-friendly object representation. */
+ toJSON(): object
+}
+
+declare class Input extends Input_ {}
+
+export = Input
diff --git a/frontend/node_modules/postcss/lib/input.js b/frontend/node_modules/postcss/lib/input.js
new file mode 100644
index 0000000..bb0ccf5
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/input.js
@@ -0,0 +1,265 @@
+'use strict'
+
+let { nanoid } = require('nanoid/non-secure')
+let { isAbsolute, resolve } = require('path')
+let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
+let { fileURLToPath, pathToFileURL } = require('url')
+
+let CssSyntaxError = require('./css-syntax-error')
+let PreviousMap = require('./previous-map')
+let terminalHighlight = require('./terminal-highlight')
+
+let lineToIndexCache = Symbol('lineToIndexCache')
+
+let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
+let pathAvailable = Boolean(resolve && isAbsolute)
+
+function getLineToIndex(input) {
+ if (input[lineToIndexCache]) return input[lineToIndexCache]
+ let lines = input.css.split('\n')
+ let lineToIndex = new Array(lines.length)
+ let prevIndex = 0
+
+ for (let i = 0, l = lines.length; i < l; i++) {
+ lineToIndex[i] = prevIndex
+ prevIndex += lines[i].length + 1
+ }
+
+ input[lineToIndexCache] = lineToIndex
+ return lineToIndex
+}
+
+class Input {
+ get from() {
+ return this.file || this.id
+ }
+
+ constructor(css, opts = {}) {
+ if (
+ css === null ||
+ typeof css === 'undefined' ||
+ (typeof css === 'object' && !css.toString)
+ ) {
+ throw new Error(`PostCSS received ${css} instead of CSS string`)
+ }
+
+ this.css = css.toString()
+
+ if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
+ this.hasBOM = true
+ this.css = this.css.slice(1)
+ } else {
+ this.hasBOM = false
+ }
+
+ this.document = this.css
+ if (opts.document) this.document = opts.document.toString()
+
+ if (opts.from) {
+ if (
+ !pathAvailable ||
+ /^\w+:\/\//.test(opts.from) ||
+ isAbsolute(opts.from)
+ ) {
+ this.file = opts.from
+ } else {
+ this.file = resolve(opts.from)
+ }
+ }
+
+ if (pathAvailable && sourceMapAvailable) {
+ let map = new PreviousMap(this.css, opts)
+ if (map.text) {
+ this.map = map
+ let file = map.consumer().file
+ if (!this.file && file) this.file = this.mapResolve(file)
+ }
+ }
+
+ if (!this.file) {
+ this.id = '<input css ' + nanoid(6) + '>'
+ }
+ if (this.map) this.map.file = this.from
+ }
+
+ error(message, line, column, opts = {}) {
+ let endColumn, endLine, endOffset, offset, result
+
+ if (line && typeof line === 'object') {
+ let start = line
+ let end = column
+ if (typeof start.offset === 'number') {
+ offset = start.offset
+ let pos = this.fromOffset(offset)
+ line = pos.line
+ column = pos.col
+ } else {
+ line = start.line
+ column = start.column
+ offset = this.fromLineAndColumn(line, column)
+ }
+ if (typeof end.offset === 'number') {
+ endOffset = end.offset
+ let pos = this.fromOffset(endOffset)
+ endLine = pos.line
+ endColumn = pos.col
+ } else {
+ endLine = end.line
+ endColumn = end.column
+ endOffset = this.fromLineAndColumn(end.line, end.column)
+ }
+ } else if (!column) {
+ offset = line
+ let pos = this.fromOffset(offset)
+ line = pos.line
+ column = pos.col
+ } else {
+ offset = this.fromLineAndColumn(line, column)
+ }
+
+ let origin = this.origin(line, column, endLine, endColumn)
+ if (origin) {
+ result = new CssSyntaxError(
+ message,
+ origin.endLine === undefined
+ ? origin.line
+ : { column: origin.column, line: origin.line },
+ origin.endLine === undefined
+ ? origin.column
+ : { column: origin.endColumn, line: origin.endLine },
+ origin.source,
+ origin.file,
+ opts.plugin
+ )
+ } else {
+ result = new CssSyntaxError(
+ message,
+ endLine === undefined ? line : { column, line },
+ endLine === undefined ? column : { column: endColumn, line: endLine },
+ this.css,
+ this.file,
+ opts.plugin
+ )
+ }
+
+ result.input = { column, endColumn, endLine, endOffset, line, offset, source: this.css }
+ if (this.file) {
+ if (pathToFileURL) {
+ result.input.url = pathToFileURL(this.file).toString()
+ }
+ result.input.file = this.file
+ }
+
+ return result
+ }
+
+ fromLineAndColumn(line, column) {
+ let lineToIndex = getLineToIndex(this)
+ let index = lineToIndex[line - 1]
+ return index + column - 1
+ }
+
+ fromOffset(offset) {
+ let lineToIndex = getLineToIndex(this)
+ let lastLine = lineToIndex[lineToIndex.length - 1]
+
+ let min = 0
+ if (offset >= lastLine) {
+ min = lineToIndex.length - 1
+ } else {
+ let max = lineToIndex.length - 2
+ let mid
+ while (min < max) {
+ mid = min + ((max - min) >> 1)
+ if (offset < lineToIndex[mid]) {
+ max = mid - 1
+ } else if (offset >= lineToIndex[mid + 1]) {
+ min = mid + 1
+ } else {
+ min = mid
+ break
+ }
+ }
+ }
+ return {
+ col: offset - lineToIndex[min] + 1,
+ line: min + 1
+ }
+ }
+
+ mapResolve(file) {
+ if (/^\w+:\/\//.test(file)) {
+ return file
+ }
+ return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
+ }
+
+ origin(line, column, endLine, endColumn) {
+ if (!this.map) return false
+ let consumer = this.map.consumer()
+
+ let from = consumer.originalPositionFor({ column, line })
+ if (!from.source) return false
+
+ let to
+ if (typeof endLine === 'number') {
+ to = consumer.originalPositionFor({ column: endColumn, line: endLine })
+ }
+
+ let fromUrl
+
+ if (isAbsolute(from.source)) {
+ fromUrl = pathToFileURL(from.source)
+ } else {
+ fromUrl = new URL(
+ from.source,
+ this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
+ )
+ }
+
+ let result = {
+ column: from.column,
+ endColumn: to && to.column,
+ endLine: to && to.line,
+ line: from.line,
+ url: fromUrl.toString()
+ }
+
+ if (fromUrl.protocol === 'file:') {
+ if (fileURLToPath) {
+ result.file = fileURLToPath(fromUrl)
+ } else {
+ /* c8 ignore next 2 */
+ throw new Error(`file: protocol is not available in this PostCSS build`)
+ }
+ }
+
+ let source = consumer.sourceContentFor(from.source)
+ if (source) result.source = source
+
+ return result
+ }
+
+ toJSON() {
+ let json = {}
+ for (let name of ['hasBOM', 'css', 'file', 'id']) {
+ if (this[name] != null) {
+ json[name] = this[name]
+ }
+ }
+ if (this.map) {
+ json.map = { ...this.map }
+ if (json.map.consumerCache) {
+ json.map.consumerCache = undefined
+ }
+ }
+ return json
+ }
+}
+
+module.exports = Input
+Input.default = Input
+
+if (terminalHighlight && terminalHighlight.registerInput) {
+ terminalHighlight.registerInput(Input)
+}
diff --git a/frontend/node_modules/postcss/lib/lazy-result.d.ts b/frontend/node_modules/postcss/lib/lazy-result.d.ts
new file mode 100644
index 0000000..2eb7279
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/lazy-result.d.ts
@@ -0,0 +1,190 @@
+import Document from './document.js'
+import { SourceMap } from './postcss.js'
+import Processor from './processor.js'
+import Result, { Message, ResultOptions } from './result.js'
+import Root from './root.js'
+import Warning from './warning.js'
+
+declare namespace LazyResult {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { LazyResult_ as default }
+}
+
+/**
+ * A Promise proxy for the result of PostCSS transformations.
+ *
+ * A `LazyResult` instance is returned by `Processor#process`.
+ *
+ * ```js
+ * const lazy = postcss([autoprefixer]).process(css)
+ * ```
+ */
+declare class LazyResult_<RootNode = Document | Root>
+ implements PromiseLike<Result<RootNode>>
+{
+ /**
+ * Processes input CSS through synchronous and asynchronous plugins
+ * and calls onRejected for each error thrown in any plugin.
+ *
+ * It implements standard Promise API.
+ *
+ * ```js
+ * postcss([autoprefixer]).process(css).then(result => {
+ * console.log(result.css)
+ * }).catch(error => {
+ * console.error(error)
+ * })
+ * ```
+ */
+ catch: Promise<Result<RootNode>>['catch']
+
+ /**
+ * Processes input CSS through synchronous and asynchronous plugins
+ * and calls onFinally on any error or when all plugins will finish work.
+ *
+ * It implements standard Promise API.
+ *
+ * ```js
+ * postcss([autoprefixer]).process(css).finally(() => {
+ * console.log('processing ended')
+ * })
+ * ```
+ */
+ finally: Promise<Result<RootNode>>['finally']
+
+ /**
+ * Processes input CSS through synchronous and asynchronous plugins
+ * and calls `onFulfilled` with a Result instance. If a plugin throws
+ * an error, the `onRejected` callback will be executed.
+ *
+ * It implements standard Promise API.
+ *
+ * ```js
+ * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
+ * console.log(result.css)
+ * })
+ * ```
+ */
+ then: Promise<Result<RootNode>>['then']
+
+ /**
+ * An alias for the `css` property. Use it with syntaxes
+ * that generate non-CSS output.
+ *
+ * This property will only work with synchronous plugins.
+ * If the processor contains any asynchronous plugins
+ * it will throw an error.
+ *
+ * PostCSS runners should always use `LazyResult#then`.
+ */
+ get content(): string
+
+ /**
+ * Processes input CSS through synchronous plugins, converts `Root`
+ * to a CSS string and returns `Result#css`.
+ *
+ * This property will only work with synchronous plugins.
+ * If the processor contains any asynchronous plugins
+ * it will throw an error.
+ *
+ * PostCSS runners should always use `LazyResult#then`.
+ */
+ get css(): string
+
+ /**
+ * Processes input CSS through synchronous plugins
+ * and returns `Result#map`.
+ *
+ * This property will only work with synchronous plugins.
+ * If the processor contains any asynchronous plugins
+ * it will throw an error.
+ *
+ * PostCSS runners should always use `LazyResult#then`.
+ */
+ get map(): SourceMap
+
+ /**
+ * Processes input CSS through synchronous plugins
+ * and returns `Result#messages`.
+ *
+ * This property will only work with synchronous plugins. If the processor
+ * contains any asynchronous plugins it will throw an error.
+ *
+ * PostCSS runners should always use `LazyResult#then`.
+ */
+ get messages(): Message[]
+
+ /**
+ * Options from the `Processor#process` call.
+ */
+ get opts(): ResultOptions
+
+ /**
+ * Returns a `Processor` instance, which will be used
+ * for CSS transformations.
+ */
+ get processor(): Processor
+
+ /**
+ * Processes input CSS through synchronous plugins
+ * and returns `Result#root`.
+ *
+ * This property will only work with synchronous plugins. If the processor
+ * contains any asynchronous plugins it will throw an error.
+ *
+ * PostCSS runners should always use `LazyResult#then`.
+ */
+ get root(): RootNode
+
+ /**
+ * Returns the default string description of an object.
+ * Required to implement the Promise interface.
+ */
+ get [Symbol.toStringTag](): string
+
+ /**
+ * @param processor Processor used for this transformation.
+ * @param css CSS to parse and transform.
+ * @param opts Options from the `Processor#process` or `Root#toResult`.
+ */
+ constructor(processor: Processor, css: string, opts: ResultOptions)
+
+ /**
+ * Run plugin in async way and return `Result`.
+ *
+ * @return Result with output content.
+ */
+ async(): Promise<Result<RootNode>>
+
+ /**
+ * Run plugin in sync way and return `Result`.
+ *
+ * @return Result with output content.
+ */
+ sync(): Result<RootNode>
+
+ /**
+ * Alias for the `LazyResult#css` property.
+ *
+ * ```js
+ * lazy + '' === lazy.css
+ * ```
+ *
+ * @return Output CSS.
+ */
+ toString(): string
+
+ /**
+ * Processes input CSS through synchronous plugins
+ * and calls `Result#warnings`.
+ *
+ * @return Warnings from plugins.
+ */
+ warnings(): Warning[]
+}
+
+declare class LazyResult<
+ RootNode = Document | Root
+> extends LazyResult_<RootNode> {}
+
+export = LazyResult
diff --git a/frontend/node_modules/postcss/lib/lazy-result.js b/frontend/node_modules/postcss/lib/lazy-result.js
new file mode 100644
index 0000000..1ea52b8
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/lazy-result.js
@@ -0,0 +1,550 @@
+'use strict'
+
+let Container = require('./container')
+let Document = require('./document')
+let MapGenerator = require('./map-generator')
+let parse = require('./parse')
+let Result = require('./result')
+let Root = require('./root')
+let stringify = require('./stringify')
+let { isClean, my } = require('./symbols')
+let warnOnce = require('./warn-once')
+
+const TYPE_TO_CLASS_NAME = {
+ atrule: 'AtRule',
+ comment: 'Comment',
+ decl: 'Declaration',
+ document: 'Document',
+ root: 'Root',
+ rule: 'Rule'
+}
+
+const PLUGIN_PROPS = {
+ AtRule: true,
+ AtRuleExit: true,
+ Comment: true,
+ CommentExit: true,
+ Declaration: true,
+ DeclarationExit: true,
+ Document: true,
+ DocumentExit: true,
+ Once: true,
+ OnceExit: true,
+ postcssPlugin: true,
+ prepare: true,
+ Root: true,
+ RootExit: true,
+ Rule: true,
+ RuleExit: true
+}
+
+const NOT_VISITORS = {
+ Once: true,
+ postcssPlugin: true,
+ prepare: true
+}
+
+const CHILDREN = 0
+
+function isPromise(obj) {
+ return typeof obj === 'object' && typeof obj.then === 'function'
+}
+
+function getEvents(node) {
+ let key = false
+ let type = TYPE_TO_CLASS_NAME[node.type]
+ if (node.type === 'decl') {
+ key = node.prop.toLowerCase()
+ } else if (node.type === 'atrule') {
+ key = node.name.toLowerCase()
+ }
+
+ if (key && node.append) {
+ return [
+ type,
+ type + '-' + key,
+ CHILDREN,
+ type + 'Exit',
+ type + 'Exit-' + key
+ ]
+ } else if (key) {
+ return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
+ } else if (node.append) {
+ return [type, CHILDREN, type + 'Exit']
+ } else {
+ return [type, type + 'Exit']
+ }
+}
+
+function toStack(node) {
+ let events
+ if (node.type === 'document') {
+ events = ['Document', CHILDREN, 'DocumentExit']
+ } else if (node.type === 'root') {
+ events = ['Root', CHILDREN, 'RootExit']
+ } else {
+ events = getEvents(node)
+ }
+
+ return {
+ eventIndex: 0,
+ events,
+ iterator: 0,
+ node,
+ visitorIndex: 0,
+ visitors: []
+ }
+}
+
+function cleanMarks(node) {
+ node[isClean] = false
+ if (node.nodes) node.nodes.forEach(i => cleanMarks(i))
+ return node
+}
+
+let postcss = {}
+
+class LazyResult {
+ 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'
+ }
+
+ constructor(processor, css, opts) {
+ this.stringified = false
+ this.processed = false
+
+ let root
+ if (
+ typeof css === 'object' &&
+ css !== null &&
+ (css.type === 'root' || css.type === 'document')
+ ) {
+ root = cleanMarks(css)
+ } else if (css instanceof LazyResult || css instanceof Result) {
+ root = cleanMarks(css.root)
+ if (css.map) {
+ if (typeof opts.map === 'undefined') opts.map = {}
+ if (!opts.map.inline) opts.map.inline = false
+ opts.map.prev = css.map
+ }
+ } else {
+ let parser = parse
+ if (opts.syntax) parser = opts.syntax.parse
+ if (opts.parser) parser = opts.parser
+ if (parser.parse) parser = parser.parse
+
+ try {
+ root = parser(css, opts)
+ } catch (error) {
+ this.processed = true
+ this.error = error
+ }
+
+ if (root && !root[my]) {
+ /* c8 ignore next 2 */
+ Container.rebuild(root)
+ }
+ }
+
+ this.result = new Result(processor, root, opts)
+ this.helpers = { ...postcss, postcss, result: this.result }
+ this.plugins = this.processor.plugins.map(plugin => {
+ if (typeof plugin === 'object' && plugin.prepare) {
+ return { ...plugin, ...plugin.prepare(this.result) }
+ } else {
+ return plugin
+ }
+ })
+ }
+
+ async() {
+ if (this.error) return Promise.reject(this.error)
+ if (this.processed) return Promise.resolve(this.result)
+ if (!this.processing) {
+ this.processing = this.runAsync()
+ }
+ return this.processing
+ }
+
+ catch(onRejected) {
+ return this.async().catch(onRejected)
+ }
+
+ finally(onFinally) {
+ return this.async().then(onFinally, onFinally)
+ }
+
+ getAsyncError() {
+ throw new Error('Use process(css).then(cb) to work with async plugins')
+ }
+
+ handleError(error, node) {
+ let plugin = this.result.lastPlugin
+ try {
+ if (node) node.addToError(error)
+ this.error = error
+ if (error.name === 'CssSyntaxError' && !error.plugin) {
+ error.plugin = plugin.postcssPlugin
+ error.setMessage()
+ } else if (plugin.postcssVersion) {
+ if (process.env.NODE_ENV !== 'production') {
+ let pluginName = plugin.postcssPlugin
+ let pluginVer = plugin.postcssVersion
+ let runtimeVer = this.result.processor.version
+ let a = pluginVer.split('.')
+ let b = runtimeVer.split('.')
+
+ if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
+ // eslint-disable-next-line no-console
+ console.error(
+ 'Unknown error from PostCSS plugin. Your current PostCSS ' +
+ 'version is ' +
+ runtimeVer +
+ ', but ' +
+ pluginName +
+ ' uses ' +
+ pluginVer +
+ '. Perhaps this is the source of the error below.'
+ )
+ }
+ }
+ }
+ } catch (err) {
+ /* c8 ignore next 3 */
+ // eslint-disable-next-line no-console
+ if (console && console.error) console.error(err)
+ }
+ return error
+ }
+
+ prepareVisitors() {
+ this.listeners = {}
+ let add = (plugin, type, cb) => {
+ if (!this.listeners[type]) this.listeners[type] = []
+ this.listeners[type].push([plugin, cb])
+ }
+ for (let plugin of this.plugins) {
+ if (typeof plugin === 'object') {
+ for (let event in plugin) {
+ if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
+ throw new Error(
+ `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
+ `Try to update PostCSS (${this.processor.version} now).`
+ )
+ }
+ if (!NOT_VISITORS[event]) {
+ if (typeof plugin[event] === 'object') {
+ for (let filter in plugin[event]) {
+ if (filter === '*') {
+ add(plugin, event, plugin[event][filter])
+ } else {
+ add(
+ plugin,
+ event + '-' + filter.toLowerCase(),
+ plugin[event][filter]
+ )
+ }
+ }
+ } else if (typeof plugin[event] === 'function') {
+ add(plugin, event, plugin[event])
+ }
+ }
+ }
+ }
+ }
+ this.hasListener = Object.keys(this.listeners).length > 0
+ }
+
+ async runAsync() {
+ this.plugin = 0
+ for (let i = 0; i < this.plugins.length; i++) {
+ let plugin = this.plugins[i]
+ let promise = this.runOnRoot(plugin)
+ if (isPromise(promise)) {
+ try {
+ await promise
+ } catch (error) {
+ throw this.handleError(error)
+ }
+ }
+ }
+
+ this.prepareVisitors()
+ if (this.hasListener) {
+ let root = this.result.root
+ while (!root[isClean]) {
+ root[isClean] = true
+ let stack = [toStack(root)]
+ while (stack.length > 0) {
+ let promise = this.visitTick(stack)
+ if (isPromise(promise)) {
+ try {
+ await promise
+ } catch (e) {
+ let node = stack[stack.length - 1].node
+ throw this.handleError(e, node)
+ }
+ }
+ }
+ }
+
+ if (this.listeners.OnceExit) {
+ for (let [plugin, visitor] of this.listeners.OnceExit) {
+ this.result.lastPlugin = plugin
+ try {
+ if (root.type === 'document') {
+ let roots = root.nodes.map(subRoot =>
+ visitor(subRoot, this.helpers)
+ )
+
+ await Promise.all(roots)
+ } else {
+ await visitor(root, this.helpers)
+ }
+ } catch (e) {
+ throw this.handleError(e)
+ }
+ }
+ }
+ }
+
+ this.processed = true
+ return this.stringify()
+ }
+
+ runOnRoot(plugin) {
+ this.result.lastPlugin = plugin
+ try {
+ if (typeof plugin === 'object' && plugin.Once) {
+ if (this.result.root.type === 'document') {
+ let roots = this.result.root.nodes.map(root =>
+ plugin.Once(root, this.helpers)
+ )
+
+ if (isPromise(roots[0])) {
+ return Promise.all(roots)
+ }
+
+ return roots
+ }
+
+ return plugin.Once(this.result.root, this.helpers)
+ } else if (typeof plugin === 'function') {
+ return plugin(this.result.root, this.result)
+ }
+ } catch (error) {
+ throw this.handleError(error)
+ }
+ }
+
+ stringify() {
+ if (this.error) throw this.error
+ if (this.stringified) return this.result
+ this.stringified = true
+
+ this.sync()
+
+ let opts = this.result.opts
+ let str = stringify
+ if (opts.syntax) str = opts.syntax.stringify
+ if (opts.stringifier) str = opts.stringifier
+ if (str.stringify) str = str.stringify
+
+ let map = new MapGenerator(str, this.result.root, this.result.opts)
+ let data = map.generate()
+ this.result.css = data[0]
+ this.result.map = data[1]
+
+ return this.result
+ }
+
+ sync() {
+ if (this.error) throw this.error
+ if (this.processed) return this.result
+ this.processed = true
+
+ if (this.processing) {
+ throw this.getAsyncError()
+ }
+
+ for (let plugin of this.plugins) {
+ let promise = this.runOnRoot(plugin)
+ if (isPromise(promise)) {
+ throw this.getAsyncError()
+ }
+ }
+
+ this.prepareVisitors()
+ if (this.hasListener) {
+ let root = this.result.root
+ while (!root[isClean]) {
+ root[isClean] = true
+ this.walkSync(root)
+ }
+ if (this.listeners.OnceExit) {
+ if (root.type === 'document') {
+ for (let subRoot of root.nodes) {
+ this.visitSync(this.listeners.OnceExit, subRoot)
+ }
+ } else {
+ this.visitSync(this.listeners.OnceExit, root)
+ }
+ }
+ }
+
+ return this.result
+ }
+
+ then(onFulfilled, onRejected) {
+ if (process.env.NODE_ENV !== 'production') {
+ if (!('from' in this.opts)) {
+ warnOnce(
+ 'Without `from` option PostCSS could generate wrong source map ' +
+ 'and will not find Browserslist config. Set it to CSS file path ' +
+ 'or to `undefined` to prevent this warning.'
+ )
+ }
+ }
+ return this.async().then(onFulfilled, onRejected)
+ }
+
+ toString() {
+ return this.css
+ }
+
+ visitSync(visitors, node) {
+ for (let [plugin, visitor] of visitors) {
+ this.result.lastPlugin = plugin
+ let promise
+ try {
+ promise = visitor(node, this.helpers)
+ } catch (e) {
+ throw this.handleError(e, node.proxyOf)
+ }
+ if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
+ return true
+ }
+ if (isPromise(promise)) {
+ throw this.getAsyncError()
+ }
+ }
+ }
+
+ visitTick(stack) {
+ let visit = stack[stack.length - 1]
+ let { node, visitors } = visit
+
+ if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
+ stack.pop()
+ return
+ }
+
+ if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
+ let [plugin, visitor] = visitors[visit.visitorIndex]
+ visit.visitorIndex += 1
+ if (visit.visitorIndex === visitors.length) {
+ visit.visitors = []
+ visit.visitorIndex = 0
+ }
+ this.result.lastPlugin = plugin
+ try {
+ return visitor(node.toProxy(), this.helpers)
+ } catch (e) {
+ throw this.handleError(e, node)
+ }
+ }
+
+ if (visit.iterator !== 0) {
+ let iterator = visit.iterator
+ let child
+ while ((child = node.nodes[node.indexes[iterator]])) {
+ node.indexes[iterator] += 1
+ if (!child[isClean]) {
+ child[isClean] = true
+ stack.push(toStack(child))
+ return
+ }
+ }
+ visit.iterator = 0
+ delete node.indexes[iterator]
+ }
+
+ let events = visit.events
+ while (visit.eventIndex < events.length) {
+ let event = events[visit.eventIndex]
+ visit.eventIndex += 1
+ if (event === CHILDREN) {
+ if (node.nodes && node.nodes.length) {
+ node[isClean] = true
+ visit.iterator = node.getIterator()
+ }
+ return
+ } else if (this.listeners[event]) {
+ visit.visitors = this.listeners[event]
+ return
+ }
+ }
+ stack.pop()
+ }
+
+ walkSync(node) {
+ node[isClean] = true
+ let events = getEvents(node)
+ for (let event of events) {
+ if (event === CHILDREN) {
+ if (node.nodes) {
+ node.each(child => {
+ if (!child[isClean]) this.walkSync(child)
+ })
+ }
+ } else {
+ let visitors = this.listeners[event]
+ if (visitors) {
+ if (this.visitSync(visitors, node.toProxy())) return
+ }
+ }
+ }
+ }
+
+ warnings() {
+ return this.sync().warnings()
+ }
+}
+
+LazyResult.registerPostcss = dependant => {
+ postcss = dependant
+}
+
+module.exports = LazyResult
+LazyResult.default = LazyResult
+
+Root.registerLazyResult(LazyResult)
+Document.registerLazyResult(LazyResult)
diff --git a/frontend/node_modules/postcss/lib/list.d.ts b/frontend/node_modules/postcss/lib/list.d.ts
new file mode 100644
index 0000000..e262ad3
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/list.d.ts
@@ -0,0 +1,60 @@
+declare namespace list {
+ type List = {
+ /**
+ * Safely splits comma-separated values (such as those for `transition-*`
+ * and `background` properties).
+ *
+ * ```js
+ * Once (root, { list }) {
+ * list.comma('black, linear-gradient(white, black)')
+ * //=> ['black', 'linear-gradient(white, black)']
+ * }
+ * ```
+ *
+ * @param str Comma-separated values.
+ * @return Split values.
+ */
+ comma(str: string): string[]
+
+ default: List
+
+ /**
+ * Safely splits space-separated values (such as those for `background`,
+ * `border-radius`, and other shorthand properties).
+ *
+ * ```js
+ * Once (root, { list }) {
+ * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
+ * }
+ * ```
+ *
+ * @param str Space-separated values.
+ * @return Split values.
+ */
+ space(str: string): string[]
+
+ /**
+ * Safely splits values.
+ *
+ * ```js
+ * Once (root, { list }) {
+ * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
+ * }
+ * ```
+ *
+ * @param string separated values.
+ * @param separators array of separators.
+ * @param last boolean indicator.
+ * @return Split values.
+ */
+ split(
+ string: string,
+ separators: readonly string[],
+ last: boolean
+ ): string[]
+ }
+}
+
+declare const list: list.List
+
+export = list
diff --git a/frontend/node_modules/postcss/lib/list.js b/frontend/node_modules/postcss/lib/list.js
new file mode 100644
index 0000000..1b31f98
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/list.js
@@ -0,0 +1,58 @@
+'use strict'
+
+let list = {
+ comma(string) {
+ return list.split(string, [','], true)
+ },
+
+ space(string) {
+ let spaces = [' ', '\n', '\t']
+ return list.split(string, spaces)
+ },
+
+ split(string, separators, last) {
+ let array = []
+ let current = ''
+ let split = false
+
+ let func = 0
+ let inQuote = false
+ let prevQuote = ''
+ let escape = false
+
+ for (let letter of string) {
+ if (escape) {
+ escape = false
+ } else if (letter === '\\') {
+ escape = true
+ } else if (inQuote) {
+ if (letter === prevQuote) {
+ inQuote = false
+ }
+ } else if (letter === '"' || letter === "'") {
+ inQuote = true
+ prevQuote = letter
+ } else if (letter === '(') {
+ func += 1
+ } else if (letter === ')') {
+ if (func > 0) func -= 1
+ } else if (func === 0) {
+ if (separators.includes(letter)) split = true
+ }
+
+ if (split) {
+ if (current !== '') array.push(current.trim())
+ current = ''
+ split = false
+ } else {
+ current += letter
+ }
+ }
+
+ if (last || current !== '') array.push(current.trim())
+ return array
+ }
+}
+
+module.exports = list
+list.default = list
diff --git a/frontend/node_modules/postcss/lib/map-generator.js b/frontend/node_modules/postcss/lib/map-generator.js
new file mode 100644
index 0000000..89069d3
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/map-generator.js
@@ -0,0 +1,368 @@
+'use strict'
+
+let { dirname, relative, resolve, sep } = require('path')
+let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
+let { pathToFileURL } = require('url')
+
+let Input = require('./input')
+
+let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
+let pathAvailable = Boolean(dirname && resolve && relative && sep)
+
+class MapGenerator {
+ constructor(stringify, root, opts, cssString) {
+ this.stringify = stringify
+ this.mapOpts = opts.map || {}
+ this.root = root
+ this.opts = opts
+ this.css = cssString
+ this.originalCSS = cssString
+ this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
+
+ this.memoizedFileURLs = new Map()
+ this.memoizedPaths = new Map()
+ this.memoizedURLs = new Map()
+ }
+
+ addAnnotation() {
+ let content
+
+ if (this.isInline()) {
+ content =
+ 'data:application/json;base64,' + this.toBase64(this.map.toString())
+ } else if (typeof this.mapOpts.annotation === 'string') {
+ content = this.mapOpts.annotation
+ } else if (typeof this.mapOpts.annotation === 'function') {
+ content = this.mapOpts.annotation(this.opts.to, this.root)
+ } else {
+ content = this.outputFile() + '.map'
+ }
+ let eol = '\n'
+ if (this.css.includes('\r\n')) eol = '\r\n'
+
+ this.css += eol + '/*# sourceMappingURL=' + content + ' */'
+ }
+
+ applyPrevMaps() {
+ for (let prev of this.previous()) {
+ let from = this.toUrl(this.path(prev.file))
+ let root = prev.root || dirname(prev.file)
+ let map
+
+ if (this.mapOpts.sourcesContent === false) {
+ map = new SourceMapConsumer(prev.text)
+ if (map.sourcesContent) {
+ map.sourcesContent = null
+ }
+ } else {
+ map = prev.consumer()
+ }
+
+ this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
+ }
+ }
+
+ clearAnnotation() {
+ if (this.mapOpts.annotation === false) return
+
+ if (this.root) {
+ let node
+ for (let i = this.root.nodes.length - 1; i >= 0; i--) {
+ node = this.root.nodes[i]
+ if (node.type !== 'comment') continue
+ if (node.text.startsWith('# sourceMappingURL=')) {
+ this.root.removeChild(i)
+ }
+ }
+ } else if (this.css) {
+ this.css = this.css.replace(/\n*\/\*#[\S\s]*?\*\/$/gm, '')
+ }
+ }
+
+ generate() {
+ this.clearAnnotation()
+ if (pathAvailable && sourceMapAvailable && this.isMap()) {
+ return this.generateMap()
+ } else {
+ let result = ''
+ this.stringify(this.root, i => {
+ result += i
+ })
+ return [result]
+ }
+ }
+
+ generateMap() {
+ if (this.root) {
+ this.generateString()
+ } else if (this.previous().length === 1) {
+ let prev = this.previous()[0].consumer()
+ prev.file = this.outputFile()
+ this.map = SourceMapGenerator.fromSourceMap(prev, {
+ ignoreInvalidMapping: true
+ })
+ } else {
+ this.map = new SourceMapGenerator({
+ file: this.outputFile(),
+ ignoreInvalidMapping: true
+ })
+ this.map.addMapping({
+ generated: { column: 0, line: 1 },
+ original: { column: 0, line: 1 },
+ source: this.opts.from
+ ? this.toUrl(this.path(this.opts.from))
+ : '<no source>'
+ })
+ }
+
+ if (this.isSourcesContent()) this.setSourcesContent()
+ if (this.root && this.previous().length > 0) this.applyPrevMaps()
+ if (this.isAnnotation()) this.addAnnotation()
+
+ if (this.isInline()) {
+ return [this.css]
+ } else {
+ return [this.css, this.map]
+ }
+ }
+
+ generateString() {
+ this.css = ''
+ this.map = new SourceMapGenerator({
+ file: this.outputFile(),
+ ignoreInvalidMapping: true
+ })
+
+ let line = 1
+ let column = 1
+
+ let noSource = '<no source>'
+ let mapping = {
+ generated: { column: 0, line: 0 },
+ original: { column: 0, line: 0 },
+ source: ''
+ }
+
+ let last, lines
+ this.stringify(this.root, (str, node, type) => {
+ this.css += str
+
+ if (node && type !== 'end') {
+ mapping.generated.line = line
+ mapping.generated.column = column - 1
+ if (node.source && node.source.start) {
+ mapping.source = this.sourcePath(node)
+ mapping.original.line = node.source.start.line
+ mapping.original.column = node.source.start.column - 1
+ this.map.addMapping(mapping)
+ } else {
+ mapping.source = noSource
+ mapping.original.line = 1
+ mapping.original.column = 0
+ this.map.addMapping(mapping)
+ }
+ }
+
+ lines = str.match(/\n/g)
+ if (lines) {
+ line += lines.length
+ last = str.lastIndexOf('\n')
+ column = str.length - last
+ } else {
+ column += str.length
+ }
+
+ if (node && type !== 'start') {
+ let p = node.parent || { raws: {} }
+ let childless =
+ node.type === 'decl' || (node.type === 'atrule' && !node.nodes)
+ if (!childless || node !== p.last || p.raws.semicolon) {
+ if (node.source && node.source.end) {
+ mapping.source = this.sourcePath(node)
+ mapping.original.line = node.source.end.line
+ mapping.original.column = node.source.end.column - 1
+ mapping.generated.line = line
+ mapping.generated.column = column - 2
+ this.map.addMapping(mapping)
+ } else {
+ mapping.source = noSource
+ mapping.original.line = 1
+ mapping.original.column = 0
+ mapping.generated.line = line
+ mapping.generated.column = column - 1
+ this.map.addMapping(mapping)
+ }
+ }
+ }
+ })
+ }
+
+ isAnnotation() {
+ if (this.isInline()) {
+ return true
+ }
+ if (typeof this.mapOpts.annotation !== 'undefined') {
+ return this.mapOpts.annotation
+ }
+ if (this.previous().length) {
+ return this.previous().some(i => i.annotation)
+ }
+ return true
+ }
+
+ isInline() {
+ if (typeof this.mapOpts.inline !== 'undefined') {
+ return this.mapOpts.inline
+ }
+
+ let annotation = this.mapOpts.annotation
+ if (typeof annotation !== 'undefined' && annotation !== true) {
+ return false
+ }
+
+ if (this.previous().length) {
+ return this.previous().some(i => i.inline)
+ }
+ return true
+ }
+
+ isMap() {
+ if (typeof this.opts.map !== 'undefined') {
+ return !!this.opts.map
+ }
+ return this.previous().length > 0
+ }
+
+ isSourcesContent() {
+ if (typeof this.mapOpts.sourcesContent !== 'undefined') {
+ return this.mapOpts.sourcesContent
+ }
+ if (this.previous().length) {
+ return this.previous().some(i => i.withContent())
+ }
+ return true
+ }
+
+ outputFile() {
+ if (this.opts.to) {
+ return this.path(this.opts.to)
+ } else if (this.opts.from) {
+ return this.path(this.opts.from)
+ } else {
+ return 'to.css'
+ }
+ }
+
+ path(file) {
+ if (this.mapOpts.absolute) return file
+ if (file.charCodeAt(0) === 60 /* `<` */) return file
+ if (/^\w+:\/\//.test(file)) return file
+ let cached = this.memoizedPaths.get(file)
+ if (cached) return cached
+
+ let from = this.opts.to ? dirname(this.opts.to) : '.'
+
+ if (typeof this.mapOpts.annotation === 'string') {
+ from = dirname(resolve(from, this.mapOpts.annotation))
+ }
+
+ let path = relative(from, file)
+ this.memoizedPaths.set(file, path)
+
+ return path
+ }
+
+ previous() {
+ if (!this.previousMaps) {
+ this.previousMaps = []
+ if (this.root) {
+ this.root.walk(node => {
+ if (node.source && node.source.input.map) {
+ let map = node.source.input.map
+ if (!this.previousMaps.includes(map)) {
+ this.previousMaps.push(map)
+ }
+ }
+ })
+ } else {
+ let input = new Input(this.originalCSS, this.opts)
+ if (input.map) this.previousMaps.push(input.map)
+ }
+ }
+
+ return this.previousMaps
+ }
+
+ setSourcesContent() {
+ let already = {}
+ if (this.root) {
+ this.root.walk(node => {
+ if (node.source) {
+ let from = node.source.input.from
+ if (from && !already[from]) {
+ already[from] = true
+ let fromUrl = this.usesFileUrls
+ ? this.toFileUrl(from)
+ : this.toUrl(this.path(from))
+ this.map.setSourceContent(fromUrl, node.source.input.css)
+ }
+ }
+ })
+ } else if (this.css) {
+ let from = this.opts.from
+ ? this.toUrl(this.path(this.opts.from))
+ : '<no source>'
+ this.map.setSourceContent(from, this.css)
+ }
+ }
+
+ sourcePath(node) {
+ if (this.mapOpts.from) {
+ return this.toUrl(this.mapOpts.from)
+ } else if (this.usesFileUrls) {
+ return this.toFileUrl(node.source.input.from)
+ } else {
+ return this.toUrl(this.path(node.source.input.from))
+ }
+ }
+
+ toBase64(str) {
+ if (Buffer) {
+ return Buffer.from(str).toString('base64')
+ } else {
+ return window.btoa(unescape(encodeURIComponent(str)))
+ }
+ }
+
+ toFileUrl(path) {
+ let cached = this.memoizedFileURLs.get(path)
+ if (cached) return cached
+
+ if (pathToFileURL) {
+ let fileURL = pathToFileURL(path).toString()
+ this.memoizedFileURLs.set(path, fileURL)
+
+ return fileURL
+ } else {
+ throw new Error(
+ '`map.absolute` option is not available in this PostCSS build'
+ )
+ }
+ }
+
+ toUrl(path) {
+ let cached = this.memoizedURLs.get(path)
+ if (cached) return cached
+
+ if (sep === '\\') {
+ path = path.replace(/\\/g, '/')
+ }
+
+ let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent)
+ this.memoizedURLs.set(path, url)
+
+ return url
+ }
+}
+
+module.exports = MapGenerator
diff --git a/frontend/node_modules/postcss/lib/no-work-result.d.ts b/frontend/node_modules/postcss/lib/no-work-result.d.ts
new file mode 100644
index 0000000..094f30a
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/no-work-result.d.ts
@@ -0,0 +1,46 @@
+import LazyResult from './lazy-result.js'
+import { SourceMap } from './postcss.js'
+import Processor from './processor.js'
+import Result, { Message, ResultOptions } from './result.js'
+import Root from './root.js'
+import Warning from './warning.js'
+
+declare namespace NoWorkResult {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { NoWorkResult_ as default }
+}
+
+/**
+ * A Promise proxy for the result of PostCSS transformations.
+ * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root`
+ * are accessed. See the example below for details.
+ * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined.
+ *
+ * ```js
+ * const noWorkResult = postcss().process(css) // No plugins are defined.
+ * // CSS is not parsed
+ * let root = noWorkResult.root // now css is parsed because we accessed the root
+ * ```
+ */
+declare class NoWorkResult_ implements LazyResult<Root> {
+ catch: Promise<Result<Root>>['catch']
+ finally: Promise<Result<Root>>['finally']
+ then: Promise<Result<Root>>['then']
+ get content(): string
+ get css(): string
+ get map(): SourceMap
+ get messages(): Message[]
+ get opts(): ResultOptions
+ get processor(): Processor
+ get root(): Root
+ get [Symbol.toStringTag](): string
+ constructor(processor: Processor, css: string, opts: ResultOptions)
+ async(): Promise<Result<Root>>
+ sync(): Result<Root>
+ toString(): string
+ warnings(): Warning[]
+}
+
+declare class NoWorkResult extends NoWorkResult_ {}
+
+export = NoWorkResult
diff --git a/frontend/node_modules/postcss/lib/no-work-result.js b/frontend/node_modules/postcss/lib/no-work-result.js
new file mode 100644
index 0000000..dd46182
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/no-work-result.js
@@ -0,0 +1,138 @@
+'use strict'
+
+let MapGenerator = require('./map-generator')
+let parse = require('./parse')
+const Result = require('./result')
+let stringify = require('./stringify')
+let warnOnce = require('./warn-once')
+
+class NoWorkResult {
+ 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 root
+ let parser = parse
+
+ try {
+ root = parser(this._css, this._opts)
+ } catch (error) {
+ this.error = error
+ }
+
+ if (this.error) {
+ throw this.error
+ } else {
+ this._root = root
+ return root
+ }
+ }
+
+ get [Symbol.toStringTag]() {
+ return 'NoWorkResult'
+ }
+
+ constructor(processor, css, opts) {
+ css = css.toString()
+ this.stringified = false
+
+ this._processor = processor
+ this._css = css
+ this._opts = opts
+ this._map = undefined
+ let root
+
+ let str = stringify
+ this.result = new Result(this._processor, root, this._opts)
+ this.result.css = css
+
+ let self = this
+ Object.defineProperty(this.result, 'root', {
+ get() {
+ return self.root
+ }
+ })
+
+ let map = new MapGenerator(str, root, this._opts, css)
+ if (map.isMap()) {
+ let [generatedCSS, generatedMap] = map.generate()
+ if (generatedCSS) {
+ this.result.css = generatedCSS
+ }
+ if (generatedMap) {
+ this.result.map = generatedMap
+ }
+ } else {
+ map.clearAnnotation()
+ this.result.css = map.css
+ }
+ }
+
+ async() {
+ if (this.error) return Promise.reject(this.error)
+ return Promise.resolve(this.result)
+ }
+
+ catch(onRejected) {
+ return this.async().catch(onRejected)
+ }
+
+ finally(onFinally) {
+ return this.async().then(onFinally, onFinally)
+ }
+
+ sync() {
+ if (this.error) throw this.error
+ return this.result
+ }
+
+ then(onFulfilled, onRejected) {
+ if (process.env.NODE_ENV !== 'production') {
+ if (!('from' in this._opts)) {
+ warnOnce(
+ 'Without `from` option PostCSS could generate wrong source map ' +
+ 'and will not find Browserslist config. Set it to CSS file path ' +
+ 'or to `undefined` to prevent this warning.'
+ )
+ }
+ }
+
+ return this.async().then(onFulfilled, onRejected)
+ }
+
+ toString() {
+ return this._css
+ }
+
+ warnings() {
+ return []
+ }
+}
+
+module.exports = NoWorkResult
+NoWorkResult.default = NoWorkResult
diff --git a/frontend/node_modules/postcss/lib/node.d.ts b/frontend/node_modules/postcss/lib/node.d.ts
new file mode 100644
index 0000000..a09fe4d
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/node.d.ts
@@ -0,0 +1,556 @@
+import AtRule = require('./at-rule.js')
+import { AtRuleProps } from './at-rule.js'
+import Comment, { CommentProps } from './comment.js'
+import Container, { NewChild } from './container.js'
+import CssSyntaxError from './css-syntax-error.js'
+import Declaration, { DeclarationProps } from './declaration.js'
+import Document from './document.js'
+import Input from './input.js'
+import { Stringifier, Syntax } from './postcss.js'
+import Result from './result.js'
+import Root from './root.js'
+import Rule, { RuleProps } from './rule.js'
+import Warning, { WarningOptions } from './warning.js'
+
+declare namespace Node {
+ export type ChildNode = AtRule.default | Comment | Declaration | Rule
+
+ export type AnyNode =
+ | AtRule.default
+ | Comment
+ | Declaration
+ | Document
+ | Root
+ | Rule
+
+ export type ChildProps =
+ | AtRuleProps
+ | CommentProps
+ | DeclarationProps
+ | RuleProps
+
+ export interface Position {
+ /**
+ * Source line in file. In contrast to `offset` it starts from 1.
+ */
+ column: number
+
+ /**
+ * Source column in file.
+ */
+ line: number
+
+ /**
+ * Source offset in file. It starts from 0.
+ */
+ offset: number
+ }
+
+ export interface Range {
+ /**
+ * End position, exclusive.
+ */
+ end: Position
+
+ /**
+ * Start position, inclusive.
+ */
+ start: Position
+ }
+
+ /**
+ * Source represents an interface for the {@link Node.source} property.
+ */
+ export interface Source {
+ /**
+ * The inclusive ending position for the source
+ * code of a node.
+ *
+ * However, `end.offset` of a non `Root` node is the exclusive position.
+ * See https://github.com/postcss/postcss/pull/1879 for details.
+ *
+ * ```js
+ * const root = postcss.parse('a { color: black }')
+ * const a = root.first
+ * const color = a.first
+ *
+ * // The offset of `Root` node is the inclusive position
+ * css.source.end // { line: 1, column: 19, offset: 18 }
+ *
+ * // The offset of non `Root` node is the exclusive position
+ * a.source.end // { line: 1, column: 18, offset: 18 }
+ * color.source.end // { line: 1, column: 16, offset: 16 }
+ * ```
+ */
+ end?: Position
+
+ /**
+ * The source file from where a node has originated.
+ */
+ input: Input
+
+ /**
+ * The inclusive starting position for the source
+ * code of a node.
+ */
+ start?: Position
+ }
+
+ /**
+ * Interface represents an interface for an object received
+ * as parameter by Node class constructor.
+ */
+ export interface NodeProps {
+ source?: Source
+ }
+
+ export interface NodeErrorOptions {
+ /**
+ * An ending index inside a node's string that should be highlighted as
+ * source of error.
+ */
+ endIndex?: number
+ /**
+ * An index inside a node's string that should be highlighted as source
+ * of error.
+ */
+ index?: number
+ /**
+ * Plugin name that created this error. PostCSS will set it automatically.
+ */
+ plugin?: string
+ /**
+ * A word inside a node's string, that should be highlighted as source
+ * of error.
+ */
+ word?: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-shadow
+ class Node extends Node_ {}
+ export { Node as default }
+}
+
+/**
+ * It represents an abstract class that handles common
+ * methods for other CSS abstract syntax tree nodes.
+ *
+ * Any node that represents CSS selector or value should
+ * not extend the `Node` class.
+ */
+declare abstract class Node_ {
+ /**
+ * It represents parent of the current node.
+ *
+ * ```js
+ * root.nodes[0].parent === root //=> true
+ * ```
+ */
+ parent: Container | Document | undefined
+
+ /**
+ * It represents unnecessary whitespace and characters present
+ * in the css source code.
+ *
+ * Information to generate byte-to-byte equal node string as it was
+ * in the origin input.
+ *
+ * The properties of the raws object are decided by parser,
+ * the default parser uses the following properties:
+ *
+ * * `before`: the space symbols before the node. It also stores `*`
+ * and `_` symbols before the declaration (IE hack).
+ * * `after`: the space symbols after the last child of the node
+ * to the end of the node.
+ * * `between`: the symbols between the property and value
+ * for declarations, selector and `{` for rules, or last parameter
+ * and `{` for at-rules.
+ * * `semicolon`: contains true if the last child has
+ * an (optional) semicolon.
+ * * `afterName`: the space between the at-rule name and its parameters.
+ * * `left`: the space symbols between `/*` and the comment’s text.
+ * * `right`: the space symbols between the comment’s text
+ * and <code>*&#47;</code>.
+ * - `important`: the content of the important statement,
+ * if it is not just `!important`.
+ *
+ * PostCSS filters out the comments inside selectors, declaration values
+ * and at-rule parameters but it stores the origin content in raws.
+ *
+ * ```js
+ * const root = postcss.parse('a {\n color:black\n}')
+ * root.first.first.raws //=> { before: '\n ', between: ':' }
+ * ```
+ */
+ raws: any
+
+ /**
+ * It represents information related to origin of a node and is required
+ * for generating source maps.
+ *
+ * The nodes that are created manually using the public APIs
+ * provided by PostCSS will have `source` undefined and
+ * will be absent in the source map.
+ *
+ * For this reason, the plugin developer should consider
+ * duplicating nodes as the duplicate node will have the
+ * same source as the original node by default or assign
+ * source to a node created manually.
+ *
+ * ```js
+ * decl.source.input.from //=> '/home/ai/source.css'
+ * decl.source.start //=> { line: 10, column: 2 }
+ * decl.source.end //=> { line: 10, column: 12 }
+ * ```
+ *
+ * ```js
+ * // Incorrect method, source not specified!
+ * const prefixed = postcss.decl({
+ * prop: '-moz-' + decl.prop,
+ * value: decl.value
+ * })
+ *
+ * // Correct method, source is inherited when duplicating.
+ * const prefixed = decl.clone({
+ * prop: '-moz-' + decl.prop
+ * })
+ * ```
+ *
+ * ```js
+ * if (atrule.name === 'add-link') {
+ * const rule = postcss.rule({
+ * selector: 'a',
+ * source: atrule.source
+ * })
+ *
+ * atrule.parent.insertBefore(atrule, rule)
+ * }
+ * ```
+ */
+ source?: Node.Source
+
+ /**
+ * It represents type of a node in
+ * an abstract syntax tree.
+ *
+ * A type of node helps in identification of a node
+ * and perform operation based on it's type.
+ *
+ * ```js
+ * const declaration = new Declaration({
+ * prop: 'color',
+ * value: 'black'
+ * })
+ *
+ * declaration.type //=> 'decl'
+ * ```
+ */
+ type: string
+
+ constructor(defaults?: object)
+
+ /**
+ * Insert new node after current node to current node’s parent.
+ *
+ * Just alias for `node.parent.insertAfter(node, add)`.
+ *
+ * ```js
+ * decl.after('color: black')
+ * ```
+ *
+ * @param newNode New node.
+ * @return This node for methods chain.
+ */
+ after(
+ newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
+ ): this
+
+ /**
+ * It assigns properties to an existing node instance.
+ *
+ * ```js
+ * decl.assign({ prop: 'word-wrap', value: 'break-word' })
+ * ```
+ *
+ * @param overrides New properties to override the node.
+ *
+ * @return `this` for method chaining.
+ */
+ assign(overrides: object): this
+
+ /**
+ * Insert new node before current node to current node’s parent.
+ *
+ * Just alias for `node.parent.insertBefore(node, add)`.
+ *
+ * ```js
+ * decl.before('content: ""')
+ * ```
+ *
+ * @param newNode New node.
+ * @return This node for methods chain.
+ */
+ before(
+ newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
+ ): this
+
+ /**
+ * Clear the code style properties for the node and its children.
+ *
+ * ```js
+ * node.raws.before //=> ' '
+ * node.cleanRaws()
+ * node.raws.before //=> undefined
+ * ```
+ *
+ * @param keepBetween Keep the `raws.between` symbols.
+ */
+ cleanRaws(keepBetween?: boolean): void
+
+ /**
+ * It creates clone of an existing node, which includes all the properties
+ * and their values, that includes `raws` but not `type`.
+ *
+ * ```js
+ * decl.raws.before //=> "\n "
+ * const cloned = decl.clone({ prop: '-moz-' + decl.prop })
+ * cloned.raws.before //=> "\n "
+ * cloned.toString() //=> -moz-transform: scale(0)
+ * ```
+ *
+ * @param overrides New properties to override in the clone.
+ *
+ * @return Duplicate of the node instance.
+ */
+ clone(overrides?: object): this
+
+ /**
+ * Shortcut to clone the node and insert the resulting cloned node
+ * after the current node.
+ *
+ * @param overrides New properties to override in the clone.
+ * @return New node.
+ */
+ cloneAfter(overrides?: object): this
+
+ /**
+ * Shortcut to clone the node and insert the resulting cloned node
+ * before the current node.
+ *
+ * ```js
+ * decl.cloneBefore({ prop: '-moz-' + decl.prop })
+ * ```
+ *
+ * @param overrides Mew properties to override in the clone.
+ *
+ * @return New node
+ */
+ cloneBefore(overrides?: object): this
+
+ /**
+ * It creates an instance of the class `CssSyntaxError` and parameters passed
+ * to this method are assigned to the error instance.
+ *
+ * The error instance will have description for the
+ * error, original position of the node in the
+ * source, showing line and column number.
+ *
+ * If any previous map is present, it would be used
+ * to get original position of the source.
+ *
+ * The Previous Map here is referred to the source map
+ * generated by previous compilation, example: Less,
+ * Stylus and Sass.
+ *
+ * This method returns the error instance instead of
+ * throwing it.
+ *
+ * ```js
+ * if (!variables[name]) {
+ * throw decl.error(`Unknown variable ${name}`, { word: name })
+ * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
+ * // color: $black
+ * // a
+ * // ^
+ * // background: white
+ * }
+ * ```
+ *
+ * @param message Description for the error instance.
+ * @param options Options for the error instance.
+ *
+ * @return Error instance is returned.
+ */
+ error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError
+
+ /**
+ * Returns the next child of the node’s parent.
+ * Returns `undefined` if the current node is the last child.
+ *
+ * ```js
+ * if (comment.text === 'delete next') {
+ * const next = comment.next()
+ * if (next) {
+ * next.remove()
+ * }
+ * }
+ * ```
+ *
+ * @return Next node.
+ */
+ next(): Node.ChildNode | undefined
+
+ /**
+ * Get the position for a word or an index inside the node.
+ *
+ * @param opts Options.
+ * @return Position.
+ */
+ positionBy(opts?: Pick<WarningOptions, 'index' | 'word'>): Node.Position
+
+ /**
+ * Convert string index to line/column.
+ *
+ * @param index The symbol number in the node’s string.
+ * @return Symbol position in file.
+ */
+ positionInside(index: number): Node.Position
+
+ /**
+ * Returns the previous child of the node’s parent.
+ * Returns `undefined` if the current node is the first child.
+ *
+ * ```js
+ * const annotation = decl.prev()
+ * if (annotation.type === 'comment') {
+ * readAnnotation(annotation.text)
+ * }
+ * ```
+ *
+ * @return Previous node.
+ */
+ prev(): Node.ChildNode | undefined
+
+ /**
+ * Get the range for a word or start and end index inside the node.
+ * The start index is inclusive; the end index is exclusive.
+ *
+ * @param opts Options.
+ * @return Range.
+ */
+ rangeBy(
+ opts?: Pick<WarningOptions, 'end' | 'endIndex' | 'index' | 'start' | 'word'>
+ ): Node.Range
+
+ /**
+ * Returns a `raws` value. If the node is missing
+ * the code style property (because the node was manually built or cloned),
+ * PostCSS will try to autodetect the code style property by looking
+ * at other nodes in the tree.
+ *
+ * ```js
+ * const root = postcss.parse('a { background: white }')
+ * root.nodes[0].append({ prop: 'color', value: 'black' })
+ * root.nodes[0].nodes[1].raws.before //=> undefined
+ * root.nodes[0].nodes[1].raw('before') //=> ' '
+ * ```
+ *
+ * @param prop Name of code style property.
+ * @param defaultType Name of default value, it can be missed
+ * if the value is the same as prop.
+ * @return {string} Code style value.
+ */
+ raw(prop: string, defaultType?: string): string
+
+ /**
+ * It removes the node from its parent and deletes its parent property.
+ *
+ * ```js
+ * if (decl.prop.match(/^-webkit-/)) {
+ * decl.remove()
+ * }
+ * ```
+ *
+ * @return `this` for method chaining.
+ */
+ remove(): this
+
+ /**
+ * Inserts node(s) before the current node and removes the current node.
+ *
+ * ```js
+ * AtRule: {
+ * mixin: atrule => {
+ * atrule.replaceWith(mixinRules[atrule.params])
+ * }
+ * }
+ * ```
+ *
+ * @param nodes Mode(s) to replace current one.
+ * @return Current node to methods chain.
+ */
+ replaceWith(...nodes: NewChild[]): this
+
+ /**
+ * Finds the Root instance of the node’s tree.
+ *
+ * ```js
+ * root.nodes[0].nodes[0].root() === root
+ * ```
+ *
+ * @return Root parent.
+ */
+ root(): Root
+
+ /**
+ * Fix circular links on `JSON.stringify()`.
+ *
+ * @return Cleaned object.
+ */
+ toJSON(): object
+
+ /**
+ * It compiles the node to browser readable cascading style sheets string
+ * depending on it's type.
+ *
+ * ```js
+ * new Rule({ selector: 'a' }).toString() //=> "a {}"
+ * ```
+ *
+ * @param stringifier A syntax to use in string generation.
+ * @return CSS string of this node.
+ */
+ toString(stringifier?: Stringifier | Syntax): string
+
+ /**
+ * It is a wrapper for {@link Result#warn}, providing convenient
+ * way of generating warnings.
+ *
+ * ```js
+ * Declaration: {
+ * bad: (decl, { result }) => {
+ * decl.warn(result, 'Deprecated property: bad')
+ * }
+ * }
+ * ```
+ *
+ * @param result The `Result` instance that will receive the warning.
+ * @param message Description for the warning.
+ * @param options Options for the warning.
+ *
+ * @return `Warning` instance is returned
+ */
+ warn(result: Result, message: string, options?: WarningOptions): Warning
+
+ /**
+ * If this node isn't already dirty, marks it and its ancestors as such. This
+ * indicates to the LazyResult processor that the {@link Root} has been
+ * modified by the current plugin and may need to be processed again by other
+ * plugins.
+ */
+ protected markDirty(): void
+}
+
+declare class Node extends Node_ {}
+
+export = Node
diff --git a/frontend/node_modules/postcss/lib/node.js b/frontend/node_modules/postcss/lib/node.js
new file mode 100644
index 0000000..b403b71
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/node.js
@@ -0,0 +1,449 @@
+'use strict'
+
+let CssSyntaxError = require('./css-syntax-error')
+let Stringifier = require('./stringifier')
+let stringify = require('./stringify')
+let { isClean, my } = require('./symbols')
+
+function cloneNode(obj, parent) {
+ let cloned = new obj.constructor()
+
+ for (let i in obj) {
+ if (!Object.prototype.hasOwnProperty.call(obj, i)) {
+ /* c8 ignore next 2 */
+ continue
+ }
+ if (i === 'proxyCache') continue
+ let value = obj[i]
+ let type = typeof value
+
+ if (i === 'parent' && type === 'object') {
+ if (parent) cloned[i] = parent
+ } else if (i === 'source') {
+ cloned[i] = value
+ } else if (Array.isArray(value)) {
+ cloned[i] = value.map(j => cloneNode(j, cloned))
+ } else {
+ if (type === 'object' && value !== null) value = cloneNode(value)
+ cloned[i] = value
+ }
+ }
+
+ return cloned
+}
+
+function sourceOffset(inputCSS, position) {
+ // Not all custom syntaxes support `offset` in `source.start` and `source.end`
+ if (position && typeof position.offset !== 'undefined') {
+ return position.offset
+ }
+
+ let column = 1
+ let line = 1
+ let offset = 0
+
+ for (let i = 0; i < inputCSS.length; i++) {
+ if (line === position.line && column === position.column) {
+ offset = i
+ break
+ }
+
+ if (inputCSS[i] === '\n') {
+ column = 1
+ line += 1
+ } else {
+ column += 1
+ }
+ }
+
+ return offset
+}
+
+class Node {
+ get proxyOf() {
+ return this
+ }
+
+ constructor(defaults = {}) {
+ this.raws = {}
+ this[isClean] = false
+ this[my] = true
+
+ for (let name in defaults) {
+ if (name === 'nodes') {
+ this.nodes = []
+ for (let node of defaults[name]) {
+ if (typeof node.clone === 'function') {
+ this.append(node.clone())
+ } else {
+ this.append(node)
+ }
+ }
+ } else {
+ this[name] = defaults[name]
+ }
+ }
+ }
+
+ addToError(error) {
+ error.postcssNode = this
+ if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
+ let s = this.source
+ error.stack = error.stack.replace(
+ /\n\s{4}at /,
+ `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
+ )
+ }
+ return error
+ }
+
+ after(add) {
+ this.parent.insertAfter(this, add)
+ return this
+ }
+
+ assign(overrides = {}) {
+ for (let name in overrides) {
+ this[name] = overrides[name]
+ }
+ return this
+ }
+
+ before(add) {
+ this.parent.insertBefore(this, add)
+ return this
+ }
+
+ cleanRaws(keepBetween) {
+ delete this.raws.before
+ delete this.raws.after
+ if (!keepBetween) delete this.raws.between
+ }
+
+ clone(overrides = {}) {
+ let cloned = cloneNode(this)
+ for (let name in overrides) {
+ cloned[name] = overrides[name]
+ }
+ return cloned
+ }
+
+ cloneAfter(overrides = {}) {
+ let cloned = this.clone(overrides)
+ this.parent.insertAfter(this, cloned)
+ return cloned
+ }
+
+ cloneBefore(overrides = {}) {
+ let cloned = this.clone(overrides)
+ this.parent.insertBefore(this, cloned)
+ return cloned
+ }
+
+ error(message, opts = {}) {
+ if (this.source) {
+ let { end, start } = this.rangeBy(opts)
+ return this.source.input.error(
+ message,
+ { column: start.column, line: start.line },
+ { column: end.column, line: end.line },
+ opts
+ )
+ }
+ return new CssSyntaxError(message)
+ }
+
+ getProxyProcessor() {
+ return {
+ get(node, prop) {
+ if (prop === 'proxyOf') {
+ return node
+ } else if (prop === 'root') {
+ return () => node.root().toProxy()
+ } else {
+ return node[prop]
+ }
+ },
+
+ set(node, prop, value) {
+ if (node[prop] === value) return true
+ node[prop] = value
+ if (
+ prop === 'prop' ||
+ prop === 'value' ||
+ prop === 'name' ||
+ prop === 'params' ||
+ prop === 'important' ||
+ /* c8 ignore next */
+ prop === 'text'
+ ) {
+ node.markDirty()
+ }
+ return true
+ }
+ }
+ }
+
+ /* c8 ignore next 3 */
+ markClean() {
+ this[isClean] = true
+ }
+
+ markDirty() {
+ if (this[isClean]) {
+ this[isClean] = false
+ let next = this
+ while ((next = next.parent)) {
+ next[isClean] = false
+ }
+ }
+ }
+
+ next() {
+ if (!this.parent) return undefined
+ let index = this.parent.index(this)
+ return this.parent.nodes[index + 1]
+ }
+
+ positionBy(opts = {}) {
+ let pos = this.source.start
+ if (opts.index) {
+ pos = this.positionInside(opts.index)
+ } else if (opts.word) {
+ let inputString =
+ 'document' in this.source.input
+ ? this.source.input.document
+ : this.source.input.css
+ let stringRepresentation = inputString.slice(
+ sourceOffset(inputString, this.source.start),
+ sourceOffset(inputString, this.source.end)
+ )
+ let index = stringRepresentation.indexOf(opts.word)
+ if (index !== -1) pos = this.positionInside(index)
+ }
+ return pos
+ }
+
+ positionInside(index) {
+ let column = this.source.start.column
+ let line = this.source.start.line
+ let inputString =
+ 'document' in this.source.input
+ ? this.source.input.document
+ : this.source.input.css
+ let offset = sourceOffset(inputString, this.source.start)
+ let end = offset + index
+
+ for (let i = offset; i < end; i++) {
+ if (inputString[i] === '\n') {
+ column = 1
+ line += 1
+ } else {
+ column += 1
+ }
+ }
+
+ return { column, line, offset: end }
+ }
+
+ prev() {
+ if (!this.parent) return undefined
+ let index = this.parent.index(this)
+ return this.parent.nodes[index - 1]
+ }
+
+ rangeBy(opts = {}) {
+ let inputString =
+ 'document' in this.source.input
+ ? this.source.input.document
+ : this.source.input.css
+ let start = {
+ column: this.source.start.column,
+ line: this.source.start.line,
+ offset: sourceOffset(inputString, this.source.start)
+ }
+ let end = this.source.end
+ ? {
+ column: this.source.end.column + 1,
+ line: this.source.end.line,
+ offset:
+ typeof this.source.end.offset === 'number'
+ ? // `source.end.offset` is exclusive, so we don't need to add 1
+ this.source.end.offset
+ : // Since line/column in this.source.end is inclusive,
+ // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
+ // So, we add 1 to convert it to exclusive.
+ sourceOffset(inputString, this.source.end) + 1
+ }
+ : {
+ column: start.column + 1,
+ line: start.line,
+ offset: start.offset + 1
+ }
+
+ if (opts.word) {
+ let stringRepresentation = inputString.slice(
+ sourceOffset(inputString, this.source.start),
+ sourceOffset(inputString, this.source.end)
+ )
+ let index = stringRepresentation.indexOf(opts.word)
+ if (index !== -1) {
+ start = this.positionInside(index)
+ end = this.positionInside(index + opts.word.length)
+ }
+ } else {
+ if (opts.start) {
+ start = {
+ column: opts.start.column,
+ line: opts.start.line,
+ offset: sourceOffset(inputString, opts.start)
+ }
+ } else if (opts.index) {
+ start = this.positionInside(opts.index)
+ }
+
+ if (opts.end) {
+ end = {
+ column: opts.end.column,
+ line: opts.end.line,
+ offset: sourceOffset(inputString, opts.end)
+ }
+ } else if (typeof opts.endIndex === 'number') {
+ end = this.positionInside(opts.endIndex)
+ } else if (opts.index) {
+ end = this.positionInside(opts.index + 1)
+ }
+ }
+
+ if (
+ end.line < start.line ||
+ (end.line === start.line && end.column <= start.column)
+ ) {
+ end = {
+ column: start.column + 1,
+ line: start.line,
+ offset: start.offset + 1
+ }
+ }
+
+ return { end, start }
+ }
+
+ raw(prop, defaultType) {
+ let str = new Stringifier()
+ return str.raw(this, prop, defaultType)
+ }
+
+ remove() {
+ if (this.parent) {
+ this.parent.removeChild(this)
+ }
+ this.parent = undefined
+ return this
+ }
+
+ replaceWith(...nodes) {
+ if (this.parent) {
+ let bookmark = this
+ let foundSelf = false
+ for (let node of nodes) {
+ if (node === this) {
+ foundSelf = true
+ } else if (foundSelf) {
+ this.parent.insertAfter(bookmark, node)
+ bookmark = node
+ } else {
+ this.parent.insertBefore(bookmark, node)
+ }
+ }
+
+ if (!foundSelf) {
+ this.remove()
+ }
+ }
+
+ return this
+ }
+
+ root() {
+ let result = this
+ while (result.parent && result.parent.type !== 'document') {
+ result = result.parent
+ }
+ return result
+ }
+
+ toJSON(_, inputs) {
+ let fixed = {}
+ let emitInputs = inputs == null
+ inputs = inputs || new Map()
+ let inputsNextIndex = 0
+
+ for (let name in this) {
+ if (!Object.prototype.hasOwnProperty.call(this, name)) {
+ /* c8 ignore next 2 */
+ continue
+ }
+ if (name === 'parent' || name === 'proxyCache') continue
+ let value = this[name]
+
+ if (Array.isArray(value)) {
+ fixed[name] = value.map(i => {
+ if (typeof i === 'object' && i.toJSON) {
+ return i.toJSON(null, inputs)
+ } else {
+ return i
+ }
+ })
+ } else if (typeof value === 'object' && value.toJSON) {
+ fixed[name] = value.toJSON(null, inputs)
+ } else if (name === 'source') {
+ if (value == null) continue
+ let inputId = inputs.get(value.input)
+ if (inputId == null) {
+ inputId = inputsNextIndex
+ inputs.set(value.input, inputsNextIndex)
+ inputsNextIndex++
+ }
+ fixed[name] = {
+ end: value.end,
+ inputId,
+ start: value.start
+ }
+ } else {
+ fixed[name] = value
+ }
+ }
+
+ if (emitInputs) {
+ fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
+ }
+
+ return fixed
+ }
+
+ toProxy() {
+ if (!this.proxyCache) {
+ this.proxyCache = new Proxy(this, this.getProxyProcessor())
+ }
+ return this.proxyCache
+ }
+
+ toString(stringifier = stringify) {
+ if (stringifier.stringify) stringifier = stringifier.stringify
+ let result = ''
+ stringifier(this, i => {
+ result += i
+ })
+ return result
+ }
+
+ warn(result, text, opts = {}) {
+ let data = { node: this }
+ for (let i in opts) data[i] = opts[i]
+ return result.warn(text, data)
+ }
+}
+
+module.exports = Node
+Node.default = Node
diff --git a/frontend/node_modules/postcss/lib/parse.d.ts b/frontend/node_modules/postcss/lib/parse.d.ts
new file mode 100644
index 0000000..4c943a4
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/parse.d.ts
@@ -0,0 +1,9 @@
+import { Parser } from './postcss.js'
+
+interface Parse extends Parser {
+ default: Parse
+}
+
+declare const parse: Parse
+
+export = parse
diff --git a/frontend/node_modules/postcss/lib/parse.js b/frontend/node_modules/postcss/lib/parse.js
new file mode 100644
index 0000000..00a1037
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/parse.js
@@ -0,0 +1,42 @@
+'use strict'
+
+let Container = require('./container')
+let Input = require('./input')
+let Parser = require('./parser')
+
+function parse(css, opts) {
+ let input = new Input(css, opts)
+ let parser = new Parser(input)
+ try {
+ parser.parse()
+ } catch (e) {
+ if (process.env.NODE_ENV !== 'production') {
+ if (e.name === 'CssSyntaxError' && opts && opts.from) {
+ if (/\.scss$/i.test(opts.from)) {
+ e.message +=
+ '\nYou tried to parse SCSS with ' +
+ 'the standard CSS parser; ' +
+ 'try again with the postcss-scss parser'
+ } else if (/\.sass/i.test(opts.from)) {
+ e.message +=
+ '\nYou tried to parse Sass with ' +
+ 'the standard CSS parser; ' +
+ 'try again with the postcss-sass parser'
+ } else if (/\.less$/i.test(opts.from)) {
+ e.message +=
+ '\nYou tried to parse Less with ' +
+ 'the standard CSS parser; ' +
+ 'try again with the postcss-less parser'
+ }
+ }
+ }
+ throw e
+ }
+
+ return parser.root
+}
+
+module.exports = parse
+parse.default = parse
+
+Container.registerParse(parse)
diff --git a/frontend/node_modules/postcss/lib/parser.js b/frontend/node_modules/postcss/lib/parser.js
new file mode 100644
index 0000000..64fb5d8
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/parser.js
@@ -0,0 +1,611 @@
+'use strict'
+
+let AtRule = require('./at-rule')
+let Comment = require('./comment')
+let Declaration = require('./declaration')
+let Root = require('./root')
+let Rule = require('./rule')
+let tokenizer = require('./tokenize')
+
+const SAFE_COMMENT_NEIGHBOR = {
+ empty: true,
+ space: true
+}
+
+function findLastWithPosition(tokens) {
+ for (let i = tokens.length - 1; i >= 0; i--) {
+ let token = tokens[i]
+ let pos = token[3] || token[2]
+ if (pos) return pos
+ }
+}
+
+class Parser {
+ constructor(input) {
+ this.input = input
+
+ this.root = new Root()
+ this.current = this.root
+ this.spaces = ''
+ this.semicolon = false
+
+ this.createTokenizer()
+ this.root.source = { input, start: { column: 1, line: 1, offset: 0 } }
+ }
+
+ atrule(token) {
+ let node = new AtRule()
+ node.name = token[1].slice(1)
+ if (node.name === '') {
+ this.unnamedAtrule(node, token)
+ }
+ this.init(node, token[2])
+
+ let type
+ let prev
+ let shift
+ let last = false
+ let open = false
+ let params = []
+ let brackets = []
+
+ while (!this.tokenizer.endOfFile()) {
+ token = this.tokenizer.nextToken()
+ type = token[0]
+
+ if (type === '(' || type === '[') {
+ brackets.push(type === '(' ? ')' : ']')
+ } else if (type === '{' && brackets.length > 0) {
+ brackets.push('}')
+ } else if (type === brackets[brackets.length - 1]) {
+ brackets.pop()
+ }
+
+ if (brackets.length === 0) {
+ if (type === ';') {
+ node.source.end = this.getPosition(token[2])
+ node.source.end.offset++
+ this.semicolon = true
+ break
+ } else if (type === '{') {
+ open = true
+ break
+ } else if (type === '}') {
+ if (params.length > 0) {
+ shift = params.length - 1
+ prev = params[shift]
+ while (prev && prev[0] === 'space') {
+ prev = params[--shift]
+ }
+ if (prev) {
+ node.source.end = this.getPosition(prev[3] || prev[2])
+ node.source.end.offset++
+ }
+ }
+ this.end(token)
+ break
+ } else {
+ params.push(token)
+ }
+ } else {
+ params.push(token)
+ }
+
+ if (this.tokenizer.endOfFile()) {
+ last = true
+ break
+ }
+ }
+
+ node.raws.between = this.spacesAndCommentsFromEnd(params)
+ if (params.length) {
+ node.raws.afterName = this.spacesAndCommentsFromStart(params)
+ this.raw(node, 'params', params)
+ if (last) {
+ token = params[params.length - 1]
+ node.source.end = this.getPosition(token[3] || token[2])
+ node.source.end.offset++
+ this.spaces = node.raws.between
+ node.raws.between = ''
+ }
+ } else {
+ node.raws.afterName = ''
+ node.params = ''
+ }
+
+ if (open) {
+ node.nodes = []
+ this.current = node
+ }
+ }
+
+ checkMissedSemicolon(tokens) {
+ let colon = this.colon(tokens)
+ if (colon === false) return
+
+ let founded = 0
+ let token
+ for (let j = colon - 1; j >= 0; j--) {
+ token = tokens[j]
+ if (token[0] !== 'space') {
+ founded += 1
+ if (founded === 2) break
+ }
+ }
+ // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
+ // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
+ // And because we need it after that one we do +1 to get the next one.
+ throw this.input.error(
+ 'Missed semicolon',
+ token[0] === 'word' ? token[3] + 1 : token[2]
+ )
+ }
+
+ colon(tokens) {
+ let brackets = 0
+ let prev, token, type
+ for (let [i, element] of tokens.entries()) {
+ token = element
+ type = token[0]
+
+ if (type === '(') {
+ brackets += 1
+ }
+ if (type === ')') {
+ brackets -= 1
+ }
+ if (brackets === 0 && type === ':') {
+ if (!prev) {
+ this.doubleColon(token)
+ } else if (prev[0] === 'word' && prev[1] === 'progid') {
+ continue
+ } else {
+ return i
+ }
+ }
+
+ prev = token
+ }
+ return false
+ }
+
+ comment(token) {
+ let node = new Comment()
+ this.init(node, token[2])
+ node.source.end = this.getPosition(token[3] || token[2])
+ node.source.end.offset++
+
+ let text = token[1].slice(2, -2)
+ if (/^\s*$/.test(text)) {
+ node.text = ''
+ node.raws.left = text
+ node.raws.right = ''
+ } else {
+ let match = text.match(/^(\s*)([^]*\S)(\s*)$/)
+ node.text = match[2]
+ node.raws.left = match[1]
+ node.raws.right = match[3]
+ }
+ }
+
+ createTokenizer() {
+ this.tokenizer = tokenizer(this.input)
+ }
+
+ decl(tokens, customProperty) {
+ let node = new Declaration()
+ this.init(node, tokens[0][2])
+
+ let last = tokens[tokens.length - 1]
+ if (last[0] === ';') {
+ this.semicolon = true
+ tokens.pop()
+ }
+
+ node.source.end = this.getPosition(
+ last[3] || last[2] || findLastWithPosition(tokens)
+ )
+ node.source.end.offset++
+
+ while (tokens[0][0] !== 'word') {
+ if (tokens.length === 1) this.unknownWord(tokens)
+ node.raws.before += tokens.shift()[1]
+ }
+ node.source.start = this.getPosition(tokens[0][2])
+
+ node.prop = ''
+ while (tokens.length) {
+ let type = tokens[0][0]
+ if (type === ':' || type === 'space' || type === 'comment') {
+ break
+ }
+ node.prop += tokens.shift()[1]
+ }
+
+ node.raws.between = ''
+
+ let token
+ while (tokens.length) {
+ token = tokens.shift()
+
+ if (token[0] === ':') {
+ node.raws.between += token[1]
+ break
+ } else {
+ if (token[0] === 'word' && /\w/.test(token[1])) {
+ this.unknownWord([token])
+ }
+ node.raws.between += token[1]
+ }
+ }
+
+ if (node.prop[0] === '_' || node.prop[0] === '*') {
+ node.raws.before += node.prop[0]
+ node.prop = node.prop.slice(1)
+ }
+
+ let firstSpaces = []
+ let next
+ while (tokens.length) {
+ next = tokens[0][0]
+ if (next !== 'space' && next !== 'comment') break
+ firstSpaces.push(tokens.shift())
+ }
+
+ this.precheckMissedSemicolon(tokens)
+
+ for (let i = tokens.length - 1; i >= 0; i--) {
+ token = tokens[i]
+ if (token[1].toLowerCase() === '!important') {
+ node.important = true
+ let string = this.stringFrom(tokens, i)
+ string = this.spacesFromEnd(tokens) + string
+ if (string !== ' !important') node.raws.important = string
+ break
+ } else if (token[1].toLowerCase() === 'important') {
+ let cache = tokens.slice(0)
+ let str = ''
+ for (let j = i; j > 0; j--) {
+ let type = cache[j][0]
+ if (str.trim().startsWith('!') && type !== 'space') {
+ break
+ }
+ str = cache.pop()[1] + str
+ }
+ if (str.trim().startsWith('!')) {
+ node.important = true
+ node.raws.important = str
+ tokens = cache
+ }
+ }
+
+ if (token[0] !== 'space' && token[0] !== 'comment') {
+ break
+ }
+ }
+
+ let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment')
+
+ if (hasWord) {
+ node.raws.between += firstSpaces.map(i => i[1]).join('')
+ firstSpaces = []
+ }
+ this.raw(node, 'value', firstSpaces.concat(tokens), customProperty)
+
+ if (node.value.includes(':') && !customProperty) {
+ this.checkMissedSemicolon(tokens)
+ }
+ }
+
+ doubleColon(token) {
+ throw this.input.error(
+ 'Double colon',
+ { offset: token[2] },
+ { offset: token[2] + token[1].length }
+ )
+ }
+
+ emptyRule(token) {
+ let node = new Rule()
+ this.init(node, token[2])
+ node.selector = ''
+ node.raws.between = ''
+ this.current = node
+ }
+
+ end(token) {
+ if (this.current.nodes && this.current.nodes.length) {
+ this.current.raws.semicolon = this.semicolon
+ }
+ this.semicolon = false
+
+ this.current.raws.after = (this.current.raws.after || '') + this.spaces
+ this.spaces = ''
+
+ if (this.current.parent) {
+ this.current.source.end = this.getPosition(token[2])
+ this.current.source.end.offset++
+ this.current = this.current.parent
+ } else {
+ this.unexpectedClose(token)
+ }
+ }
+
+ endFile() {
+ if (this.current.parent) this.unclosedBlock()
+ if (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(token) {
+ this.spaces += token[1]
+ if (this.current.nodes) {
+ let prev = this.current.nodes[this.current.nodes.length - 1]
+ if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
+ prev.raws.ownSemicolon = this.spaces
+ this.spaces = ''
+ prev.source.end = this.getPosition(token[2])
+ prev.source.end.offset += prev.raws.ownSemicolon.length
+ }
+ }
+ }
+
+ // Helpers
+
+ getPosition(offset) {
+ let pos = this.input.fromOffset(offset)
+ return {
+ column: pos.col,
+ line: pos.line,
+ offset
+ }
+ }
+
+ init(node, offset) {
+ this.current.push(node)
+ node.source = {
+ input: this.input,
+ start: this.getPosition(offset)
+ }
+ node.raws.before = this.spaces
+ this.spaces = ''
+ if (node.type !== 'comment') this.semicolon = false
+ }
+
+ other(start) {
+ let end = false
+ let type = null
+ let colon = false
+ let bracket = null
+ let brackets = []
+ let customProperty = start[1].startsWith('--')
+
+ let tokens = []
+ let token = start
+ while (token) {
+ type = token[0]
+ tokens.push(token)
+
+ if (type === '(' || type === '[') {
+ if (!bracket) bracket = token
+ brackets.push(type === '(' ? ')' : ']')
+ } else if (customProperty && colon && type === '{') {
+ if (!bracket) bracket = token
+ brackets.push('}')
+ } else if (brackets.length === 0) {
+ if (type === ';') {
+ if (colon) {
+ this.decl(tokens, customProperty)
+ return
+ } else {
+ break
+ }
+ } else if (type === '{') {
+ this.rule(tokens)
+ return
+ } else if (type === '}') {
+ this.tokenizer.back(tokens.pop())
+ end = true
+ break
+ } else if (type === ':') {
+ colon = true
+ }
+ } else if (type === brackets[brackets.length - 1]) {
+ brackets.pop()
+ if (brackets.length === 0) bracket = null
+ }
+
+ token = this.tokenizer.nextToken()
+ }
+
+ if (this.tokenizer.endOfFile()) end = true
+ if (brackets.length > 0) this.unclosedBracket(bracket)
+
+ if (end && colon) {
+ if (!customProperty) {
+ while (tokens.length) {
+ token = tokens[tokens.length - 1][0]
+ if (token !== 'space' && token !== 'comment') break
+ this.tokenizer.back(tokens.pop())
+ }
+ }
+ this.decl(tokens, customProperty)
+ } else {
+ this.unknownWord(tokens)
+ }
+ }
+
+ parse() {
+ let token
+ while (!this.tokenizer.endOfFile()) {
+ token = this.tokenizer.nextToken()
+
+ switch (token[0]) {
+ case 'space':
+ this.spaces += token[1]
+ break
+
+ case ';':
+ this.freeSemicolon(token)
+ break
+
+ case '}':
+ this.end(token)
+ break
+
+ case 'comment':
+ this.comment(token)
+ break
+
+ case 'at-word':
+ this.atrule(token)
+ break
+
+ case '{':
+ this.emptyRule(token)
+ break
+
+ default:
+ this.other(token)
+ break
+ }
+ }
+ this.endFile()
+ }
+
+ precheckMissedSemicolon(/* tokens */) {
+ // Hook for Safe Parser
+ }
+
+ raw(node, prop, tokens, customProperty) {
+ let token, type
+ let length = tokens.length
+ let value = ''
+ let clean = true
+ let next, prev
+
+ for (let i = 0; i < length; i += 1) {
+ token = tokens[i]
+ type = token[0]
+ if (type === 'space' && i === length - 1 && !customProperty) {
+ clean = false
+ } else if (type === 'comment') {
+ prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty'
+ next = tokens[i + 1] ? tokens[i + 1][0] : 'empty'
+ if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
+ if (value.slice(-1) === ',') {
+ clean = false
+ } else {
+ value += token[1]
+ }
+ } else {
+ clean = false
+ }
+ } else {
+ value += token[1]
+ }
+ }
+ if (!clean) {
+ let raw = tokens.reduce((all, i) => all + i[1], '')
+ node.raws[prop] = { raw, value }
+ }
+ node[prop] = value
+ }
+
+ rule(tokens) {
+ tokens.pop()
+
+ let node = new Rule()
+ this.init(node, tokens[0][2])
+
+ node.raws.between = this.spacesAndCommentsFromEnd(tokens)
+ this.raw(node, 'selector', tokens)
+ this.current = node
+ }
+
+ spacesAndCommentsFromEnd(tokens) {
+ let lastTokenType
+ let spaces = ''
+ while (tokens.length) {
+ lastTokenType = tokens[tokens.length - 1][0]
+ if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
+ spaces = tokens.pop()[1] + spaces
+ }
+ return spaces
+ }
+
+ // Errors
+
+ spacesAndCommentsFromStart(tokens) {
+ let next
+ let spaces = ''
+ while (tokens.length) {
+ next = tokens[0][0]
+ if (next !== 'space' && next !== 'comment') break
+ spaces += tokens.shift()[1]
+ }
+ return spaces
+ }
+
+ spacesFromEnd(tokens) {
+ let lastTokenType
+ let spaces = ''
+ while (tokens.length) {
+ lastTokenType = tokens[tokens.length - 1][0]
+ if (lastTokenType !== 'space') break
+ spaces = tokens.pop()[1] + spaces
+ }
+ return spaces
+ }
+
+ stringFrom(tokens, from) {
+ let result = ''
+ for (let i = from; i < tokens.length; i++) {
+ result += tokens[i][1]
+ }
+ tokens.splice(from, tokens.length - from)
+ return result
+ }
+
+ unclosedBlock() {
+ let pos = this.current.source.start
+ throw this.input.error('Unclosed block', pos.line, pos.column)
+ }
+
+ unclosedBracket(bracket) {
+ throw this.input.error(
+ 'Unclosed bracket',
+ { offset: bracket[2] },
+ { offset: bracket[2] + 1 }
+ )
+ }
+
+ unexpectedClose(token) {
+ throw this.input.error(
+ 'Unexpected }',
+ { offset: token[2] },
+ { offset: token[2] + 1 }
+ )
+ }
+
+ unknownWord(tokens) {
+ throw this.input.error(
+ 'Unknown word ' + tokens[0][1],
+ { offset: tokens[0][2] },
+ { offset: tokens[0][2] + tokens[0][1].length }
+ )
+ }
+
+ unnamedAtrule(node, token) {
+ throw this.input.error(
+ 'At-rule without name',
+ { offset: token[2] },
+ { offset: token[2] + token[1].length }
+ )
+ }
+}
+
+module.exports = Parser
diff --git a/frontend/node_modules/postcss/lib/postcss.d.mts b/frontend/node_modules/postcss/lib/postcss.d.mts
new file mode 100644
index 0000000..d343f3c
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/postcss.d.mts
@@ -0,0 +1,69 @@
+export {
+ // Type-only exports
+ AcceptedPlugin,
+
+ AnyNode,
+ atRule,
+ AtRule,
+ AtRuleProps,
+ Builder,
+ ChildNode,
+ ChildProps,
+ comment,
+ Comment,
+ CommentProps,
+ Container,
+ ContainerProps,
+ CssSyntaxError,
+ decl,
+ Declaration,
+ DeclarationProps,
+ // postcss function / namespace
+ default,
+ document,
+ Document,
+ DocumentProps,
+ FilePosition,
+ fromJSON,
+ Helpers,
+ Input,
+
+ JSONHydrator,
+ // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here.
+ type LazyResult,
+ list,
+ Message,
+ Node,
+ NodeErrorOptions,
+ NodeProps,
+ OldPlugin,
+ parse,
+ Parser,
+ // @ts-expect-error This value exists, but it’s untyped.
+ plugin,
+ Plugin,
+ PluginCreator,
+ Position,
+ Postcss,
+ ProcessOptions,
+ Processor,
+ Result,
+ root,
+ Root,
+ RootProps,
+ rule,
+ Rule,
+ RuleProps,
+ Source,
+ SourceMap,
+ SourceMapOptions,
+ Stringifier,
+ // Value exports from postcss.mjs
+ stringify,
+ Syntax,
+ TransformCallback,
+ Transformer,
+ Warning,
+
+ WarningOptions
+} from './postcss.js'
diff --git a/frontend/node_modules/postcss/lib/postcss.d.ts b/frontend/node_modules/postcss/lib/postcss.d.ts
new file mode 100644
index 0000000..c5e3605
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/postcss.d.ts
@@ -0,0 +1,458 @@
+import { RawSourceMap, SourceMapGenerator } from 'source-map-js'
+
+import AtRule, { AtRuleProps } from './at-rule.js'
+import Comment, { CommentProps } from './comment.js'
+import Container, { ContainerProps, NewChild } from './container.js'
+import CssSyntaxError from './css-syntax-error.js'
+import Declaration, { DeclarationProps } from './declaration.js'
+import Document, { DocumentProps } from './document.js'
+import Input, { FilePosition } from './input.js'
+import LazyResult from './lazy-result.js'
+import list from './list.js'
+import Node, {
+ AnyNode,
+ ChildNode,
+ ChildProps,
+ NodeErrorOptions,
+ NodeProps,
+ Position,
+ Source
+} from './node.js'
+import Processor from './processor.js'
+import Result, { Message } from './result.js'
+import Root, { RootProps } from './root.js'
+import Rule, { RuleProps } from './rule.js'
+import Warning, { WarningOptions } from './warning.js'
+
+type DocumentProcessor = (
+ document: Document,
+ helper: postcss.Helpers
+) => Promise<void> | void
+type RootProcessor = (
+ root: Root,
+ helper: postcss.Helpers
+) => Promise<void> | void
+type DeclarationProcessor = (
+ decl: Declaration,
+ helper: postcss.Helpers
+) => Promise<void> | void
+type RuleProcessor = (
+ rule: Rule,
+ helper: postcss.Helpers
+) => Promise<void> | void
+type AtRuleProcessor = (
+ atRule: AtRule,
+ helper: postcss.Helpers
+) => Promise<void> | void
+type CommentProcessor = (
+ comment: Comment,
+ helper: postcss.Helpers
+) => Promise<void> | void
+
+interface Processors {
+ /**
+ * Will be called on all`AtRule` nodes.
+ *
+ * Will be called again on node or children changes.
+ */
+ AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
+
+ /**
+ * Will be called on all `AtRule` nodes, when all children will be processed.
+ *
+ * Will be called again on node or children changes.
+ */
+ AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
+
+ /**
+ * Will be called on all `Comment` nodes.
+ *
+ * Will be called again on node or children changes.
+ */
+ Comment?: CommentProcessor
+
+ /**
+ * Will be called on all `Comment` nodes after listeners
+ * for `Comment` event.
+ *
+ * Will be called again on node or children changes.
+ */
+ CommentExit?: CommentProcessor
+
+ /**
+ * Will be called on all `Declaration` nodes after listeners
+ * for `Declaration` event.
+ *
+ * Will be called again on node or children changes.
+ */
+ Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor
+
+ /**
+ * Will be called on all `Declaration` nodes.
+ *
+ * Will be called again on node or children changes.
+ */
+ DeclarationExit?:
+ | { [prop: string]: DeclarationProcessor }
+ | DeclarationProcessor
+
+ /**
+ * Will be called on `Document` node.
+ *
+ * Will be called again on children changes.
+ */
+ Document?: DocumentProcessor
+
+ /**
+ * Will be called on `Document` node, when all children will be processed.
+ *
+ * Will be called again on children changes.
+ */
+ DocumentExit?: DocumentProcessor
+
+ /**
+ * Will be called on `Root` node once.
+ */
+ Once?: RootProcessor
+
+ /**
+ * Will be called on `Root` node once, when all children will be processed.
+ */
+ OnceExit?: RootProcessor
+
+ /**
+ * Will be called on `Root` node.
+ *
+ * Will be called again on children changes.
+ */
+ Root?: RootProcessor
+
+ /**
+ * Will be called on `Root` node, when all children will be processed.
+ *
+ * Will be called again on children changes.
+ */
+ RootExit?: RootProcessor
+
+ /**
+ * Will be called on all `Rule` nodes.
+ *
+ * Will be called again on node or children changes.
+ */
+ Rule?: RuleProcessor
+
+ /**
+ * Will be called on all `Rule` nodes, when all children will be processed.
+ *
+ * Will be called again on node or children changes.
+ */
+ RuleExit?: RuleProcessor
+}
+
+declare namespace postcss {
+ export {
+ AnyNode,
+ AtRule,
+ AtRuleProps,
+ ChildNode,
+ ChildProps,
+ Comment,
+ CommentProps,
+ Container,
+ ContainerProps,
+ CssSyntaxError,
+ Declaration,
+ DeclarationProps,
+ Document,
+ DocumentProps,
+ FilePosition,
+ Input,
+ LazyResult,
+ list,
+ Message,
+ NewChild,
+ Node,
+ NodeErrorOptions,
+ NodeProps,
+ Position,
+ Processor,
+ Result,
+ Root,
+ RootProps,
+ Rule,
+ RuleProps,
+ Source,
+ Warning,
+ WarningOptions
+ }
+
+ export type SourceMap = {
+ toJSON(): RawSourceMap
+ } & SourceMapGenerator
+
+ export type Helpers = { postcss: Postcss; result: Result } & Postcss
+
+ export interface Plugin extends Processors {
+ postcssPlugin: string
+ prepare?: (result: Result) => Processors
+ }
+
+ export interface PluginCreator<PluginOptions> {
+ (opts?: PluginOptions): Plugin | Processor
+ postcss: true
+ }
+
+ export interface Transformer extends TransformCallback {
+ postcssPlugin: string
+ postcssVersion: string
+ }
+
+ export interface TransformCallback {
+ (root: Root, result: Result): Promise<void> | void
+ }
+
+ export interface OldPlugin<T> extends Transformer {
+ (opts?: T): Transformer
+ postcss: Transformer
+ }
+
+ export type AcceptedPlugin =
+ | {
+ postcss: Processor | TransformCallback
+ }
+ | OldPlugin<any>
+ | Plugin
+ | PluginCreator<any>
+ | Processor
+ | TransformCallback
+
+ export interface Parser<RootNode = Document | Root> {
+ (
+ css: { toString(): string } | string,
+ opts?: Pick<ProcessOptions, 'document' | 'from' | 'map'>
+ ): RootNode
+ }
+
+ export interface Builder {
+ (part: string, node?: AnyNode, type?: 'end' | 'start'): void
+ }
+
+ export interface Stringifier {
+ (node: AnyNode, builder: Builder): void
+ }
+
+ export interface JSONHydrator {
+ (data: object): Node
+ (data: object[]): Node[]
+ }
+
+ export interface Syntax<RootNode = Document | Root> {
+ /**
+ * Function to generate AST by string.
+ */
+ parse?: Parser<RootNode>
+
+ /**
+ * Class to generate string by AST.
+ */
+ stringify?: Stringifier
+ }
+
+ export interface SourceMapOptions {
+ /**
+ * Use absolute path in generated source map.
+ */
+ absolute?: boolean
+
+ /**
+ * Indicates that PostCSS should add annotation comments to the CSS.
+ * By default, PostCSS will always add a comment with a path
+ * to the source map. PostCSS will not add annotations to CSS files
+ * that do not contain any comments.
+ *
+ * By default, PostCSS presumes that you want to save the source map as
+ * `opts.to + '.map'` and will use this path in the annotation comment.
+ * A different path can be set by providing a string value for annotation.
+ *
+ * If you have set `inline: true`, annotation cannot be disabled.
+ */
+ annotation?: ((file: string, root: Root) => string) | boolean | string
+
+ /**
+ * Override `from` in map’s sources.
+ */
+ from?: string
+
+ /**
+ * Indicates that the source map should be embedded in the output CSS
+ * as a Base64-encoded comment. By default, it is `true`.
+ * But if all previous maps are external, not inline, PostCSS will not embed
+ * the map even if you do not set this option.
+ *
+ * If you have an inline source map, the result.map property will be empty,
+ * as the source map will be contained within the text of `result.css`.
+ */
+ inline?: boolean
+
+ /**
+ * Source map content from a previous processing step (e.g., Sass).
+ *
+ * PostCSS will try to read the previous source map
+ * automatically (based on comments within the source CSS), but you can use
+ * this option to identify it manually.
+ *
+ * If desired, you can omit the previous map with prev: `false`.
+ */
+ prev?: ((file: string) => string) | boolean | object | string
+
+ /**
+ * Indicates that PostCSS should set the origin content (e.g., Sass source)
+ * of the source map. By default, it is true. But if all previous maps do not
+ * contain sources content, PostCSS will also leave it out even if you
+ * do not set this option.
+ */
+ sourcesContent?: boolean
+ }
+
+ export interface ProcessOptions<RootNode = Document | Root> {
+ /**
+ * Input file if it is not simple CSS file, but HTML with <style> or JS with CSS-in-JS blocks.
+ */
+ document?: string
+
+ /**
+ * The path of the CSS source file. You should always set `from`,
+ * because it is used in source map generation and syntax error messages.
+ */
+ from?: string | undefined
+
+ /**
+ * Source map options
+ */
+ map?: boolean | SourceMapOptions
+
+ /**
+ * Function to generate AST by string.
+ */
+ parser?: Parser<RootNode> | Syntax<RootNode>
+
+ /**
+ * Class to generate string by AST.
+ */
+ stringifier?: Stringifier | Syntax<RootNode>
+
+ /**
+ * Object with parse and stringify.
+ */
+ syntax?: Syntax<RootNode>
+
+ /**
+ * The path where you'll put the output CSS file. You should always set `to`
+ * to generate correct source maps.
+ */
+ to?: string
+ }
+
+ export type Postcss = typeof postcss
+
+ /**
+ * Default function to convert a node tree into a CSS string.
+ */
+ export let stringify: Stringifier
+
+ /**
+ * Parses source css and returns a new `Root` or `Document` node,
+ * which contains the source CSS nodes.
+ *
+ * ```js
+ * // Simple CSS concatenation with source map support
+ * const root1 = postcss.parse(css1, { from: file1 })
+ * const root2 = postcss.parse(css2, { from: file2 })
+ * root1.append(root2).toResult().css
+ * ```
+ */
+ export let parse: Parser<Root>
+
+ /**
+ * Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes.
+ *
+ * ```js
+ * const json = root.toJSON()
+ * // save to file, send by network, etc
+ * const root2 = postcss.fromJSON(json)
+ * ```
+ */
+ export let fromJSON: JSONHydrator
+
+ /**
+ * Creates a new `Comment` node.
+ *
+ * @param defaults Properties for the new node.
+ * @return New comment node
+ */
+ export function comment(defaults?: CommentProps): Comment
+
+ /**
+ * Creates a new `AtRule` node.
+ *
+ * @param defaults Properties for the new node.
+ * @return New at-rule node.
+ */
+ export function atRule(defaults?: AtRuleProps): AtRule
+
+ /**
+ * Creates a new `Declaration` node.
+ *
+ * @param defaults Properties for the new node.
+ * @return New declaration node.
+ */
+ export function decl(defaults?: DeclarationProps): Declaration
+
+ /**
+ * Creates a new `Rule` node.
+ *
+ * @param default Properties for the new node.
+ * @return New rule node.
+ */
+ export function rule(defaults?: RuleProps): Rule
+
+ /**
+ * Creates a new `Root` node.
+ *
+ * @param defaults Properties for the new node.
+ * @return New root node.
+ */
+ export function root(defaults?: RootProps): Root
+
+ /**
+ * Creates a new `Document` node.
+ *
+ * @param defaults Properties for the new node.
+ * @return New document node.
+ */
+ export function document(defaults?: DocumentProps): Document
+
+ export { postcss as default }
+}
+
+/**
+ * Create a new `Processor` instance that will apply `plugins`
+ * as CSS processors.
+ *
+ * ```js
+ * let postcss = require('postcss')
+ *
+ * postcss(plugins).process(css, { from, to }).then(result => {
+ * console.log(result.css)
+ * })
+ * ```
+ *
+ * @param plugins PostCSS plugins.
+ * @return Processor to process multiple CSS.
+ */
+declare function postcss(
+ plugins?: readonly postcss.AcceptedPlugin[]
+): Processor
+declare function postcss(...plugins: postcss.AcceptedPlugin[]): Processor
+
+export = postcss
diff --git a/frontend/node_modules/postcss/lib/postcss.js b/frontend/node_modules/postcss/lib/postcss.js
new file mode 100644
index 0000000..8f0773b
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/postcss.js
@@ -0,0 +1,101 @@
+'use strict'
+
+let AtRule = require('./at-rule')
+let Comment = require('./comment')
+let Container = require('./container')
+let CssSyntaxError = require('./css-syntax-error')
+let Declaration = require('./declaration')
+let Document = require('./document')
+let fromJSON = require('./fromJSON')
+let Input = require('./input')
+let LazyResult = require('./lazy-result')
+let list = require('./list')
+let Node = require('./node')
+let parse = require('./parse')
+let Processor = require('./processor')
+let Result = require('./result.js')
+let Root = require('./root')
+let Rule = require('./rule')
+let stringify = require('./stringify')
+let Warning = require('./warning')
+
+function postcss(...plugins) {
+ if (plugins.length === 1 && Array.isArray(plugins[0])) {
+ plugins = plugins[0]
+ }
+ return new Processor(plugins)
+}
+
+postcss.plugin = function plugin(name, initializer) {
+ let warningPrinted = false
+ function creator(...args) {
+ // eslint-disable-next-line no-console
+ if (console && console.warn && !warningPrinted) {
+ warningPrinted = true
+ // eslint-disable-next-line no-console
+ console.warn(
+ name +
+ ': postcss.plugin was deprecated. Migration guide:\n' +
+ 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
+ )
+ if (process.env.LANG && process.env.LANG.startsWith('cn')) {
+ /* c8 ignore next 7 */
+ // eslint-disable-next-line no-console
+ console.warn(
+ name +
+ ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
+ 'https://www.w3ctech.com/topic/2226'
+ )
+ }
+ }
+ let transformer = initializer(...args)
+ transformer.postcssPlugin = name
+ transformer.postcssVersion = new Processor().version
+ return transformer
+ }
+
+ let cache
+ Object.defineProperty(creator, 'postcss', {
+ get() {
+ if (!cache) cache = creator()
+ return cache
+ }
+ })
+
+ creator.process = function (css, processOpts, pluginOpts) {
+ return postcss([creator(pluginOpts)]).process(css, processOpts)
+ }
+
+ return creator
+}
+
+postcss.stringify = stringify
+postcss.parse = parse
+postcss.fromJSON = fromJSON
+postcss.list = list
+
+postcss.comment = defaults => new Comment(defaults)
+postcss.atRule = defaults => new AtRule(defaults)
+postcss.decl = defaults => new Declaration(defaults)
+postcss.rule = defaults => new Rule(defaults)
+postcss.root = defaults => new Root(defaults)
+postcss.document = defaults => new Document(defaults)
+
+postcss.CssSyntaxError = CssSyntaxError
+postcss.Declaration = Declaration
+postcss.Container = Container
+postcss.Processor = Processor
+postcss.Document = Document
+postcss.Comment = Comment
+postcss.Warning = Warning
+postcss.AtRule = AtRule
+postcss.Result = Result
+postcss.Input = Input
+postcss.Rule = Rule
+postcss.Root = Root
+postcss.Node = Node
+
+LazyResult.registerPostcss(postcss)
+
+module.exports = postcss
+postcss.default = postcss
diff --git a/frontend/node_modules/postcss/lib/postcss.mjs b/frontend/node_modules/postcss/lib/postcss.mjs
new file mode 100644
index 0000000..3507598
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/postcss.mjs
@@ -0,0 +1,30 @@
+import postcss from './postcss.js'
+
+export default postcss
+
+export const stringify = postcss.stringify
+export const fromJSON = postcss.fromJSON
+export const plugin = postcss.plugin
+export const parse = postcss.parse
+export const list = postcss.list
+
+export const document = postcss.document
+export const comment = postcss.comment
+export const atRule = postcss.atRule
+export const rule = postcss.rule
+export const decl = postcss.decl
+export const root = postcss.root
+
+export const CssSyntaxError = postcss.CssSyntaxError
+export const Declaration = postcss.Declaration
+export const Container = postcss.Container
+export const Processor = postcss.Processor
+export const Document = postcss.Document
+export const Comment = postcss.Comment
+export const Warning = postcss.Warning
+export const AtRule = postcss.AtRule
+export const Result = postcss.Result
+export const Input = postcss.Input
+export const Rule = postcss.Rule
+export const Root = postcss.Root
+export const Node = postcss.Node
diff --git a/frontend/node_modules/postcss/lib/previous-map.d.ts b/frontend/node_modules/postcss/lib/previous-map.d.ts
new file mode 100644
index 0000000..23edeb5
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/previous-map.d.ts
@@ -0,0 +1,81 @@
+import { SourceMapConsumer } from 'source-map-js'
+
+import { ProcessOptions } from './postcss.js'
+
+declare namespace PreviousMap {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { PreviousMap_ as default }
+}
+
+/**
+ * Source map information from input CSS.
+ * For example, source map after Sass compiler.
+ *
+ * This class will automatically find source map in input CSS or in file system
+ * near input file (according `from` option).
+ *
+ * ```js
+ * const root = parse(css, { from: 'a.sass.css' })
+ * root.input.map //=> PreviousMap
+ * ```
+ */
+declare class PreviousMap_ {
+ /**
+ * `sourceMappingURL` content.
+ */
+ annotation?: string
+
+ /**
+ * The CSS source identifier. Contains `Input#file` if the user
+ * set the `from` option, or `Input#id` if they did not.
+ */
+ file?: string
+
+ /**
+ * Was source map inlined by data-uri to input CSS.
+ */
+ inline: boolean
+
+ /**
+ * Path to source map file.
+ */
+ mapFile?: string
+
+ /**
+ * The directory with source map file, if source map is in separated file.
+ */
+ root?: string
+
+ /**
+ * Source map file content.
+ */
+ text?: string
+
+ /**
+ * @param css Input CSS source.
+ * @param opts Process options.
+ */
+ constructor(css: string, opts?: ProcessOptions)
+
+ /**
+ * Create a instance of `SourceMapGenerator` class
+ * from the `source-map` library to work with source map information.
+ *
+ * It is lazy method, so it will create object only on first call
+ * and then it will use cache.
+ *
+ * @return Object with source map information.
+ */
+ consumer(): SourceMapConsumer
+
+ /**
+ * Does source map contains `sourcesContent` with input source text.
+ *
+ * @return Is `sourcesContent` present.
+ */
+ withContent(): boolean
+}
+
+declare class PreviousMap extends PreviousMap_ {}
+
+export = PreviousMap
diff --git a/frontend/node_modules/postcss/lib/previous-map.js b/frontend/node_modules/postcss/lib/previous-map.js
new file mode 100644
index 0000000..b123dcd
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/previous-map.js
@@ -0,0 +1,144 @@
+'use strict'
+
+let { existsSync, readFileSync } = require('fs')
+let { dirname, join } = require('path')
+let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
+
+function fromBase64(str) {
+ if (Buffer) {
+ return Buffer.from(str, 'base64').toString()
+ } else {
+ /* c8 ignore next 2 */
+ return window.atob(str)
+ }
+}
+
+class PreviousMap {
+ constructor(css, opts) {
+ if (opts.map === false) return
+ this.loadAnnotation(css)
+ this.inline = this.startWith(this.annotation, 'data:')
+
+ let prev = opts.map ? opts.map.prev : undefined
+ let text = this.loadMap(opts.from, prev)
+ if (!this.mapFile && opts.from) {
+ this.mapFile = opts.from
+ }
+ if (this.mapFile) this.root = dirname(this.mapFile)
+ if (text) this.text = text
+ }
+
+ consumer() {
+ if (!this.consumerCache) {
+ this.consumerCache = new SourceMapConsumer(this.text)
+ }
+ return this.consumerCache
+ }
+
+ decodeInline(text) {
+ let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/
+ let baseUri = /^data:application\/json;base64,/
+ let charsetUri = /^data:application\/json;charset=utf-?8,/
+ let uri = /^data:application\/json,/
+
+ let uriMatch = text.match(charsetUri) || text.match(uri)
+ if (uriMatch) {
+ return decodeURIComponent(text.substr(uriMatch[0].length))
+ }
+
+ let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri)
+ if (baseUriMatch) {
+ return fromBase64(text.substr(baseUriMatch[0].length))
+ }
+
+ let encoding = text.match(/data:application\/json;([^,]+),/)[1]
+ throw new Error('Unsupported source map encoding ' + encoding)
+ }
+
+ getAnnotationURL(sourceMapString) {
+ return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
+ }
+
+ isMap(map) {
+ if (typeof map !== 'object') return false
+ return (
+ typeof map.mappings === 'string' ||
+ typeof map._mappings === 'string' ||
+ Array.isArray(map.sections)
+ )
+ }
+
+ loadAnnotation(css) {
+ let comments = css.match(/\/\*\s*# sourceMappingURL=/g)
+ if (!comments) return
+
+ // sourceMappingURLs from comments, strings, etc.
+ let start = css.lastIndexOf(comments.pop())
+ let end = css.indexOf('*/', start)
+
+ if (start > -1 && end > -1) {
+ // Locate the last sourceMappingURL to avoid pickin
+ this.annotation = this.getAnnotationURL(css.substring(start, end))
+ }
+ }
+
+ loadFile(path) {
+ this.root = dirname(path)
+ if (existsSync(path)) {
+ this.mapFile = path
+ return readFileSync(path, 'utf-8').toString().trim()
+ }
+ }
+
+ loadMap(file, prev) {
+ if (prev === false) return false
+
+ if (prev) {
+ if (typeof prev === 'string') {
+ return prev
+ } else if (typeof prev === 'function') {
+ let prevPath = prev(file)
+ if (prevPath) {
+ let map = this.loadFile(prevPath)
+ if (!map) {
+ throw new Error(
+ 'Unable to load previous source map: ' + prevPath.toString()
+ )
+ }
+ return map
+ }
+ } else if (prev instanceof SourceMapConsumer) {
+ return SourceMapGenerator.fromSourceMap(prev).toString()
+ } else if (prev instanceof SourceMapGenerator) {
+ return prev.toString()
+ } else if (this.isMap(prev)) {
+ return JSON.stringify(prev)
+ } else {
+ throw new Error(
+ 'Unsupported previous source map format: ' + prev.toString()
+ )
+ }
+ } else if (this.inline) {
+ return this.decodeInline(this.annotation)
+ } else if (this.annotation) {
+ let map = this.annotation
+ if (file) map = join(dirname(file), map)
+ return this.loadFile(map)
+ }
+ }
+
+ startWith(string, start) {
+ if (!string) return false
+ return string.substr(0, start.length) === start
+ }
+
+ withContent() {
+ return !!(
+ this.consumer().sourcesContent &&
+ this.consumer().sourcesContent.length > 0
+ )
+ }
+}
+
+module.exports = PreviousMap
+PreviousMap.default = PreviousMap
diff --git a/frontend/node_modules/postcss/lib/processor.d.ts b/frontend/node_modules/postcss/lib/processor.d.ts
new file mode 100644
index 0000000..aa2942c
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/processor.d.ts
@@ -0,0 +1,115 @@
+import Document from './document.js'
+import LazyResult from './lazy-result.js'
+import NoWorkResult from './no-work-result.js'
+import {
+ AcceptedPlugin,
+ Plugin,
+ ProcessOptions,
+ TransformCallback,
+ Transformer
+} from './postcss.js'
+import Result from './result.js'
+import Root from './root.js'
+
+declare namespace Processor {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Processor_ as default }
+}
+
+/**
+ * Contains plugins to process CSS. Create one `Processor` instance,
+ * initialize its plugins, and then use that instance on numerous CSS files.
+ *
+ * ```js
+ * const processor = postcss([autoprefixer, postcssNested])
+ * processor.process(css1).then(result => console.log(result.css))
+ * processor.process(css2).then(result => console.log(result.css))
+ * ```
+ */
+declare class Processor_ {
+ /**
+ * Plugins added to this processor.
+ *
+ * ```js
+ * const processor = postcss([autoprefixer, postcssNested])
+ * processor.plugins.length //=> 2
+ * ```
+ */
+ plugins: (Plugin | TransformCallback | Transformer)[]
+
+ /**
+ * Current PostCSS version.
+ *
+ * ```js
+ * if (result.processor.version.split('.')[0] !== '6') {
+ * throw new Error('This plugin works only with PostCSS 6')
+ * }
+ * ```
+ */
+ version: string
+
+ /**
+ * @param plugins PostCSS plugins
+ */
+ constructor(plugins?: readonly AcceptedPlugin[])
+
+ /**
+ * Parses source CSS and returns a `LazyResult` Promise proxy.
+ * Because some plugins can be asynchronous it doesn’t make
+ * any transformations. Transformations will be applied
+ * in the `LazyResult` methods.
+ *
+ * ```js
+ * processor.process(css, { from: 'a.css', to: 'a.out.css' })
+ * .then(result => {
+ * console.log(result.css)
+ * })
+ * ```
+ *
+ * @param css String with input CSS or any object with a `toString()` method,
+ * like a Buffer. Optionally, send a `Result` instance
+ * and the processor will take the `Root` from it.
+ * @param opts Options.
+ * @return Promise proxy.
+ */
+ process(
+ css: { toString(): string } | LazyResult | Result | Root | string
+ ): LazyResult | NoWorkResult
+ process<RootNode extends Document | Root = Root>(
+ css: { toString(): string } | LazyResult | Result | Root | string,
+ options: ProcessOptions<RootNode>
+ ): LazyResult<RootNode>
+
+ /**
+ * Adds a plugin to be used as a CSS processor.
+ *
+ * PostCSS plugin can be in 4 formats:
+ * * A plugin in `Plugin` format.
+ * * A plugin creator function with `pluginCreator.postcss = true`.
+ * PostCSS will call this function without argument to get plugin.
+ * * A function. PostCSS will pass the function a {@link Root}
+ * as the first argument and current `Result` instance
+ * as the second.
+ * * Another `Processor` instance. PostCSS will copy plugins
+ * from that instance into this one.
+ *
+ * Plugins can also be added by passing them as arguments when creating
+ * a `postcss` instance (see [`postcss(plugins)`]).
+ *
+ * Asynchronous plugins should return a `Promise` instance.
+ *
+ * ```js
+ * const processor = postcss()
+ * .use(autoprefixer)
+ * .use(postcssNested)
+ * ```
+ *
+ * @param plugin PostCSS plugin or `Processor` with plugins.
+ * @return Current processor to make methods chain.
+ */
+ use(plugin: AcceptedPlugin): this
+}
+
+declare class Processor extends Processor_ {}
+
+export = Processor
diff --git a/frontend/node_modules/postcss/lib/processor.js b/frontend/node_modules/postcss/lib/processor.js
new file mode 100644
index 0000000..8493687
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/processor.js
@@ -0,0 +1,67 @@
+'use strict'
+
+let Document = require('./document')
+let LazyResult = require('./lazy-result')
+let NoWorkResult = require('./no-work-result')
+let Root = require('./root')
+
+class Processor {
+ constructor(plugins = []) {
+ this.version = '8.5.6'
+ this.plugins = this.normalize(plugins)
+ }
+
+ normalize(plugins) {
+ let normalized = []
+ for (let i of plugins) {
+ if (i.postcss === true) {
+ i = i()
+ } else if (i.postcss) {
+ i = i.postcss
+ }
+
+ if (typeof i === 'object' && Array.isArray(i.plugins)) {
+ normalized = normalized.concat(i.plugins)
+ } else if (typeof i === 'object' && i.postcssPlugin) {
+ normalized.push(i)
+ } else if (typeof i === 'function') {
+ normalized.push(i)
+ } else if (typeof i === 'object' && (i.parse || i.stringify)) {
+ if (process.env.NODE_ENV !== 'production') {
+ throw new Error(
+ 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
+ 'one of the syntax/parser/stringifier options as outlined ' +
+ 'in your PostCSS runner documentation.'
+ )
+ }
+ } else {
+ throw new Error(i + ' is not a PostCSS plugin')
+ }
+ }
+ return normalized
+ }
+
+ process(css, opts = {}) {
+ if (
+ !this.plugins.length &&
+ !opts.parser &&
+ !opts.stringifier &&
+ !opts.syntax
+ ) {
+ return new NoWorkResult(this, css, opts)
+ } else {
+ return new LazyResult(this, css, opts)
+ }
+ }
+
+ use(plugin) {
+ this.plugins = this.plugins.concat(this.normalize([plugin]))
+ return this
+ }
+}
+
+module.exports = Processor
+Processor.default = Processor
+
+Root.registerProcessor(Processor)
+Document.registerProcessor(Processor)
diff --git a/frontend/node_modules/postcss/lib/result.d.ts b/frontend/node_modules/postcss/lib/result.d.ts
new file mode 100644
index 0000000..3f52efb
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/result.d.ts
@@ -0,0 +1,205 @@
+import {
+ Document,
+ Node,
+ Plugin,
+ ProcessOptions,
+ Root,
+ SourceMap,
+ TransformCallback,
+ Warning,
+ WarningOptions
+} from './postcss.js'
+import Processor from './processor.js'
+
+declare namespace Result {
+ export interface Message {
+ [others: string]: any
+
+ /**
+ * Source PostCSS plugin name.
+ */
+ plugin?: string
+
+ /**
+ * Message type.
+ */
+ type: string
+ }
+
+ export interface ResultOptions extends ProcessOptions {
+ /**
+ * The CSS node that was the source of the warning.
+ */
+ node?: Node
+
+ /**
+ * Name of plugin that created this warning. `Result#warn` will fill it
+ * automatically with `Plugin#postcssPlugin` value.
+ */
+ plugin?: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Result_ as default }
+}
+
+/**
+ * Provides the result of the PostCSS transformations.
+ *
+ * A Result instance is returned by `LazyResult#then`
+ * or `Root#toResult` methods.
+ *
+ * ```js
+ * postcss([autoprefixer]).process(css).then(result => {
+ * console.log(result.css)
+ * })
+ * ```
+ *
+ * ```js
+ * const result2 = postcss.parse(css).toResult()
+ * ```
+ */
+declare class Result_<RootNode = Document | Root> {
+ /**
+ * A CSS string representing of `Result#root`.
+ *
+ * ```js
+ * postcss.parse('a{}').toResult().css //=> "a{}"
+ * ```
+ */
+ css: string
+
+ /**
+ * Last runned PostCSS plugin.
+ */
+ lastPlugin: Plugin | TransformCallback
+
+ /**
+ * An instance of `SourceMapGenerator` class from the `source-map` library,
+ * representing changes to the `Result#root` instance.
+ *
+ * ```js
+ * result.map.toJSON() //=> { version: 3, file: 'a.css', … }
+ * ```
+ *
+ * ```js
+ * if (result.map) {
+ * fs.writeFileSync(result.opts.to + '.map', result.map.toString())
+ * }
+ * ```
+ */
+ map: SourceMap
+
+ /**
+ * Contains messages from plugins (e.g., warnings or custom messages).
+ * Each message should have type and plugin properties.
+ *
+ * ```js
+ * AtRule: {
+ * import: (atRule, { result }) {
+ * const importedFile = parseImport(atRule)
+ * result.messages.push({
+ * type: 'dependency',
+ * plugin: 'postcss-import',
+ * file: importedFile,
+ * parent: result.opts.from
+ * })
+ * }
+ * }
+ * ```
+ */
+ messages: Result.Message[]
+
+ /**
+ * Options from the `Processor#process` or `Root#toResult` call
+ * that produced this Result instance.]
+ *
+ * ```js
+ * root.toResult(opts).opts === opts
+ * ```
+ */
+ opts: Result.ResultOptions
+
+ /**
+ * The Processor instance used for this transformation.
+ *
+ * ```js
+ * for (const plugin of result.processor.plugins) {
+ * if (plugin.postcssPlugin === 'postcss-bad') {
+ * throw 'postcss-good is incompatible with postcss-bad'
+ * }
+ * })
+ * ```
+ */
+ processor: Processor
+
+ /**
+ * Root node after all transformations.
+ *
+ * ```js
+ * root.toResult().root === root
+ * ```
+ */
+ root: RootNode
+
+ /**
+ * An alias for the `Result#css` property.
+ * Use it with syntaxes that generate non-CSS output.
+ *
+ * ```js
+ * result.css === result.content
+ * ```
+ */
+ get content(): string
+
+ /**
+ * @param processor Processor used for this transformation.
+ * @param root Root node after all transformations.
+ * @param opts Options from the `Processor#process` or `Root#toResult`.
+ */
+ constructor(processor: Processor, root: RootNode, opts: Result.ResultOptions)
+
+ /**
+ * Returns for `Result#css` content.
+ *
+ * ```js
+ * result + '' === result.css
+ * ```
+ *
+ * @return String representing of `Result#root`.
+ */
+ toString(): string
+
+ /**
+ * Creates an instance of `Warning` and adds it to `Result#messages`.
+ *
+ * ```js
+ * if (decl.important) {
+ * result.warn('Avoid !important', { node: decl, word: '!important' })
+ * }
+ * ```
+ *
+ * @param text Warning message.
+ * @param opts Warning options.
+ * @return Created warning.
+ */
+ warn(message: string, options?: WarningOptions): Warning
+
+ /**
+ * Returns warnings from plugins. Filters `Warning` instances
+ * from `Result#messages`.
+ *
+ * ```js
+ * result.warnings().forEach(warn => {
+ * console.warn(warn.toString())
+ * })
+ * ```
+ *
+ * @return Warnings from plugins.
+ */
+ warnings(): Warning[]
+}
+
+declare class Result<RootNode = Document | Root> extends Result_<RootNode> {}
+
+export = Result
diff --git a/frontend/node_modules/postcss/lib/result.js b/frontend/node_modules/postcss/lib/result.js
new file mode 100644
index 0000000..c6af4e8
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/result.js
@@ -0,0 +1,42 @@
+'use strict'
+
+let Warning = require('./warning')
+
+class Result {
+ get content() {
+ return this.css
+ }
+
+ constructor(processor, root, opts) {
+ this.processor = processor
+ this.messages = []
+ this.root = root
+ this.opts = opts
+ this.css = ''
+ this.map = undefined
+ }
+
+ toString() {
+ return this.css
+ }
+
+ warn(text, opts = {}) {
+ if (!opts.plugin) {
+ if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
+ opts.plugin = this.lastPlugin.postcssPlugin
+ }
+ }
+
+ let warning = new Warning(text, opts)
+ this.messages.push(warning)
+
+ return warning
+ }
+
+ warnings() {
+ return this.messages.filter(i => i.type === 'warning')
+ }
+}
+
+module.exports = Result
+Result.default = Result
diff --git a/frontend/node_modules/postcss/lib/root.d.ts b/frontend/node_modules/postcss/lib/root.d.ts
new file mode 100644
index 0000000..5c91139
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/root.d.ts
@@ -0,0 +1,87 @@
+import Container, { ContainerProps } from './container.js'
+import Document from './document.js'
+import { ProcessOptions } from './postcss.js'
+import Result from './result.js'
+
+declare namespace Root {
+ export interface RootRaws extends Record<string, any> {
+ /**
+ * The space symbols after the last child to the end of file.
+ */
+ after?: string
+
+ /**
+ * Non-CSS code after `Root`, when `Root` is inside `Document`.
+ *
+ * **Experimental:** some aspects of this node could change within minor
+ * or patch version releases.
+ */
+ codeAfter?: string
+
+ /**
+ * Non-CSS code before `Root`, when `Root` is inside `Document`.
+ *
+ * **Experimental:** some aspects of this node could change within minor
+ * or patch version releases.
+ */
+ codeBefore?: string
+
+ /**
+ * Is the last child has an (optional) semicolon.
+ */
+ semicolon?: boolean
+ }
+
+ export interface RootProps extends ContainerProps {
+ /**
+ * Information used to generate byte-to-byte equal node string
+ * as it was in the origin input.
+ * */
+ raws?: RootRaws
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Root_ as default }
+}
+
+/**
+ * Represents a CSS file and contains all its parsed nodes.
+ *
+ * ```js
+ * const root = postcss.parse('a{color:black} b{z-index:2}')
+ * root.type //=> 'root'
+ * root.nodes.length //=> 2
+ * ```
+ */
+declare class Root_ extends Container {
+ nodes: NonNullable<Container['nodes']>
+ parent: Document | undefined
+ raws: Root.RootRaws
+ type: 'root'
+
+ constructor(defaults?: Root.RootProps)
+
+ assign(overrides: object | Root.RootProps): this
+ clone(overrides?: Partial<Root.RootProps>): this
+ cloneAfter(overrides?: Partial<Root.RootProps>): this
+ cloneBefore(overrides?: Partial<Root.RootProps>): this
+
+ /**
+ * Returns a `Result` instance representing the root’s CSS.
+ *
+ * ```js
+ * const root1 = postcss.parse(css1, { from: 'a.css' })
+ * const root2 = postcss.parse(css2, { from: 'b.css' })
+ * root1.append(root2)
+ * const result = root1.toResult({ to: 'all.css', map: true })
+ * ```
+ *
+ * @param options Options.
+ * @return Result with current root’s CSS.
+ */
+ toResult(options?: ProcessOptions): Result
+}
+
+declare class Root extends Root_ {}
+
+export = Root
diff --git a/frontend/node_modules/postcss/lib/root.js b/frontend/node_modules/postcss/lib/root.js
new file mode 100644
index 0000000..ea574ed
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/root.js
@@ -0,0 +1,61 @@
+'use strict'
+
+let Container = require('./container')
+
+let LazyResult, Processor
+
+class Root extends Container {
+ constructor(defaults) {
+ super(defaults)
+ this.type = 'root'
+ if (!this.nodes) this.nodes = []
+ }
+
+ normalize(child, sample, type) {
+ let nodes = super.normalize(child)
+
+ if (sample) {
+ if (type === 'prepend') {
+ if (this.nodes.length > 1) {
+ sample.raws.before = this.nodes[1].raws.before
+ } else {
+ delete sample.raws.before
+ }
+ } else if (this.first !== sample) {
+ for (let node of nodes) {
+ node.raws.before = sample.raws.before
+ }
+ }
+ }
+
+ return nodes
+ }
+
+ removeChild(child, ignore) {
+ let index = this.index(child)
+
+ if (!ignore && index === 0 && this.nodes.length > 1) {
+ this.nodes[1].raws.before = this.nodes[index].raws.before
+ }
+
+ return super.removeChild(child)
+ }
+
+ toResult(opts = {}) {
+ let lazy = new LazyResult(new Processor(), this, opts)
+ return lazy.stringify()
+ }
+}
+
+Root.registerLazyResult = dependant => {
+ LazyResult = dependant
+}
+
+Root.registerProcessor = dependant => {
+ Processor = dependant
+}
+
+module.exports = Root
+Root.default = Root
+
+Container.registerRoot(Root)
diff --git a/frontend/node_modules/postcss/lib/rule.d.ts b/frontend/node_modules/postcss/lib/rule.d.ts
new file mode 100644
index 0000000..9a951e7
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/rule.d.ts
@@ -0,0 +1,126 @@
+import Container, {
+ ContainerProps,
+ ContainerWithChildren
+} from './container.js'
+
+declare namespace Rule {
+ export interface RuleRaws extends Record<string, unknown> {
+ /**
+ * The space symbols after the last child of the node to the end of the node.
+ */
+ after?: string
+
+ /**
+ * The space symbols before the node. It also stores `*`
+ * and `_` symbols before the declaration (IE hack).
+ */
+ before?: string
+
+ /**
+ * The symbols between the selector and `{` for rules.
+ */
+ between?: string
+
+ /**
+ * Contains the text of the semicolon after this rule.
+ */
+ ownSemicolon?: string
+
+ /**
+ * The rule’s selector with comments.
+ */
+ selector?: {
+ raw: string
+ value: string
+ }
+
+ /**
+ * Contains `true` if the last child has an (optional) semicolon.
+ */
+ semicolon?: boolean
+ }
+
+ export type RuleProps = {
+ /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
+ raws?: RuleRaws
+ } & (
+ | {
+ /** Selector or selectors of the rule. */
+ selector: string
+ selectors?: never
+ }
+ | {
+ selector?: never
+ /** Selectors of the rule represented as an array of strings. */
+ selectors: readonly string[]
+ }
+ ) & ContainerProps
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Rule_ as default }
+}
+
+/**
+ * Represents a CSS rule: a selector followed by a declaration block.
+ *
+ * ```js
+ * Once (root, { Rule }) {
+ * let a = new Rule({ selector: 'a' })
+ * a.append(…)
+ * root.append(a)
+ * }
+ * ```
+ *
+ * ```js
+ * const root = postcss.parse('a{}')
+ * const rule = root.first
+ * rule.type //=> 'rule'
+ * rule.toString() //=> 'a{}'
+ * ```
+ */
+declare class Rule_ extends Container {
+ nodes: NonNullable<Container['nodes']>
+ parent: ContainerWithChildren | undefined
+ raws: Rule.RuleRaws
+ type: 'rule'
+ /**
+ * The rule’s full selector represented as a string.
+ *
+ * ```js
+ * const root = postcss.parse('a, b { }')
+ * const rule = root.first
+ * rule.selector //=> 'a, b'
+ * ```
+ */
+ get selector(): string
+
+ set selector(value: string)
+ /**
+ * An array containing the rule’s individual selectors.
+ * Groups of selectors are split at commas.
+ *
+ * ```js
+ * const root = postcss.parse('a, b { }')
+ * const rule = root.first
+ *
+ * rule.selector //=> 'a, b'
+ * rule.selectors //=> ['a', 'b']
+ *
+ * rule.selectors = ['a', 'strong']
+ * rule.selector //=> 'a, strong'
+ * ```
+ */
+ get selectors(): string[]
+
+ set selectors(values: string[])
+
+ constructor(defaults?: Rule.RuleProps)
+ assign(overrides: object | Rule.RuleProps): this
+ clone(overrides?: Partial<Rule.RuleProps>): this
+ cloneAfter(overrides?: Partial<Rule.RuleProps>): this
+ cloneBefore(overrides?: Partial<Rule.RuleProps>): this
+}
+
+declare class Rule extends Rule_ {}
+
+export = Rule
diff --git a/frontend/node_modules/postcss/lib/rule.js b/frontend/node_modules/postcss/lib/rule.js
new file mode 100644
index 0000000..3b9b7e9
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/rule.js
@@ -0,0 +1,27 @@
+'use strict'
+
+let Container = require('./container')
+let list = require('./list')
+
+class Rule extends Container {
+ get selectors() {
+ return list.comma(this.selector)
+ }
+
+ set selectors(values) {
+ let match = this.selector ? this.selector.match(/,\s*/) : null
+ let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen')
+ this.selector = values.join(sep)
+ }
+
+ constructor(defaults) {
+ super(defaults)
+ this.type = 'rule'
+ if (!this.nodes) this.nodes = []
+ }
+}
+
+module.exports = Rule
+Rule.default = Rule
+
+Container.registerRule(Rule)
diff --git a/frontend/node_modules/postcss/lib/stringifier.d.ts b/frontend/node_modules/postcss/lib/stringifier.d.ts
new file mode 100644
index 0000000..b5a6f86
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/stringifier.d.ts
@@ -0,0 +1,46 @@
+import {
+ AnyNode,
+ AtRule,
+ Builder,
+ Comment,
+ Container,
+ Declaration,
+ Document,
+ Root,
+ Rule
+} from './postcss.js'
+
+declare namespace Stringifier {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Stringifier_ as default }
+}
+
+declare class Stringifier_ {
+ builder: Builder
+ constructor(builder: Builder)
+ atrule(node: AtRule, semicolon?: boolean): void
+ beforeAfter(node: AnyNode, detect: 'after' | 'before'): string
+ block(node: AnyNode, start: string): void
+ body(node: Container): void
+ comment(node: Comment): void
+ decl(node: Declaration, semicolon?: boolean): void
+ document(node: Document): void
+ raw(node: AnyNode, own: null | string, detect?: string): boolean | string
+ rawBeforeClose(root: Root): string | undefined
+ rawBeforeComment(root: Root, node: Comment): string | undefined
+ rawBeforeDecl(root: Root, node: Declaration): string | undefined
+ rawBeforeOpen(root: Root): string | undefined
+ rawBeforeRule(root: Root): string | undefined
+ rawColon(root: Root): string | undefined
+ rawEmptyBody(root: Root): string | undefined
+ rawIndent(root: Root): string | undefined
+ rawSemicolon(root: Root): boolean | undefined
+ rawValue(node: AnyNode, prop: string): number | string
+ root(node: Root): void
+ rule(node: Rule): void
+ stringify(node: AnyNode, semicolon?: boolean): void
+}
+
+declare class Stringifier extends Stringifier_ {}
+
+export = Stringifier
diff --git a/frontend/node_modules/postcss/lib/stringifier.js b/frontend/node_modules/postcss/lib/stringifier.js
new file mode 100644
index 0000000..e07ad12
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/stringifier.js
@@ -0,0 +1,353 @@
+'use strict'
+
+const DEFAULT_RAW = {
+ after: '\n',
+ beforeClose: '\n',
+ beforeComment: '\n',
+ beforeDecl: '\n',
+ beforeOpen: ' ',
+ beforeRule: '\n',
+ colon: ': ',
+ commentLeft: ' ',
+ commentRight: ' ',
+ emptyBody: '',
+ indent: ' ',
+ semicolon: false
+}
+
+function capitalize(str) {
+ return str[0].toUpperCase() + str.slice(1)
+}
+
+class Stringifier {
+ constructor(builder) {
+ this.builder = builder
+ }
+
+ atrule(node, semicolon) {
+ let name = '@' + node.name
+ let params = node.params ? this.rawValue(node, 'params') : ''
+
+ if (typeof node.raws.afterName !== 'undefined') {
+ name += node.raws.afterName
+ } else if (params) {
+ name += ' '
+ }
+
+ if (node.nodes) {
+ this.block(node, name + params)
+ } else {
+ let end = (node.raws.between || '') + (semicolon ? ';' : '')
+ this.builder(name + params + end, node)
+ }
+ }
+
+ beforeAfter(node, detect) {
+ let value
+ if (node.type === 'decl') {
+ value = this.raw(node, null, 'beforeDecl')
+ } else if (node.type === 'comment') {
+ value = this.raw(node, null, 'beforeComment')
+ } else if (detect === 'before') {
+ value = this.raw(node, null, 'beforeRule')
+ } else {
+ value = this.raw(node, null, 'beforeClose')
+ }
+
+ let buf = node.parent
+ let depth = 0
+ while (buf && buf.type !== 'root') {
+ depth += 1
+ buf = buf.parent
+ }
+
+ if (value.includes('\n')) {
+ let indent = this.raw(node, null, 'indent')
+ if (indent.length) {
+ for (let step = 0; step < depth; step++) value += indent
+ }
+ }
+
+ return value
+ }
+
+ block(node, start) {
+ let between = this.raw(node, 'between', 'beforeOpen')
+ this.builder(start + between + '{', node, 'start')
+
+ let after
+ if (node.nodes && node.nodes.length) {
+ this.body(node)
+ after = this.raw(node, 'after')
+ } else {
+ after = this.raw(node, 'after', 'emptyBody')
+ }
+
+ if (after) this.builder(after)
+ this.builder('}', node, 'end')
+ }
+
+ body(node) {
+ let last = node.nodes.length - 1
+ while (last > 0) {
+ if (node.nodes[last].type !== 'comment') break
+ last -= 1
+ }
+
+ let semicolon = this.raw(node, 'semicolon')
+ for (let i = 0; i < node.nodes.length; i++) {
+ let child = node.nodes[i]
+ let before = this.raw(child, 'before')
+ if (before) this.builder(before)
+ this.stringify(child, last !== i || semicolon)
+ }
+ }
+
+ comment(node) {
+ let left = this.raw(node, 'left', 'commentLeft')
+ let right = this.raw(node, 'right', 'commentRight')
+ this.builder('/*' + left + node.text + right + '*/', node)
+ }
+
+ decl(node, semicolon) {
+ let between = this.raw(node, 'between', 'colon')
+ let string = node.prop + between + this.rawValue(node, 'value')
+
+ if (node.important) {
+ string += node.raws.important || ' !important'
+ }
+
+ if (semicolon) string += ';'
+ this.builder(string, node)
+ }
+
+ document(node) {
+ this.body(node)
+ }
+
+ raw(node, own, detect) {
+ let value
+ if (!detect) detect = own
+
+ // Already had
+ if (own) {
+ value = node.raws[own]
+ if (typeof value !== 'undefined') return value
+ }
+
+ let parent = node.parent
+
+ if (detect === 'before') {
+ // Hack for first rule in CSS
+ if (!parent || (parent.type === 'root' && parent.first === node)) {
+ return ''
+ }
+
+ // `root` nodes in `document` should use only their own raws
+ if (parent && parent.type === 'document') {
+ return ''
+ }
+ }
+
+ // Floating child without parent
+ if (!parent) return DEFAULT_RAW[detect]
+
+ // Detect style by other nodes
+ let root = node.root()
+ if (!root.rawCache) root.rawCache = {}
+ if (typeof root.rawCache[detect] !== 'undefined') {
+ return root.rawCache[detect]
+ }
+
+ if (detect === 'before' || detect === 'after') {
+ return this.beforeAfter(node, detect)
+ } else {
+ let method = 'raw' + capitalize(detect)
+ if (this[method]) {
+ value = this[method](root, node)
+ } else {
+ root.walk(i => {
+ value = i.raws[own]
+ if (typeof value !== 'undefined') return false
+ })
+ }
+ }
+
+ if (typeof value === 'undefined') value = DEFAULT_RAW[detect]
+
+ root.rawCache[detect] = value
+ return value
+ }
+
+ rawBeforeClose(root) {
+ let value
+ root.walk(i => {
+ if (i.nodes && i.nodes.length > 0) {
+ if (typeof i.raws.after !== 'undefined') {
+ value = i.raws.after
+ if (value.includes('\n')) {
+ value = value.replace(/[^\n]+$/, '')
+ }
+ return false
+ }
+ }
+ })
+ if (value) value = value.replace(/\S/g, '')
+ return value
+ }
+
+ rawBeforeComment(root, node) {
+ let value
+ root.walkComments(i => {
+ if (typeof i.raws.before !== 'undefined') {
+ value = i.raws.before
+ if (value.includes('\n')) {
+ value = value.replace(/[^\n]+$/, '')
+ }
+ return false
+ }
+ })
+ if (typeof value === 'undefined') {
+ value = this.raw(node, null, 'beforeDecl')
+ } else if (value) {
+ value = value.replace(/\S/g, '')
+ }
+ return value
+ }
+
+ rawBeforeDecl(root, node) {
+ let value
+ root.walkDecls(i => {
+ if (typeof i.raws.before !== 'undefined') {
+ value = i.raws.before
+ if (value.includes('\n')) {
+ value = value.replace(/[^\n]+$/, '')
+ }
+ return false
+ }
+ })
+ if (typeof value === 'undefined') {
+ value = this.raw(node, null, 'beforeRule')
+ } else if (value) {
+ value = value.replace(/\S/g, '')
+ }
+ return value
+ }
+
+ rawBeforeOpen(root) {
+ let value
+ root.walk(i => {
+ if (i.type !== 'decl') {
+ value = i.raws.between
+ if (typeof value !== 'undefined') return false
+ }
+ })
+ return value
+ }
+
+ rawBeforeRule(root) {
+ let value
+ root.walk(i => {
+ if (i.nodes && (i.parent !== root || root.first !== i)) {
+ if (typeof i.raws.before !== 'undefined') {
+ value = i.raws.before
+ if (value.includes('\n')) {
+ value = value.replace(/[^\n]+$/, '')
+ }
+ return false
+ }
+ }
+ })
+ if (value) value = value.replace(/\S/g, '')
+ return value
+ }
+
+ rawColon(root) {
+ let value
+ root.walkDecls(i => {
+ if (typeof i.raws.between !== 'undefined') {
+ value = i.raws.between.replace(/[^\s:]/g, '')
+ return false
+ }
+ })
+ return value
+ }
+
+ rawEmptyBody(root) {
+ let value
+ root.walk(i => {
+ if (i.nodes && i.nodes.length === 0) {
+ value = i.raws.after
+ if (typeof value !== 'undefined') return false
+ }
+ })
+ return value
+ }
+
+ rawIndent(root) {
+ if (root.raws.indent) return root.raws.indent
+ let value
+ root.walk(i => {
+ let p = i.parent
+ if (p && p !== root && p.parent && p.parent === root) {
+ if (typeof i.raws.before !== 'undefined') {
+ let parts = i.raws.before.split('\n')
+ value = parts[parts.length - 1]
+ value = value.replace(/\S/g, '')
+ return false
+ }
+ }
+ })
+ return value
+ }
+
+ rawSemicolon(root) {
+ let value
+ root.walk(i => {
+ if (i.nodes && i.nodes.length && i.last.type === 'decl') {
+ value = i.raws.semicolon
+ if (typeof value !== 'undefined') return false
+ }
+ })
+ return value
+ }
+
+ rawValue(node, prop) {
+ let value = node[prop]
+ let raw = node.raws[prop]
+ if (raw && raw.value === value) {
+ return raw.raw
+ }
+
+ return value
+ }
+
+ root(node) {
+ this.body(node)
+ if (node.raws.after) this.builder(node.raws.after)
+ }
+
+ rule(node) {
+ this.block(node, this.rawValue(node, 'selector'))
+ if (node.raws.ownSemicolon) {
+ this.builder(node.raws.ownSemicolon, node, 'end')
+ }
+ }
+
+ stringify(node, semicolon) {
+ /* c8 ignore start */
+ if (!this[node.type]) {
+ throw new Error(
+ 'Unknown AST node type ' +
+ node.type +
+ '. ' +
+ 'Maybe you need to change PostCSS stringifier.'
+ )
+ }
+ /* c8 ignore stop */
+ this[node.type](node, semicolon)
+ }
+}
+
+module.exports = Stringifier
+Stringifier.default = Stringifier
diff --git a/frontend/node_modules/postcss/lib/stringify.d.ts b/frontend/node_modules/postcss/lib/stringify.d.ts
new file mode 100644
index 0000000..06ad0b4
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/stringify.d.ts
@@ -0,0 +1,9 @@
+import { Stringifier } from './postcss.js'
+
+interface Stringify extends Stringifier {
+ default: Stringify
+}
+
+declare const stringify: Stringify
+
+export = stringify
diff --git a/frontend/node_modules/postcss/lib/stringify.js b/frontend/node_modules/postcss/lib/stringify.js
new file mode 100644
index 0000000..77bd017
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/stringify.js
@@ -0,0 +1,11 @@
+'use strict'
+
+let Stringifier = require('./stringifier')
+
+function stringify(node, builder) {
+ let str = new Stringifier(builder)
+ str.stringify(node)
+}
+
+module.exports = stringify
+stringify.default = stringify
diff --git a/frontend/node_modules/postcss/lib/symbols.js b/frontend/node_modules/postcss/lib/symbols.js
new file mode 100644
index 0000000..a142c26
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/symbols.js
@@ -0,0 +1,5 @@
+'use strict'
+
+module.exports.isClean = Symbol('isClean')
+
+module.exports.my = Symbol('my')
diff --git a/frontend/node_modules/postcss/lib/terminal-highlight.js b/frontend/node_modules/postcss/lib/terminal-highlight.js
new file mode 100644
index 0000000..6196c9d
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/terminal-highlight.js
@@ -0,0 +1,70 @@
+'use strict'
+
+let pico = require('picocolors')
+
+let tokenizer = require('./tokenize')
+
+let Input
+
+function registerInput(dependant) {
+ Input = dependant
+}
+
+const HIGHLIGHT_THEME = {
+ ';': pico.yellow,
+ ':': pico.yellow,
+ '(': pico.cyan,
+ ')': pico.cyan,
+ '[': pico.yellow,
+ ']': pico.yellow,
+ '{': pico.yellow,
+ '}': pico.yellow,
+ 'at-word': pico.cyan,
+ 'brackets': pico.cyan,
+ 'call': pico.cyan,
+ 'class': pico.yellow,
+ 'comment': pico.gray,
+ 'hash': pico.magenta,
+ 'string': pico.green
+}
+
+function getTokenType([type, value], processor) {
+ if (type === 'word') {
+ if (value[0] === '.') {
+ return 'class'
+ }
+ if (value[0] === '#') {
+ return 'hash'
+ }
+ }
+
+ if (!processor.endOfFile()) {
+ let next = processor.nextToken()
+ processor.back(next)
+ if (next[0] === 'brackets' || next[0] === '(') return 'call'
+ }
+
+ return type
+}
+
+function terminalHighlight(css) {
+ let processor = tokenizer(new Input(css), { ignoreErrors: true })
+ let result = ''
+ while (!processor.endOfFile()) {
+ let token = processor.nextToken()
+ let color = HIGHLIGHT_THEME[getTokenType(token, processor)]
+ if (color) {
+ result += token[1]
+ .split(/\r?\n/)
+ .map(i => color(i))
+ .join('\n')
+ } else {
+ result += token[1]
+ }
+ }
+ return result
+}
+
+terminalHighlight.registerInput = registerInput
+
+module.exports = terminalHighlight
diff --git a/frontend/node_modules/postcss/lib/tokenize.js b/frontend/node_modules/postcss/lib/tokenize.js
new file mode 100644
index 0000000..1d41284
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/tokenize.js
@@ -0,0 +1,266 @@
+'use strict'
+
+const SINGLE_QUOTE = "'".charCodeAt(0)
+const DOUBLE_QUOTE = '"'.charCodeAt(0)
+const BACKSLASH = '\\'.charCodeAt(0)
+const SLASH = '/'.charCodeAt(0)
+const NEWLINE = '\n'.charCodeAt(0)
+const SPACE = ' '.charCodeAt(0)
+const FEED = '\f'.charCodeAt(0)
+const TAB = '\t'.charCodeAt(0)
+const CR = '\r'.charCodeAt(0)
+const OPEN_SQUARE = '['.charCodeAt(0)
+const CLOSE_SQUARE = ']'.charCodeAt(0)
+const OPEN_PARENTHESES = '('.charCodeAt(0)
+const CLOSE_PARENTHESES = ')'.charCodeAt(0)
+const OPEN_CURLY = '{'.charCodeAt(0)
+const CLOSE_CURLY = '}'.charCodeAt(0)
+const SEMICOLON = ';'.charCodeAt(0)
+const ASTERISK = '*'.charCodeAt(0)
+const COLON = ':'.charCodeAt(0)
+const AT = '@'.charCodeAt(0)
+
+const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g
+const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g
+const RE_BAD_BRACKET = /.[\r\n"'(/\\]/
+const RE_HEX_ESCAPE = /[\da-f]/i
+
+module.exports = function tokenizer(input, options = {}) {
+ let css = input.css.valueOf()
+ let ignore = options.ignoreErrors
+
+ let code, content, escape, next, quote
+ let currentToken, escaped, escapePos, n, prev
+
+ let length = css.length
+ let pos = 0
+ let buffer = []
+ let returned = []
+
+ function position() {
+ return pos
+ }
+
+ function unclosed(what) {
+ throw input.error('Unclosed ' + what, pos)
+ }
+
+ function endOfFile() {
+ return returned.length === 0 && pos >= length
+ }
+
+ function nextToken(opts) {
+ if (returned.length) return returned.pop()
+ if (pos >= length) return
+
+ let ignoreUnclosed = opts ? opts.ignoreUnclosed : false
+
+ code = css.charCodeAt(pos)
+
+ switch (code) {
+ case NEWLINE:
+ case SPACE:
+ case TAB:
+ case CR:
+ case FEED: {
+ next = pos
+ do {
+ next += 1
+ code = css.charCodeAt(next)
+ } while (
+ code === SPACE ||
+ code === NEWLINE ||
+ code === TAB ||
+ code === CR ||
+ code === FEED
+ )
+
+ currentToken = ['space', css.slice(pos, next)]
+ pos = next - 1
+ break
+ }
+
+ case OPEN_SQUARE:
+ case CLOSE_SQUARE:
+ case OPEN_CURLY:
+ case CLOSE_CURLY:
+ case COLON:
+ case SEMICOLON:
+ case CLOSE_PARENTHESES: {
+ let controlChar = String.fromCharCode(code)
+ currentToken = [controlChar, controlChar, pos]
+ break
+ }
+
+ case OPEN_PARENTHESES: {
+ prev = buffer.length ? buffer.pop()[1] : ''
+ n = css.charCodeAt(pos + 1)
+ if (
+ prev === 'url' &&
+ n !== SINGLE_QUOTE &&
+ n !== DOUBLE_QUOTE &&
+ n !== SPACE &&
+ n !== NEWLINE &&
+ n !== TAB &&
+ n !== FEED &&
+ n !== CR
+ ) {
+ next = pos
+ do {
+ escaped = false
+ next = css.indexOf(')', next + 1)
+ if (next === -1) {
+ if (ignore || ignoreUnclosed) {
+ next = pos
+ break
+ } else {
+ unclosed('bracket')
+ }
+ }
+ escapePos = next
+ while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
+ escapePos -= 1
+ escaped = !escaped
+ }
+ } while (escaped)
+
+ currentToken = ['brackets', css.slice(pos, next + 1), pos, next]
+
+ pos = next
+ } else {
+ next = css.indexOf(')', pos + 1)
+ content = css.slice(pos, next + 1)
+
+ if (next === -1 || RE_BAD_BRACKET.test(content)) {
+ currentToken = ['(', '(', pos]
+ } else {
+ currentToken = ['brackets', content, pos, next]
+ pos = next
+ }
+ }
+
+ break
+ }
+
+ case SINGLE_QUOTE:
+ case DOUBLE_QUOTE: {
+ quote = code === SINGLE_QUOTE ? "'" : '"'
+ next = pos
+ do {
+ escaped = false
+ next = css.indexOf(quote, next + 1)
+ if (next === -1) {
+ if (ignore || ignoreUnclosed) {
+ next = pos + 1
+ break
+ } else {
+ unclosed('string')
+ }
+ }
+ escapePos = next
+ while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
+ escapePos -= 1
+ escaped = !escaped
+ }
+ } while (escaped)
+
+ currentToken = ['string', css.slice(pos, next + 1), pos, next]
+ pos = next
+ break
+ }
+
+ case AT: {
+ RE_AT_END.lastIndex = pos + 1
+ RE_AT_END.test(css)
+ if (RE_AT_END.lastIndex === 0) {
+ next = css.length - 1
+ } else {
+ next = RE_AT_END.lastIndex - 2
+ }
+
+ currentToken = ['at-word', css.slice(pos, next + 1), pos, next]
+
+ pos = next
+ break
+ }
+
+ case BACKSLASH: {
+ next = pos
+ escape = true
+ while (css.charCodeAt(next + 1) === BACKSLASH) {
+ next += 1
+ escape = !escape
+ }
+ code = css.charCodeAt(next + 1)
+ if (
+ escape &&
+ code !== SLASH &&
+ code !== SPACE &&
+ code !== NEWLINE &&
+ code !== TAB &&
+ code !== CR &&
+ code !== FEED
+ ) {
+ next += 1
+ if (RE_HEX_ESCAPE.test(css.charAt(next))) {
+ while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
+ next += 1
+ }
+ if (css.charCodeAt(next + 1) === SPACE) {
+ next += 1
+ }
+ }
+ }
+
+ currentToken = ['word', css.slice(pos, next + 1), pos, next]
+
+ pos = next
+ break
+ }
+
+ default: {
+ if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
+ next = css.indexOf('*/', pos + 2) + 1
+ if (next === 0) {
+ if (ignore || ignoreUnclosed) {
+ next = css.length
+ } else {
+ unclosed('comment')
+ }
+ }
+
+ currentToken = ['comment', css.slice(pos, next + 1), pos, next]
+ pos = next
+ } else {
+ RE_WORD_END.lastIndex = pos + 1
+ RE_WORD_END.test(css)
+ if (RE_WORD_END.lastIndex === 0) {
+ next = css.length - 1
+ } else {
+ next = RE_WORD_END.lastIndex - 2
+ }
+
+ currentToken = ['word', css.slice(pos, next + 1), pos, next]
+ buffer.push(currentToken)
+ pos = next
+ }
+
+ break
+ }
+ }
+
+ pos++
+ return currentToken
+ }
+
+ function back(token) {
+ returned.push(token)
+ }
+
+ return {
+ back,
+ endOfFile,
+ nextToken,
+ position
+ }
+}
diff --git a/frontend/node_modules/postcss/lib/warn-once.js b/frontend/node_modules/postcss/lib/warn-once.js
new file mode 100644
index 0000000..316e1cf
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/warn-once.js
@@ -0,0 +1,13 @@
+/* eslint-disable no-console */
+'use strict'
+
+let printed = {}
+
+module.exports = function warnOnce(message) {
+ if (printed[message]) return
+ printed[message] = true
+
+ if (typeof console !== 'undefined' && console.warn) {
+ console.warn(message)
+ }
+}
diff --git a/frontend/node_modules/postcss/lib/warning.d.ts b/frontend/node_modules/postcss/lib/warning.d.ts
new file mode 100644
index 0000000..b25bba8
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/warning.d.ts
@@ -0,0 +1,147 @@
+import { RangePosition } from './css-syntax-error.js'
+import Node from './node.js'
+
+declare namespace Warning {
+ export interface WarningOptions {
+ /**
+ * End position, exclusive, in CSS node string that caused the warning.
+ */
+ end?: RangePosition
+
+ /**
+ * End index, exclusive, in CSS node string that caused the warning.
+ */
+ endIndex?: number
+
+ /**
+ * Start index, inclusive, in CSS node string that caused the warning.
+ */
+ index?: number
+
+ /**
+ * CSS node that caused the warning.
+ */
+ node?: Node
+
+ /**
+ * Name of the plugin that created this warning. `Result#warn` fills
+ * this property automatically.
+ */
+ plugin?: string
+
+ /**
+ * Start position, inclusive, in CSS node string that caused the warning.
+ */
+ start?: RangePosition
+
+ /**
+ * Word in CSS source that caused the warning.
+ */
+ word?: string
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ export { Warning_ as default }
+}
+
+/**
+ * Represents a plugin’s warning. It can be created using `Node#warn`.
+ *
+ * ```js
+ * if (decl.important) {
+ * decl.warn(result, 'Avoid !important', { word: '!important' })
+ * }
+ * ```
+ */
+declare class Warning_ {
+ /**
+ * Column for inclusive start position in the input file with this warning’s source.
+ *
+ * ```js
+ * warning.column //=> 6
+ * ```
+ */
+ column: number
+
+ /**
+ * Column for exclusive end position in the input file with this warning’s source.
+ *
+ * ```js
+ * warning.endColumn //=> 4
+ * ```
+ */
+ endColumn?: number
+
+ /**
+ * Line for exclusive end position in the input file with this warning’s source.
+ *
+ * ```js
+ * warning.endLine //=> 6
+ * ```
+ */
+ endLine?: number
+
+ /**
+ * Line for inclusive start position in the input file with this warning’s source.
+ *
+ * ```js
+ * warning.line //=> 5
+ * ```
+ */
+ line: number
+
+ /**
+ * Contains the CSS node that caused the warning.
+ *
+ * ```js
+ * warning.node.toString() //=> 'color: white !important'
+ * ```
+ */
+ node: Node
+
+ /**
+ * The name of the plugin that created this warning.
+ * When you call `Node#warn` it will fill this property automatically.
+ *
+ * ```js
+ * warning.plugin //=> 'postcss-important'
+ * ```
+ */
+ plugin: string
+
+ /**
+ * The warning message.
+ *
+ * ```js
+ * warning.text //=> 'Try to avoid !important'
+ * ```
+ */
+ text: string
+
+ /**
+ * Type to filter warnings from `Result#messages`.
+ * Always equal to `"warning"`.
+ */
+ type: 'warning'
+
+ /**
+ * @param text Warning message.
+ * @param opts Warning options.
+ */
+ constructor(text: string, opts?: Warning.WarningOptions)
+
+ /**
+ * Returns a warning position and message.
+ *
+ * ```js
+ * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
+ * ```
+ *
+ * @return Warning position and message.
+ */
+ toString(): string
+}
+
+declare class Warning extends Warning_ {}
+
+export = Warning
diff --git a/frontend/node_modules/postcss/lib/warning.js b/frontend/node_modules/postcss/lib/warning.js
new file mode 100644
index 0000000..3a3d79c
--- /dev/null
+++ b/frontend/node_modules/postcss/lib/warning.js
@@ -0,0 +1,37 @@
+'use strict'
+
+class Warning {
+ constructor(text, opts = {}) {
+ this.type = 'warning'
+ this.text = text
+
+ if (opts.node && opts.node.source) {
+ let range = opts.node.rangeBy(opts)
+ this.line = range.start.line
+ this.column = range.start.column
+ this.endLine = range.end.line
+ this.endColumn = range.end.column
+ }
+
+ for (let opt in opts) this[opt] = opts[opt]
+ }
+
+ toString() {
+ if (this.node) {
+ return this.node.error(this.text, {
+ index: this.index,
+ plugin: this.plugin,
+ word: this.word
+ }).message
+ }
+
+ if (this.plugin) {
+ return this.plugin + ': ' + this.text
+ }
+
+ return this.text
+ }
+}
+
+module.exports = Warning
+Warning.default = Warning
diff --git a/frontend/node_modules/postcss/package.json b/frontend/node_modules/postcss/package.json
new file mode 100644
index 0000000..c69124b
--- /dev/null
+++ b/frontend/node_modules/postcss/package.json
@@ -0,0 +1,88 @@
+{
+ "name": "postcss",
+ "version": "8.5.6",
+ "description": "Tool for transforming styles with JS plugins",
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ },
+ "exports": {
+ ".": {
+ "import": "./lib/postcss.mjs",
+ "require": "./lib/postcss.js"
+ },
+ "./lib/at-rule": "./lib/at-rule.js",
+ "./lib/comment": "./lib/comment.js",
+ "./lib/container": "./lib/container.js",
+ "./lib/css-syntax-error": "./lib/css-syntax-error.js",
+ "./lib/declaration": "./lib/declaration.js",
+ "./lib/fromJSON": "./lib/fromJSON.js",
+ "./lib/input": "./lib/input.js",
+ "./lib/lazy-result": "./lib/lazy-result.js",
+ "./lib/no-work-result": "./lib/no-work-result.js",
+ "./lib/list": "./lib/list.js",
+ "./lib/map-generator": "./lib/map-generator.js",
+ "./lib/node": "./lib/node.js",
+ "./lib/parse": "./lib/parse.js",
+ "./lib/parser": "./lib/parser.js",
+ "./lib/postcss": "./lib/postcss.js",
+ "./lib/previous-map": "./lib/previous-map.js",
+ "./lib/processor": "./lib/processor.js",
+ "./lib/result": "./lib/result.js",
+ "./lib/root": "./lib/root.js",
+ "./lib/rule": "./lib/rule.js",
+ "./lib/stringifier": "./lib/stringifier.js",
+ "./lib/stringify": "./lib/stringify.js",
+ "./lib/symbols": "./lib/symbols.js",
+ "./lib/terminal-highlight": "./lib/terminal-highlight.js",
+ "./lib/tokenize": "./lib/tokenize.js",
+ "./lib/warn-once": "./lib/warn-once.js",
+ "./lib/warning": "./lib/warning.js",
+ "./package.json": "./package.json"
+ },
+ "main": "./lib/postcss.js",
+ "types": "./lib/postcss.d.ts",
+ "keywords": [
+ "css",
+ "postcss",
+ "rework",
+ "preprocessor",
+ "parser",
+ "source map",
+ "transform",
+ "manipulation",
+ "transpiler"
+ ],
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "author": "Andrey Sitnik <[email protected]>",
+ "license": "MIT",
+ "homepage": "https://postcss.org/",
+ "repository": "postcss/postcss",
+ "bugs": {
+ "url": "https://github.com/postcss/postcss/issues"
+ },
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "browser": {
+ "./lib/terminal-highlight": false,
+ "source-map-js": false,
+ "path": false,
+ "url": false,
+ "fs": false
+ }
+}
diff --git a/frontend/node_modules/rollup/LICENSE.md b/frontend/node_modules/rollup/LICENSE.md
new file mode 100644
index 0000000..bd7af55
--- /dev/null
+++ b/frontend/node_modules/rollup/LICENSE.md
@@ -0,0 +1,679 @@
+# Rollup core license
+Rollup is released under the MIT license:
+
+The MIT License (MIT)
+
+Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+# Licenses of bundled dependencies
+The published Rollup artifact additionally contains code with the following licenses:
+MIT, ISC, 0BSD
+
+# Bundled dependencies:
+## @jridgewell/sourcemap-codec
+License: MIT
+By: Justin Ridgewell
+Repository: git+https://github.com/jridgewell/sourcemaps.git
+
+> Copyright 2024 Justin Ridgewell <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## @rollup/pluginutils
+License: MIT
+By: Rich Harris
+Repository: rollup/plugins
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## anymatch
+License: ISC
+By: Elan Shanker
+Repository: https://github.com/micromatch/anymatch
+
+> The ISC License
+>
+> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com)
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## binary-extensions
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/binary-extensions
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+> Copyright (c) Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## braces
+License: MIT
+By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm
+Repository: micromatch/braces
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## builtin-modules
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/builtin-modules
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## chokidar
+License: MIT
+By: Paul Miller, Elan Shanker
+Repository: git+https://github.com/paulmillr/chokidar.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the “Software”), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## date-time
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/date-time
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## fill-range
+License: MIT
+By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling
+Repository: jonschlinkert/fill-range
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## flru
+License: MIT
+By: Luke Edwards
+Repository: lukeed/flru
+
+> MIT License
+>
+> Copyright (c) Luke Edwards <[email protected]> (lukeed.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## glob-parent
+License: ISC
+By: Gulp Team, Elan Shanker, Blaine Bublitz
+Repository: gulpjs/glob-parent
+
+> The ISC License
+>
+> Copyright (c) 2015, 2019 Elan Shanker
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## is-binary-path
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/is-binary-path
+
+> MIT License
+>
+> Copyright (c) 2019 Sindre Sorhus <[email protected]> (https://sindresorhus.com), Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## is-extglob
+License: MIT
+By: Jon Schlinkert
+Repository: jonschlinkert/is-extglob
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2016, Jon Schlinkert
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## is-glob
+License: MIT
+By: Jon Schlinkert, Brian Woodward, Daniel Perez
+Repository: micromatch/is-glob
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2017, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## is-number
+License: MIT
+By: Jon Schlinkert, Olsten Larck, Rouven Weßling
+Repository: jonschlinkert/is-number
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## is-reference
+License: MIT
+By: Rich Harris
+Repository: git+https://github.com/Rich-Harris/is-reference.git
+
+---------------------------------------
+
+## locate-character
+License: MIT
+By: Rich Harris
+Repository: git+https://gitlab.com/Rich-Harris/locate-character.git
+
+---------------------------------------
+
+## magic-string
+License: MIT
+By: Rich Harris
+Repository: https://github.com/rich-harris/magic-string.git
+
+> Copyright 2018 Rich Harris
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## normalize-path
+License: MIT
+By: Jon Schlinkert, Blaine Bublitz
+Repository: jonschlinkert/normalize-path
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2018, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## parse-ms
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/parse-ms
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## picocolors
+License: ISC
+By: Alexey Raspopov
+Repository: alexeyraspopov/picocolors
+
+> ISC License
+>
+> Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+> OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## picomatch
+License: MIT
+By: Jon Schlinkert
+Repository: micromatch/picomatch
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2017-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## pretty-bytes
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/pretty-bytes
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## pretty-ms
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/pretty-ms
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## readdirp
+License: MIT
+By: Thorsten Lorenz, Paul Miller
+Repository: git://github.com/paulmillr/readdirp.git
+
+> MIT License
+>
+> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## signal-exit
+License: ISC
+By: Ben Coe
+Repository: https://github.com/tapjs/signal-exit.git
+
+> The ISC License
+>
+> Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors
+>
+> Permission to use, copy, modify, and/or distribute this software
+> for any purpose with or without fee is hereby granted, provided
+> that the above copyright notice and this permission notice
+> appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
+> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## time-zone
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/time-zone
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## to-regex-range
+License: MIT
+By: Jon Schlinkert, Rouven Weßling
+Repository: micromatch/to-regex-range
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2015-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## tslib
+License: 0BSD
+By: Microsoft Corp.
+Repository: https://github.com/Microsoft/tslib.git
+
+> Copyright (c) Microsoft Corporation.
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+> AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+> OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+> PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## yargs-parser
+License: ISC
+By: Ben Coe
+Repository: https://github.com/yargs/yargs-parser.git
+
+> Copyright (c) 2016, Contributors
+>
+> Permission to use, copy, modify, and/or distribute this software
+> for any purpose with or without fee is hereby granted, provided
+> that the above copyright notice and this permission notice
+> appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
+> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/frontend/node_modules/rollup/README.md b/frontend/node_modules/rollup/README.md
new file mode 100644
index 0000000..0c4fe95
--- /dev/null
+++ b/frontend/node_modules/rollup/README.md
@@ -0,0 +1,134 @@
+<p align="center">
+ <a href="https://rollupjs.org/"><img src="https://rollupjs.org/rollup-logo.svg" width="150" /></a>
+</p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/rollup">
+ <img src="https://img.shields.io/npm/v/rollup.svg" alt="npm version" >
+ </a>
+ <a href="https://nodejs.org/en/about/previous-releases">
+ <img src="https://img.shields.io/node/v/rollup.svg" alt="node compatibility">
+ </a>
+ <a href="https://packagephobia.now.sh/result?p=rollup">
+ <img src="https://packagephobia.now.sh/badge?p=rollup" alt="install size" >
+ </a>
+ <a href="https://codecov.io/gh/rollup/rollup">
+ <img src="https://codecov.io/gh/rollup/rollup/graph/badge.svg" alt="code coverage" >
+ </a>
+ <a href="#backers" alt="sponsors on Open Collective">
+ <img src="https://opencollective.com/rollup/backers/badge.svg" alt="backers" >
+ </a>
+ <a href="#sponsors" alt="Sponsors on Open Collective">
+ <img src="https://opencollective.com/rollup/sponsors/badge.svg" alt="sponsors" >
+ </a>
+ <a href="https://github.com/rollup/rollup/blob/master/LICENSE.md">
+ <img src="https://img.shields.io/npm/l/rollup.svg" alt="license">
+ </a>
+ <a href='https://is.gd/rollup_chat?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge'>
+ <img src='https://img.shields.io/discord/466787075518365708?color=778cd1&label=chat' alt='Join the chat at https://is.gd/rollup_chat'>
+ </a>
+</p>
+
+<h1 align="center">Rollup</h1>
+
+## Overview
+
+Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today.
+
+## Quick Start Guide
+
+Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/command-line-interface/) with an optional configuration file or else through its [JavaScript API](https://rollupjs.org/javascript-api/). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/introduction/).
+
+### Commands
+
+These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js.
+
+For browsers:
+
+```bash
+# compile to a <script> containing a self-executing function
+rollup main.js --format iife --name "myBundle" --file bundle.js
+```
+
+For Node.js:
+
+```bash
+# compile to a CommonJS module
+rollup main.js --format cjs --file bundle.js
+```
+
+For both browsers and Node.js:
+
+```bash
+# UMD format requires a bundle name
+rollup main.js --format umd --name "myBundle" --file bundle.js
+```
+
+## Why
+
+Developing software is usually easier if you break your project into smaller separate pieces, since that often removes unexpected interactions and dramatically reduces the complexity of the problems you'll need to solve, and simply writing smaller projects in the first place [isn't necessarily the answer](https://medium.com/@Rich_Harris/small-modules-it-s-not-quite-that-simple-3ca532d65de4). Unfortunately, JavaScript has not historically included this capability as a core feature in the language.
+
+This finally changed with ES modules support in JavaScript, which provides a syntax for importing and exporting functions and data so they can be shared between separate scripts. Most browsers and Node.js support ES modules. However, Node.js releases before 12.17 support ES modules only behind the `--experimental-modules` flag, and older browsers like Internet Explorer do not support ES modules at all. Rollup allows you to write your code using ES modules, and run your application even in environments that do not support ES modules natively. For environments that support them, Rollup can output optimized ES modules; for environments that don't, Rollup can compile your code to other formats such as CommonJS modules, AMD modules, and IIFE-style scripts. This means that you get to _write future-proof code_, and you also get the tremendous benefits of...
+
+## Tree Shaking
+
+In addition to enabling the use of ES modules, Rollup also statically analyzes and optimizes the code you are importing, and will exclude anything that isn't actually used. This allows you to build on top of existing tools and modules without adding extra dependencies or bloating the size of your project.
+
+For example, with CommonJS, the _entire tool or library must be imported_.
+
+```js
+// import the entire utils object with CommonJS
+var utils = require('node:utils');
+var query = 'Rollup';
+// use the ajax method of the utils object
+utils.ajax('https://api.example.com?search=' + query).then(handleResponse);
+```
+
+But with ES modules, instead of importing the whole `utils` object, we can just import the one `ajax` function we need:
+
+```js
+// import the ajax function with an ES import statement
+import { ajax } from 'node:utils';
+
+var query = 'Rollup';
+// call the ajax function
+ajax('https://api.example.com?search=' + query).then(handleResponse);
+```
+
+Because Rollup includes the bare minimum, it results in lighter, faster, and less complicated libraries and applications. Since this approach is based on explicit `import` and `export` statements, it is vastly more effective than simply running an automated minifier to detect unused variables in the compiled output code.
+
+## Compatibility
+
+### Importing CommonJS
+
+Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/plugins/tree/master/packages/commonjs).
+
+### Publishing ES Modules
+
+To make sure your ES modules are immediately usable by tools that work with CommonJS such as Node.js and webpack, you can use Rollup to compile to UMD or CommonJS format, and then point to that compiled version with the `main` property in your `package.json` file. If your `package.json` file also has a `module` field, ES-module-aware tools like Rollup and [webpack](https://webpack.js.org/) will [import the ES module version](https://github.com/rollup/rollup/wiki/pkg.module) directly.
+
+## Contributors
+
+This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. <a href="https://github.com/rollup/rollup/graphs/contributors"><img src="https://opencollective.com/rollup/contributors.svg?width=890" /></a>. If you want to contribute yourself, head over to the [contribution guidelines](CONTRIBUTING.md).
+
+## Backers
+
+Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/rollup#backer)]
+
+<a href="https://opencollective.com/rollup#backers" target="_blank"><img src="https://opencollective.com/rollup/backers.svg?width=890"></a>
+
+## Sponsors
+
+Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/rollup#sponsor)]
+
+<a href="https://opencollective.com/rollup/sponsor/0/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/1/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/2/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/3/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/4/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/5/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/6/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/7/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/8/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/9/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/10/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/11/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/12/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/13/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/14/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/14/avatar.svg"></a>
+
+## Special Sponsor
+
+<a href="https://www.tngtech.com/en/index.html" target="_blank"><img src="https://avatars.githubusercontent.com/u/432256?s=200&v=4" alt="TNG Logo"/></a>
+
+TNG has been supporting the work of [Lukas Taegert-Atkinson](https://github.com/lukastaegert) on Rollup since 2017.
+
+## License
+
+[MIT](https://github.com/rollup/rollup/blob/master/LICENSE.md)
diff --git a/frontend/node_modules/rollup/package.json b/frontend/node_modules/rollup/package.json
new file mode 100644
index 0000000..0c004b6
--- /dev/null
+++ b/frontend/node_modules/rollup/package.json
@@ -0,0 +1,273 @@
+{
+ "name": "rollup",
+ "version": "4.52.5",
+ "description": "Next-generation ES module bundler",
+ "main": "dist/rollup.js",
+ "module": "dist/es/rollup.js",
+ "types": "dist/rollup.d.ts",
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "napi": {
+ "binaryName": "rollup",
+ "packageName": "@rollup/rollup",
+ "targets": [
+ "aarch64-apple-darwin",
+ "aarch64-linux-android",
+ "aarch64-pc-windows-msvc",
+ "aarch64-unknown-freebsd",
+ "aarch64-unknown-linux-gnu",
+ "aarch64-unknown-linux-musl",
+ "armv7-linux-androideabi",
+ "armv7-unknown-linux-gnueabihf",
+ "armv7-unknown-linux-musleabihf",
+ "i686-pc-windows-msvc",
+ "loongarch64-unknown-linux-gnu",
+ "riscv64gc-unknown-linux-gnu",
+ "riscv64gc-unknown-linux-musl",
+ "powerpc64le-unknown-linux-gnu",
+ "s390x-unknown-linux-gnu",
+ "x86_64-apple-darwin",
+ "x86_64-pc-windows-gnu",
+ "x86_64-pc-windows-msvc",
+ "x86_64-unknown-freebsd",
+ "x86_64-unknown-linux-gnu",
+ "x86_64-unknown-linux-musl",
+ "aarch64-unknown-linux-ohos"
+ ]
+ },
+ "scripts": {
+ "build": "concurrently -c green,blue \"npm run build:wasm\" \"npm:build:ast-converters\" && concurrently -c green,blue \"npm run build:napi -- --release\" \"npm:build:js\" && npm run build:copy-native",
+ "build:quick": "concurrently -c green,blue 'npm:build:napi' 'npm:build:cjs' && npm run build:copy-native",
+ "build:napi": "napi build --cwd rust/bindings_napi --platform --dts ../../native.d.ts --no-js --output-dir ../.. --package-json-path ../../package.json",
+ "build:wasm": "wasm-pack build rust/bindings_wasm --out-dir ../../wasm --target web --no-pack && shx rm wasm/.gitignore",
+ "build:wasm:node": "wasm-pack build rust/bindings_wasm --out-dir ../../wasm-node --target nodejs --no-pack && shx rm wasm-node/.gitignore",
+ "update:napi": "npm run build:napi && npm run build:copy-native",
+ "build:js": "rollup --config rollup.config.ts --configPlugin typescript --forceExit",
+ "build:js:node": "rollup --config rollup.config.ts --configPlugin typescript --configIsBuildNode --forceExit",
+ "build:prepare": "concurrently -c green,blue \"npm run build:napi -- --release\" \"npm:build:js:node\" && npm run build:copy-native",
+ "update:js": "npm run build:js && npm run build:copy-native",
+ "build:copy-native": "shx mkdir -p dist && shx cp rollup.*.node dist/",
+ "dev": "concurrently -kc green,blue 'nodemon --watch rust -e rs --exec \"npm run build:wasm\"' 'vitepress dev docs'",
+ "build:cjs": "rollup --config rollup.config.ts --configPlugin typescript --configTest --forceExit",
+ "build:bootstrap": "shx mv dist dist-build && node dist-build/bin/rollup --config rollup.config.ts --configPlugin typescript --forceExit && shx rm -rf dist-build",
+ "build:bootstrap:cjs": "shx mv dist dist-build && node dist-build/bin/rollup --config rollup.config.ts --configPlugin typescript --configTest --forceExit && shx rm -rf dist-build",
+ "build:docs": "vitepress build docs",
+ "build:ast-converters": "node scripts/generate-ast-converters.js",
+ "preview:docs": "vitepress preview docs",
+ "ci:artifacts": "napi artifacts",
+ "ci:lint": "concurrently -c red,yellow,green,blue 'npm:lint:js:nofix' 'npm:lint:native-js' 'npm:lint:markdown:nofix' 'npm:lint:rust:nofix'",
+ "ci:test:only": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && npm run test:only",
+ "ci:test:all": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && concurrently --kill-others-on-fail -c green,blue,magenta,cyan 'npm:test:only' 'npm:test:typescript' 'npm:test:leak' 'npm:test:browser'",
+ "ci:coverage": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && NODE_OPTIONS=--no-experimental-require-module nyc --reporter lcovonly mocha",
+ "lint": "concurrently -c red,yellow,green,blue 'npm:lint:js' 'npm:lint:native-js' 'npm:lint:markdown' 'npm:lint:rust'",
+ "lint:js": "eslint . --fix --cache --concurrency auto",
+ "lint:js:nofix": "eslint . --cache --concurrency auto",
+ "lint:native-js": "node scripts/lint-native-js.js",
+ "lint:markdown": "prettier --write \"**/*.md\"",
+ "lint:markdown:nofix": "prettier --check \"**/*.md\"",
+ "lint:rust": "cd rust && cargo fmt && cargo clippy --fix --allow-dirty",
+ "lint:rust:nofix": "cd rust && cargo fmt --check && cargo clippy",
+ "perf": "npm run build:bootstrap:cjs && node --expose-gc scripts/perf-report/index.js",
+ "prepare": "husky && node scripts/check-release.js || npm run build:prepare",
+ "prepublishOnly": "node scripts/check-release.js && node scripts/prepublish.js",
+ "postpublish": "node scripts/postpublish.js",
+ "prepublish:napi": "napi prepublish --no-gh-release",
+ "release": "node scripts/prepare-release.js",
+ "release:docs": "git fetch --update-head-ok origin master:master && git branch --force documentation-published master && git push origin documentation-published",
+ "test": "npm run build && npm run test:all",
+ "test:update-snapshots": "node scripts/update-snapshots.js",
+ "test:cjs": "npm run build:cjs && npm run test:only",
+ "test:quick": "mocha -b test/test.js",
+ "test:all": "concurrently --kill-others-on-fail -c green,blue,magenta,cyan,red 'npm:test:only' 'npm:test:browser' 'npm:test:typescript' 'npm:test:package' 'npm:test:options'",
+ "test:coverage": "npm run build:cjs && shx rm -rf coverage/* && nyc --reporter html mocha test/test.js",
+ "test:coverage:browser": "npm run build && shx rm -rf coverage/* && nyc mocha test/browser/index.js",
+ "test:leak": "npm install --no-save weak-napi && node --expose-gc test/leak/index.js",
+ "test:package": "node scripts/test-package.js",
+ "test:options": "node scripts/test-options.js",
+ "test:only": "mocha test/test.js",
+ "test:typescript": "shx rm -rf test/typescript/dist && shx cp -r dist test/typescript/ && tsc --noEmit -p test/typescript && tsc --noEmit && tsc --noEmit -p scripts",
+ "test:browser": "mocha test/browser/index.js",
+ "watch": "rollup --config rollup.config.ts --configPlugin typescript --watch"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/rollup/rollup.git"
+ },
+ "keywords": [
+ "modules",
+ "bundler",
+ "bundling",
+ "es6",
+ "optimizer"
+ ],
+ "author": "Rich Harris",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/rollup/rollup/issues"
+ },
+ "homepage": "https://rollupjs.org/",
+ "optionalDependencies": {
+ "fsevents": "~2.3.2",
+ "@rollup/rollup-darwin-arm64": "4.52.5",
+ "@rollup/rollup-android-arm64": "4.52.5",
+ "@rollup/rollup-win32-arm64-msvc": "4.52.5",
+ "@rollup/rollup-freebsd-arm64": "4.52.5",
+ "@rollup/rollup-linux-arm64-gnu": "4.52.5",
+ "@rollup/rollup-linux-arm64-musl": "4.52.5",
+ "@rollup/rollup-android-arm-eabi": "4.52.5",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.52.5",
+ "@rollup/rollup-linux-arm-musleabihf": "4.52.5",
+ "@rollup/rollup-win32-ia32-msvc": "4.52.5",
+ "@rollup/rollup-linux-loong64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-musl": "4.52.5",
+ "@rollup/rollup-linux-ppc64-gnu": "4.52.5",
+ "@rollup/rollup-linux-s390x-gnu": "4.52.5",
+ "@rollup/rollup-darwin-x64": "4.52.5",
+ "@rollup/rollup-win32-x64-gnu": "4.52.5",
+ "@rollup/rollup-win32-x64-msvc": "4.52.5",
+ "@rollup/rollup-freebsd-x64": "4.52.5",
+ "@rollup/rollup-linux-x64-gnu": "4.52.5",
+ "@rollup/rollup-linux-x64-musl": "4.52.5",
+ "@rollup/rollup-openharmony-arm64": "4.52.5"
+ },
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "devDependenciesComments": {
+ "core-js": "We only update manually as every update requires a snapshot update"
+ },
+ "devDependencies": {
+ "@codemirror/commands": "^6.9.0",
+ "@codemirror/lang-javascript": "^6.2.4",
+ "@codemirror/language": "^6.11.3",
+ "@codemirror/search": "^6.5.11",
+ "@codemirror/state": "^6.5.2",
+ "@codemirror/view": "^6.38.6",
+ "@eslint/js": "^9.37.0",
+ "@inquirer/prompts": "^7.9.0",
+ "@jridgewell/sourcemap-codec": "^1.5.5",
+ "@mermaid-js/mermaid-cli": "^11.4.0",
+ "@napi-rs/cli": "^3.3.1",
+ "@rollup/plugin-alias": "^5.1.1",
+ "@rollup/plugin-buble": "^1.0.3",
+ "@rollup/plugin-commonjs": "^28.0.7",
+ "@rollup/plugin-json": "^6.1.0",
+ "@rollup/plugin-node-resolve": "^16.0.3",
+ "@rollup/plugin-replace": "^6.0.2",
+ "@rollup/plugin-terser": "^0.4.4",
+ "@rollup/plugin-typescript": "^12.1.4",
+ "@rollup/pluginutils": "^5.3.0",
+ "@shikijs/vitepress-twoslash": "^3.13.0",
+ "@types/mocha": "^10.0.10",
+ "@types/node": "^20.19.21",
+ "@types/picomatch": "^4.0.2",
+ "@types/semver": "^7.7.1",
+ "@types/yargs-parser": "^21.0.3",
+ "@vue/language-server": "^3.1.1",
+ "acorn": "^8.15.0",
+ "acorn-import-assertions": "^1.9.0",
+ "acorn-jsx": "^5.3.2",
+ "buble": "^0.20.0",
+ "builtin-modules": "^5.0.0",
+ "chokidar": "^3.6.0",
+ "concurrently": "^9.2.1",
+ "core-js": "3.38.1",
+ "cross-env": "^10.1.0",
+ "date-time": "^4.0.0",
+ "es5-shim": "^4.6.7",
+ "es6-shim": "^0.35.8",
+ "eslint": "^9.37.0",
+ "eslint-config-prettier": "^10.1.8",
+ "eslint-plugin-prettier": "^5.5.4",
+ "eslint-plugin-unicorn": "^61.0.2",
+ "eslint-plugin-vue": "^10.5.0",
+ "fixturify": "^3.0.0",
+ "flru": "^1.0.2",
+ "fs-extra": "^11.3.2",
+ "github-api": "^3.4.0",
+ "globals": "^16.4.0",
+ "husky": "^9.1.7",
+ "is-reference": "^3.0.3",
+ "lint-staged": "^16.2.4",
+ "locate-character": "^3.0.0",
+ "magic-string": "^0.30.19",
+ "memfs": "^4.49.0",
+ "mocha": "^11.7.4",
+ "nodemon": "^3.1.10",
+ "nyc": "^17.1.0",
+ "picocolors": "^1.1.1",
+ "picomatch": "^4.0.3",
+ "pinia": "^3.0.3",
+ "prettier": "^3.6.2",
+ "prettier-plugin-organize-imports": "^4.3.0",
+ "pretty-bytes": "^7.1.0",
+ "pretty-ms": "^9.3.0",
+ "requirejs": "^2.3.7",
+ "rollup": "^4.52.4",
+ "rollup-plugin-license": "^3.6.0",
+ "rollup-plugin-string": "^3.0.0",
+ "semver": "^7.7.3",
+ "shx": "^0.4.0",
+ "signal-exit": "^4.1.0",
+ "source-map": "^0.7.6",
+ "source-map-support": "^0.5.21",
+ "systemjs": "^6.15.1",
+ "terser": "^5.44.0",
+ "tslib": "^2.8.1",
+ "typescript": "^5.9.3",
+ "typescript-eslint": "^8.46.1",
+ "vite": "^7.1.10",
+ "vitepress": "^1.6.4",
+ "vue": "^3.5.22",
+ "vue-eslint-parser": "^10.2.0",
+ "vue-tsc": "^2.2.12",
+ "wasm-pack": "^0.13.1",
+ "yargs-parser": "^21.1.1"
+ },
+ "overrides": {
+ "axios": "^1.12.2",
+ "semver": "^7.7.3",
+ "readable-stream": "npm:@built-in/readable-stream@1",
+ "esbuild": ">0.24.2"
+ },
+ "comments": {
+ "vue-tsc": "This is necessary so that prettier-plugin-organize-imports works correctly in Vue templatges"
+ },
+ "files": [
+ "dist/*.node",
+ "dist/**/*.js",
+ "dist/*.d.ts",
+ "dist/bin/rollup",
+ "dist/es/package.json"
+ ],
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/rollup.d.ts",
+ "import": "./dist/es/rollup.js",
+ "require": "./dist/rollup.js"
+ },
+ "./loadConfigFile": {
+ "types": "./dist/loadConfigFile.d.ts",
+ "require": "./dist/loadConfigFile.js",
+ "default": "./dist/loadConfigFile.js"
+ },
+ "./getLogFilter": {
+ "types": "./dist/getLogFilter.d.ts",
+ "import": "./dist/es/getLogFilter.js",
+ "require": "./dist/getLogFilter.js"
+ },
+ "./parseAst": {
+ "types": "./dist/parseAst.d.ts",
+ "import": "./dist/es/parseAst.js",
+ "require": "./dist/parseAst.js"
+ },
+ "./dist/*": "./dist/*",
+ "./package.json": "./package.json"
+ }
+}
\ No newline at end of file
diff --git a/frontend/node_modules/source-map-js/LICENSE b/frontend/node_modules/source-map-js/LICENSE
new file mode 100644
index 0000000..ed1b7cf
--- /dev/null
+++ b/frontend/node_modules/source-map-js/LICENSE
@@ -0,0 +1,28 @@
+
+Copyright (c) 2009-2011, Mozilla Foundation and contributors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the names of the Mozilla Foundation nor the names of project
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/frontend/node_modules/source-map-js/README.md b/frontend/node_modules/source-map-js/README.md
new file mode 100644
index 0000000..614962d
--- /dev/null
+++ b/frontend/node_modules/source-map-js/README.md
@@ -0,0 +1,765 @@
+# Source Map JS
+
+[![NPM](https://nodei.co/npm/source-map-js.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map-js)
+
+Difference between original [source-map](https://github.com/mozilla/source-map):
+
+> TL,DR: it's fork of original [email protected], but with perfomance optimizations.
+
+This journey starts from [[email protected]](https://github.com/mozilla/source-map/blob/master/CHANGELOG.md#070). Some part of it was rewritten to Rust and WASM and API became async.
+
+It's still a major block for many libraries like PostCSS or Sass for example because they need to migrate the whole API to the async way. This is the reason why 0.6.1 has 2x more downloads than 0.7.3 while it's faster several times.
+
+![Downloads count](media/downloads.png)
+
+More important that WASM version has some optimizations in JS code too. This is why [community asked to create branch for 0.6 version](https://github.com/mozilla/source-map/issues/324) and port these optimizations but, sadly, the answer was «no». A bit later I discovered [the issue](https://github.com/mozilla/source-map/issues/370) created by [Ben Rothman (@benthemonkey)](https://github.com/benthemonkey) with no response at all.
+
+[Roman Dvornov (@lahmatiy)](https://github.com/lahmatiy) wrote a [serveral posts](https://t.me/gorshochekvarit/76) (russian, only, sorry) about source-map library in his own Telegram channel. He mentioned the article [«Maybe you don't need Rust and WASM to speed up your JS»](https://mrale.ph/blog/2018/02/03/maybe-you-dont-need-rust-to-speed-up-your-js.html) written by [Vyacheslav Egorov (@mraleph)](https://github.com/mraleph). This article contains optimizations and hacks that lead to almost the same performance compare to WASM implementation.
+
+I decided to fork the original source-map and port these optimizations from the article and several others PR from the original source-map.
+
+---------
+
+This is a library to generate and consume the source map format
+[described here][format].
+
+[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
+
+## Use with Node
+
+ $ npm install source-map-js
+
+<!-- ## Use on the Web
+
+ <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -->
+
+--------------------------------------------------------------------------------
+
+<!-- `npm run toc` to regenerate the Table of Contents -->
+
+<!-- START doctoc generated TOC please keep comment here to allow auto update -->
+<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
+## Table of Contents
+
+- [Examples](#examples)
+ - [Consuming a source map](#consuming-a-source-map)
+ - [Generating a source map](#generating-a-source-map)
+ - [With SourceNode (high level API)](#with-sourcenode-high-level-api)
+ - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
+- [API](#api)
+ - [SourceMapConsumer](#sourcemapconsumer)
+ - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
+ - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
+ - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
+ - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
+ - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
+ - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
+ - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
+ - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
+ - [SourceMapGenerator](#sourcemapgenerator)
+ - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
+ - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
+ - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
+ - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
+ - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
+ - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
+ - [SourceNode](#sourcenode)
+ - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
+ - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
+ - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
+ - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
+ - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
+ - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
+ - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
+ - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
+ - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
+ - [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
+ - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
+
+<!-- END doctoc generated TOC please keep comment here to allow auto update -->
+
+## Examples
+
+### Consuming a source map
+
+```js
+var rawSourceMap = {
+ version: 3,
+ file: 'min.js',
+ names: ['bar', 'baz', 'n'],
+ sources: ['one.js', 'two.js'],
+ sourceRoot: 'http://example.com/www/js/',
+ mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
+};
+
+var smc = new SourceMapConsumer(rawSourceMap);
+
+console.log(smc.sources);
+// [ 'http://example.com/www/js/one.js',
+// 'http://example.com/www/js/two.js' ]
+
+console.log(smc.originalPositionFor({
+ line: 2,
+ column: 28
+}));
+// { source: 'http://example.com/www/js/two.js',
+// line: 2,
+// column: 10,
+// name: 'n' }
+
+console.log(smc.generatedPositionFor({
+ source: 'http://example.com/www/js/two.js',
+ line: 2,
+ column: 10
+}));
+// { line: 2, column: 28 }
+
+smc.eachMapping(function (m) {
+ // ...
+});
+```
+
+### Generating a source map
+
+In depth guide:
+[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
+
+#### With SourceNode (high level API)
+
+```js
+function compile(ast) {
+ switch (ast.type) {
+ case 'BinaryExpression':
+ return new SourceNode(
+ ast.location.line,
+ ast.location.column,
+ ast.location.source,
+ [compile(ast.left), " + ", compile(ast.right)]
+ );
+ case 'Literal':
+ return new SourceNode(
+ ast.location.line,
+ ast.location.column,
+ ast.location.source,
+ String(ast.value)
+ );
+ // ...
+ default:
+ throw new Error("Bad AST");
+ }
+}
+
+var ast = parse("40 + 2", "add.js");
+console.log(compile(ast).toStringWithSourceMap({
+ file: 'add.js'
+}));
+// { code: '40 + 2',
+// map: [object SourceMapGenerator] }
+```
+
+#### With SourceMapGenerator (low level API)
+
+```js
+var map = new SourceMapGenerator({
+ file: "source-mapped.js"
+});
+
+map.addMapping({
+ generated: {
+ line: 10,
+ column: 35
+ },
+ source: "foo.js",
+ original: {
+ line: 33,
+ column: 2
+ },
+ name: "christopher"
+});
+
+console.log(map.toString());
+// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
+```
+
+## API
+
+Get a reference to the module:
+
+```js
+// Node.js
+var sourceMap = require('source-map');
+
+// Browser builds
+var sourceMap = window.sourceMap;
+
+// Inside Firefox
+const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
+```
+
+### SourceMapConsumer
+
+A SourceMapConsumer instance represents a parsed source map which we can query
+for information about the original file positions by giving it a file position
+in the generated source.
+
+#### new SourceMapConsumer(rawSourceMap)
+
+The only parameter is the raw source map (either as a string which can be
+`JSON.parse`'d, or an object). According to the spec, source maps have the
+following attributes:
+
+* `version`: Which version of the source map spec this map is following.
+
+* `sources`: An array of URLs to the original source files.
+
+* `names`: An array of identifiers which can be referenced by individual
+ mappings.
+
+* `sourceRoot`: Optional. The URL root from which all sources are relative.
+
+* `sourcesContent`: Optional. An array of contents of the original source files.
+
+* `mappings`: A string of base64 VLQs which contain the actual mappings.
+
+* `file`: Optional. The generated filename this source map is associated with.
+
+```js
+var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
+```
+
+#### SourceMapConsumer.prototype.computeColumnSpans()
+
+Compute the last column for each generated mapping. The last column is
+inclusive.
+
+```js
+// Before:
+consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
+// [ { line: 2,
+// column: 1 },
+// { line: 2,
+// column: 10 },
+// { line: 2,
+// column: 20 } ]
+
+consumer.computeColumnSpans();
+
+// After:
+consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
+// [ { line: 2,
+// column: 1,
+// lastColumn: 9 },
+// { line: 2,
+// column: 10,
+// lastColumn: 19 },
+// { line: 2,
+// column: 20,
+// lastColumn: Infinity } ]
+
+```
+
+#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
+
+Returns the original source, line, and column information for the generated
+source's line and column positions provided. The only argument is an object with
+the following properties:
+
+* `line`: The line number in the generated source. Line numbers in
+ this library are 1-based (note that the underlying source map
+ specification uses 0-based line numbers -- this library handles the
+ translation).
+
+* `column`: The column number in the generated source. Column numbers
+ in this library are 0-based.
+
+* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
+ `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
+ element that is smaller than or greater than the one we are searching for,
+ respectively, if the exact element cannot be found. Defaults to
+ `SourceMapConsumer.GREATEST_LOWER_BOUND`.
+
+and an object is returned with the following properties:
+
+* `source`: The original source file, or null if this information is not
+ available.
+
+* `line`: The line number in the original source, or null if this information is
+ not available. The line number is 1-based.
+
+* `column`: The column number in the original source, or null if this
+ information is not available. The column number is 0-based.
+
+* `name`: The original identifier, or null if this information is not available.
+
+```js
+consumer.originalPositionFor({ line: 2, column: 10 })
+// { source: 'foo.coffee',
+// line: 2,
+// column: 2,
+// name: null }
+
+consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
+// { source: null,
+// line: null,
+// column: null,
+// name: null }
+```
+
+#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
+
+Returns the generated line and column information for the original source,
+line, and column positions provided. The only argument is an object with
+the following properties:
+
+* `source`: The filename of the original source.
+
+* `line`: The line number in the original source. The line number is
+ 1-based.
+
+* `column`: The column number in the original source. The column
+ number is 0-based.
+
+and an object is returned with the following properties:
+
+* `line`: The line number in the generated source, or null. The line
+ number is 1-based.
+
+* `column`: The column number in the generated source, or null. The
+ column number is 0-based.
+
+```js
+consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
+// { line: 1,
+// column: 56 }
+```
+
+#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
+
+Returns all generated line and column information for the original source, line,
+and column provided. If no column is provided, returns all mappings
+corresponding to a either the line we are searching for or the next closest line
+that has any mappings. Otherwise, returns all mappings corresponding to the
+given line and either the column we are searching for or the next closest column
+that has any offsets.
+
+The only argument is an object with the following properties:
+
+* `source`: The filename of the original source.
+
+* `line`: The line number in the original source. The line number is
+ 1-based.
+
+* `column`: Optional. The column number in the original source. The
+ column number is 0-based.
+
+and an array of objects is returned, each with the following properties:
+
+* `line`: The line number in the generated source, or null. The line
+ number is 1-based.
+
+* `column`: The column number in the generated source, or null. The
+ column number is 0-based.
+
+```js
+consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
+// [ { line: 2,
+// column: 1 },
+// { line: 2,
+// column: 10 },
+// { line: 2,
+// column: 20 } ]
+```
+
+#### SourceMapConsumer.prototype.hasContentsOfAllSources()
+
+Return true if we have the embedded source content for every source listed in
+the source map, false otherwise.
+
+In other words, if this method returns `true`, then
+`consumer.sourceContentFor(s)` will succeed for every source `s` in
+`consumer.sources`.
+
+```js
+// ...
+if (consumer.hasContentsOfAllSources()) {
+ consumerReadyCallback(consumer);
+} else {
+ fetchSources(consumer, consumerReadyCallback);
+}
+// ...
+```
+
+#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
+
+Returns the original source content for the source provided. The only
+argument is the URL of the original source file.
+
+If the source content for the given source is not found, then an error is
+thrown. Optionally, pass `true` as the second param to have `null` returned
+instead.
+
+```js
+consumer.sources
+// [ "my-cool-lib.clj" ]
+
+consumer.sourceContentFor("my-cool-lib.clj")
+// "..."
+
+consumer.sourceContentFor("this is not in the source map");
+// Error: "this is not in the source map" is not in the source map
+
+consumer.sourceContentFor("this is not in the source map", true);
+// null
+```
+
+#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
+
+Iterate over each mapping between an original source/line/column and a
+generated line/column in this source map.
+
+* `callback`: The function that is called with each mapping. Mappings have the
+ form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
+ name }`
+
+* `context`: Optional. If specified, this object will be the value of `this`
+ every time that `callback` is called.
+
+* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
+ `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
+ the mappings sorted by the generated file's line/column order or the
+ original's source/line/column order, respectively. Defaults to
+ `SourceMapConsumer.GENERATED_ORDER`.
+
+```js
+consumer.eachMapping(function (m) { console.log(m); })
+// ...
+// { source: 'illmatic.js',
+// generatedLine: 1,
+// generatedColumn: 0,
+// originalLine: 1,
+// originalColumn: 0,
+// name: null }
+// { source: 'illmatic.js',
+// generatedLine: 2,
+// generatedColumn: 0,
+// originalLine: 2,
+// originalColumn: 0,
+// name: null }
+// ...
+```
+### SourceMapGenerator
+
+An instance of the SourceMapGenerator represents a source map which is being
+built incrementally.
+
+#### new SourceMapGenerator([startOfSourceMap])
+
+You may pass an object with the following properties:
+
+* `file`: The filename of the generated source that this source map is
+ associated with.
+
+* `sourceRoot`: A root for all relative URLs in this source map.
+
+* `skipValidation`: Optional. When `true`, disables validation of mappings as
+ they are added. This can improve performance but should be used with
+ discretion, as a last resort. Even then, one should avoid using this flag when
+ running tests, if possible.
+
+* `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on
+ invalid mapping, it will be ignored.
+
+```js
+var generator = new sourceMap.SourceMapGenerator({
+ file: "my-generated-javascript-file.js",
+ sourceRoot: "http://example.com/app/js/"
+});
+```
+
+#### SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions)
+
+Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
+
+* `sourceMapConsumer` The SourceMap.
+
+* `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood.
+
+```js
+var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, {
+ ignoreInvalidMapping: true,
+});
+```
+
+#### SourceMapGenerator.prototype.addMapping(mapping)
+
+Add a single mapping from original source line and column to the generated
+source's line and column for this source map being created. The mapping object
+should have the following properties:
+
+* `generated`: An object with the generated line and column positions.
+
+* `original`: An object with the original line and column positions.
+
+* `source`: The original source file (relative to the sourceRoot).
+
+* `name`: An optional original token name for this mapping.
+
+```js
+generator.addMapping({
+ source: "module-one.scm",
+ original: { line: 128, column: 0 },
+ generated: { line: 3, column: 456 }
+})
+```
+
+#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
+
+Set the source content for an original source file.
+
+* `sourceFile` the URL of the original source file.
+
+* `sourceContent` the content of the source file.
+
+```js
+generator.setSourceContent("module-one.scm",
+ fs.readFileSync("path/to/module-one.scm"))
+```
+
+#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
+
+Applies a SourceMap for a source file to the SourceMap.
+Each mapping to the supplied source file is rewritten using the
+supplied SourceMap. Note: The resolution for the resulting mappings
+is the minimum of this map and the supplied map.
+
+* `sourceMapConsumer`: The SourceMap to be applied.
+
+* `sourceFile`: Optional. The filename of the source file.
+ If omitted, sourceMapConsumer.file will be used, if it exists.
+ Otherwise an error will be thrown.
+
+* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
+ to be applied. If relative, it is relative to the SourceMap.
+
+ This parameter is needed when the two SourceMaps aren't in the same
+ directory, and the SourceMap to be applied contains relative source
+ paths. If so, those relative source paths need to be rewritten
+ relative to the SourceMap.
+
+ If omitted, it is assumed that both SourceMaps are in the same directory,
+ thus not needing any rewriting. (Supplying `'.'` has the same effect.)
+
+#### SourceMapGenerator.prototype.toString()
+
+Renders the source map being generated to a string.
+
+```js
+generator.toString()
+// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
+```
+
+### SourceNode
+
+SourceNodes provide a way to abstract over interpolating and/or concatenating
+snippets of generated JavaScript source code, while maintaining the line and
+column information associated between those snippets and the original source
+code. This is useful as the final intermediate representation a compiler might
+use before outputting the generated JS and source map.
+
+#### new SourceNode([line, column, source[, chunk[, name]]])
+
+* `line`: The original line number associated with this source node, or null if
+ it isn't associated with an original line. The line number is 1-based.
+
+* `column`: The original column number associated with this source node, or null
+ if it isn't associated with an original column. The column number
+ is 0-based.
+
+* `source`: The original source's filename; null if no filename is provided.
+
+* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
+ below.
+
+* `name`: Optional. The original identifier.
+
+```js
+var node = new SourceNode(1, 2, "a.cpp", [
+ new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
+ new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
+ new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
+]);
+```
+
+#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
+
+Creates a SourceNode from generated code and a SourceMapConsumer.
+
+* `code`: The generated code
+
+* `sourceMapConsumer` The SourceMap for the generated code
+
+* `relativePath` The optional path that relative sources in `sourceMapConsumer`
+ should be relative to.
+
+```js
+var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
+var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
+ consumer);
+```
+
+#### SourceNode.prototype.add(chunk)
+
+Add a chunk of generated JS to this source node.
+
+* `chunk`: A string snippet of generated JS code, another instance of
+ `SourceNode`, or an array where each member is one of those things.
+
+```js
+node.add(" + ");
+node.add(otherNode);
+node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
+```
+
+#### SourceNode.prototype.prepend(chunk)
+
+Prepend a chunk of generated JS to this source node.
+
+* `chunk`: A string snippet of generated JS code, another instance of
+ `SourceNode`, or an array where each member is one of those things.
+
+```js
+node.prepend("/** Build Id: f783haef86324gf **/\n\n");
+```
+
+#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
+
+Set the source content for a source file. This will be added to the
+`SourceMap` in the `sourcesContent` field.
+
+* `sourceFile`: The filename of the source file
+
+* `sourceContent`: The content of the source file
+
+```js
+node.setSourceContent("module-one.scm",
+ fs.readFileSync("path/to/module-one.scm"))
+```
+
+#### SourceNode.prototype.walk(fn)
+
+Walk over the tree of JS snippets in this node and its children. The walking
+function is called once for each snippet of JS and is passed that snippet and
+the its original associated source's line/column location.
+
+* `fn`: The traversal function.
+
+```js
+var node = new SourceNode(1, 2, "a.js", [
+ new SourceNode(3, 4, "b.js", "uno"),
+ "dos",
+ [
+ "tres",
+ new SourceNode(5, 6, "c.js", "quatro")
+ ]
+]);
+
+node.walk(function (code, loc) { console.log("WALK:", code, loc); })
+// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
+// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
+// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
+// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
+```
+
+#### SourceNode.prototype.walkSourceContents(fn)
+
+Walk over the tree of SourceNodes. The walking function is called for each
+source file content and is passed the filename and source content.
+
+* `fn`: The traversal function.
+
+```js
+var a = new SourceNode(1, 2, "a.js", "generated from a");
+a.setSourceContent("a.js", "original a");
+var b = new SourceNode(1, 2, "b.js", "generated from b");
+b.setSourceContent("b.js", "original b");
+var c = new SourceNode(1, 2, "c.js", "generated from c");
+c.setSourceContent("c.js", "original c");
+
+var node = new SourceNode(null, null, null, [a, b, c]);
+node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
+// WALK: a.js : original a
+// WALK: b.js : original b
+// WALK: c.js : original c
+```
+
+#### SourceNode.prototype.join(sep)
+
+Like `Array.prototype.join` except for SourceNodes. Inserts the separator
+between each of this source node's children.
+
+* `sep`: The separator.
+
+```js
+var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
+var operand = new SourceNode(3, 4, "a.rs", "=");
+var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
+
+var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
+var joinedNode = node.join(" ");
+```
+
+#### SourceNode.prototype.replaceRight(pattern, replacement)
+
+Call `String.prototype.replace` on the very right-most source snippet. Useful
+for trimming white space from the end of a source node, etc.
+
+* `pattern`: The pattern to replace.
+
+* `replacement`: The thing to replace the pattern with.
+
+```js
+// Trim trailing white space.
+node.replaceRight(/\s*$/, "");
+```
+
+#### SourceNode.prototype.toString()
+
+Return the string representation of this source node. Walks over the tree and
+concatenates all the various snippets together to one string.
+
+```js
+var node = new SourceNode(1, 2, "a.js", [
+ new SourceNode(3, 4, "b.js", "uno"),
+ "dos",
+ [
+ "tres",
+ new SourceNode(5, 6, "c.js", "quatro")
+ ]
+]);
+
+node.toString()
+// 'unodostresquatro'
+```
+
+#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
+
+Returns the string representation of this tree of source nodes, plus a
+SourceMapGenerator which contains all the mappings between the generated and
+original sources.
+
+The arguments are the same as those to `new SourceMapGenerator`.
+
+```js
+var node = new SourceNode(1, 2, "a.js", [
+ new SourceNode(3, 4, "b.js", "uno"),
+ "dos",
+ [
+ "tres",
+ new SourceNode(5, 6, "c.js", "quatro")
+ ]
+]);
+
+node.toStringWithSourceMap({ file: "my-output-file.js" })
+// { code: 'unodostresquatro',
+// map: [object SourceMapGenerator] }
+```
diff --git a/frontend/node_modules/source-map-js/lib/array-set.js b/frontend/node_modules/source-map-js/lib/array-set.js
new file mode 100644
index 0000000..fbd5c81
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/array-set.js
@@ -0,0 +1,121 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var util = require('./util');
+var has = Object.prototype.hasOwnProperty;
+var hasNativeMap = typeof Map !== "undefined";
+
+/**
+ * A data structure which is a combination of an array and a set. Adding a new
+ * member is O(1), testing for membership is O(1), and finding the index of an
+ * element is O(1). Removing elements from the set is not supported. Only
+ * strings are supported for membership.
+ */
+function ArraySet() {
+ this._array = [];
+ this._set = hasNativeMap ? new Map() : Object.create(null);
+}
+
+/**
+ * Static method for creating ArraySet instances from an existing array.
+ */
+ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
+ var set = new ArraySet();
+ for (var i = 0, len = aArray.length; i < len; i++) {
+ set.add(aArray[i], aAllowDuplicates);
+ }
+ return set;
+};
+
+/**
+ * Return how many unique items are in this ArraySet. If duplicates have been
+ * added, than those do not count towards the size.
+ *
+ * @returns Number
+ */
+ArraySet.prototype.size = function ArraySet_size() {
+ return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
+};
+
+/**
+ * Add the given string to this set.
+ *
+ * @param String aStr
+ */
+ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
+ var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
+ var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
+ var idx = this._array.length;
+ if (!isDuplicate || aAllowDuplicates) {
+ this._array.push(aStr);
+ }
+ if (!isDuplicate) {
+ if (hasNativeMap) {
+ this._set.set(aStr, idx);
+ } else {
+ this._set[sStr] = idx;
+ }
+ }
+};
+
+/**
+ * Is the given string a member of this set?
+ *
+ * @param String aStr
+ */
+ArraySet.prototype.has = function ArraySet_has(aStr) {
+ if (hasNativeMap) {
+ return this._set.has(aStr);
+ } else {
+ var sStr = util.toSetString(aStr);
+ return has.call(this._set, sStr);
+ }
+};
+
+/**
+ * What is the index of the given string in the array?
+ *
+ * @param String aStr
+ */
+ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
+ if (hasNativeMap) {
+ var idx = this._set.get(aStr);
+ if (idx >= 0) {
+ return idx;
+ }
+ } else {
+ var sStr = util.toSetString(aStr);
+ if (has.call(this._set, sStr)) {
+ return this._set[sStr];
+ }
+ }
+
+ throw new Error('"' + aStr + '" is not in the set.');
+};
+
+/**
+ * What is the element at the given index?
+ *
+ * @param Number aIdx
+ */
+ArraySet.prototype.at = function ArraySet_at(aIdx) {
+ if (aIdx >= 0 && aIdx < this._array.length) {
+ return this._array[aIdx];
+ }
+ throw new Error('No element indexed by ' + aIdx);
+};
+
+/**
+ * Returns the array representation of this set (which has the proper indices
+ * indicated by indexOf). Note that this is a copy of the internal array used
+ * for storing the members so that no one can mess with internal state.
+ */
+ArraySet.prototype.toArray = function ArraySet_toArray() {
+ return this._array.slice();
+};
+
+exports.ArraySet = ArraySet;
diff --git a/frontend/node_modules/source-map-js/lib/base64-vlq.js b/frontend/node_modules/source-map-js/lib/base64-vlq.js
new file mode 100644
index 0000000..612b404
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/base64-vlq.js
@@ -0,0 +1,140 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ *
+ * Based on the Base 64 VLQ implementation in Closure Compiler:
+ * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
+ *
+ * Copyright 2011 The Closure Compiler Authors. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+var base64 = require('./base64');
+
+// A single base 64 digit can contain 6 bits of data. For the base 64 variable
+// length quantities we use in the source map spec, the first bit is the sign,
+// the next four bits are the actual value, and the 6th bit is the
+// continuation bit. The continuation bit tells us whether there are more
+// digits in this value following this digit.
+//
+// Continuation
+// | Sign
+// | |
+// V V
+// 101011
+
+var VLQ_BASE_SHIFT = 5;
+
+// binary: 100000
+var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
+
+// binary: 011111
+var VLQ_BASE_MASK = VLQ_BASE - 1;
+
+// binary: 100000
+var VLQ_CONTINUATION_BIT = VLQ_BASE;
+
+/**
+ * Converts from a two-complement value to a value where the sign bit is
+ * placed in the least significant bit. For example, as decimals:
+ * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
+ * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
+ */
+function toVLQSigned(aValue) {
+ return aValue < 0
+ ? ((-aValue) << 1) + 1
+ : (aValue << 1) + 0;
+}
+
+/**
+ * Converts to a two-complement value from a value where the sign bit is
+ * placed in the least significant bit. For example, as decimals:
+ * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
+ * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
+ */
+function fromVLQSigned(aValue) {
+ var isNegative = (aValue & 1) === 1;
+ var shifted = aValue >> 1;
+ return isNegative
+ ? -shifted
+ : shifted;
+}
+
+/**
+ * Returns the base 64 VLQ encoded value.
+ */
+exports.encode = function base64VLQ_encode(aValue) {
+ var encoded = "";
+ var digit;
+
+ var vlq = toVLQSigned(aValue);
+
+ do {
+ digit = vlq & VLQ_BASE_MASK;
+ vlq >>>= VLQ_BASE_SHIFT;
+ if (vlq > 0) {
+ // There are still more digits in this value, so we must make sure the
+ // continuation bit is marked.
+ digit |= VLQ_CONTINUATION_BIT;
+ }
+ encoded += base64.encode(digit);
+ } while (vlq > 0);
+
+ return encoded;
+};
+
+/**
+ * Decodes the next base 64 VLQ value from the given string and returns the
+ * value and the rest of the string via the out parameter.
+ */
+exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
+ var strLen = aStr.length;
+ var result = 0;
+ var shift = 0;
+ var continuation, digit;
+
+ do {
+ if (aIndex >= strLen) {
+ throw new Error("Expected more digits in base 64 VLQ value.");
+ }
+
+ digit = base64.decode(aStr.charCodeAt(aIndex++));
+ if (digit === -1) {
+ throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
+ }
+
+ continuation = !!(digit & VLQ_CONTINUATION_BIT);
+ digit &= VLQ_BASE_MASK;
+ result = result + (digit << shift);
+ shift += VLQ_BASE_SHIFT;
+ } while (continuation);
+
+ aOutParam.value = fromVLQSigned(result);
+ aOutParam.rest = aIndex;
+};
diff --git a/frontend/node_modules/source-map-js/lib/base64.js b/frontend/node_modules/source-map-js/lib/base64.js
new file mode 100644
index 0000000..8aa86b3
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/base64.js
@@ -0,0 +1,67 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
+
+/**
+ * Encode an integer in the range of 0 to 63 to a single base 64 digit.
+ */
+exports.encode = function (number) {
+ if (0 <= number && number < intToCharMap.length) {
+ return intToCharMap[number];
+ }
+ throw new TypeError("Must be between 0 and 63: " + number);
+};
+
+/**
+ * Decode a single base 64 character code digit to an integer. Returns -1 on
+ * failure.
+ */
+exports.decode = function (charCode) {
+ var bigA = 65; // 'A'
+ var bigZ = 90; // 'Z'
+
+ var littleA = 97; // 'a'
+ var littleZ = 122; // 'z'
+
+ var zero = 48; // '0'
+ var nine = 57; // '9'
+
+ var plus = 43; // '+'
+ var slash = 47; // '/'
+
+ var littleOffset = 26;
+ var numberOffset = 52;
+
+ // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
+ if (bigA <= charCode && charCode <= bigZ) {
+ return (charCode - bigA);
+ }
+
+ // 26 - 51: abcdefghijklmnopqrstuvwxyz
+ if (littleA <= charCode && charCode <= littleZ) {
+ return (charCode - littleA + littleOffset);
+ }
+
+ // 52 - 61: 0123456789
+ if (zero <= charCode && charCode <= nine) {
+ return (charCode - zero + numberOffset);
+ }
+
+ // 62: +
+ if (charCode == plus) {
+ return 62;
+ }
+
+ // 63: /
+ if (charCode == slash) {
+ return 63;
+ }
+
+ // Invalid base64 digit.
+ return -1;
+};
diff --git a/frontend/node_modules/source-map-js/lib/binary-search.js b/frontend/node_modules/source-map-js/lib/binary-search.js
new file mode 100644
index 0000000..010ac94
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/binary-search.js
@@ -0,0 +1,111 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+exports.GREATEST_LOWER_BOUND = 1;
+exports.LEAST_UPPER_BOUND = 2;
+
+/**
+ * Recursive implementation of binary search.
+ *
+ * @param aLow Indices here and lower do not contain the needle.
+ * @param aHigh Indices here and higher do not contain the needle.
+ * @param aNeedle The element being searched for.
+ * @param aHaystack The non-empty array being searched.
+ * @param aCompare Function which takes two elements and returns -1, 0, or 1.
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ */
+function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
+ // This function terminates when one of the following is true:
+ //
+ // 1. We find the exact element we are looking for.
+ //
+ // 2. We did not find the exact element, but we can return the index of
+ // the next-closest element.
+ //
+ // 3. We did not find the exact element, and there is no next-closest
+ // element than the one we are searching for, so we return -1.
+ var mid = Math.floor((aHigh - aLow) / 2) + aLow;
+ var cmp = aCompare(aNeedle, aHaystack[mid], true);
+ if (cmp === 0) {
+ // Found the element we are looking for.
+ return mid;
+ }
+ else if (cmp > 0) {
+ // Our needle is greater than aHaystack[mid].
+ if (aHigh - mid > 1) {
+ // The element is in the upper half.
+ return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
+ }
+
+ // The exact needle element was not found in this haystack. Determine if
+ // we are in termination case (3) or (2) and return the appropriate thing.
+ if (aBias == exports.LEAST_UPPER_BOUND) {
+ return aHigh < aHaystack.length ? aHigh : -1;
+ } else {
+ return mid;
+ }
+ }
+ else {
+ // Our needle is less than aHaystack[mid].
+ if (mid - aLow > 1) {
+ // The element is in the lower half.
+ return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
+ }
+
+ // we are in termination case (3) or (2) and return the appropriate thing.
+ if (aBias == exports.LEAST_UPPER_BOUND) {
+ return mid;
+ } else {
+ return aLow < 0 ? -1 : aLow;
+ }
+ }
+}
+
+/**
+ * This is an implementation of binary search which will always try and return
+ * the index of the closest element if there is no exact hit. This is because
+ * mappings between original and generated line/col pairs are single points,
+ * and there is an implicit region between each of them, so a miss just means
+ * that you aren't on the very start of a region.
+ *
+ * @param aNeedle The element you are looking for.
+ * @param aHaystack The array that is being searched.
+ * @param aCompare A function which takes the needle and an element in the
+ * array and returns -1, 0, or 1 depending on whether the needle is less
+ * than, equal to, or greater than the element, respectively.
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
+ */
+exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
+ if (aHaystack.length === 0) {
+ return -1;
+ }
+
+ var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
+ aCompare, aBias || exports.GREATEST_LOWER_BOUND);
+ if (index < 0) {
+ return -1;
+ }
+
+ // We have found either the exact element, or the next-closest element than
+ // the one we are searching for. However, there may be more than one such
+ // element. Make sure we always return the smallest of these.
+ while (index - 1 >= 0) {
+ if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
+ break;
+ }
+ --index;
+ }
+
+ return index;
+};
diff --git a/frontend/node_modules/source-map-js/lib/mapping-list.js b/frontend/node_modules/source-map-js/lib/mapping-list.js
new file mode 100644
index 0000000..06d1274
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/mapping-list.js
@@ -0,0 +1,79 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2014 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var util = require('./util');
+
+/**
+ * Determine whether mappingB is after mappingA with respect to generated
+ * position.
+ */
+function generatedPositionAfter(mappingA, mappingB) {
+ // Optimized for most common case
+ var lineA = mappingA.generatedLine;
+ var lineB = mappingB.generatedLine;
+ var columnA = mappingA.generatedColumn;
+ var columnB = mappingB.generatedColumn;
+ return lineB > lineA || lineB == lineA && columnB >= columnA ||
+ util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
+}
+
+/**
+ * A data structure to provide a sorted view of accumulated mappings in a
+ * performance conscious manner. It trades a neglibable overhead in general
+ * case for a large speedup in case of mappings being added in order.
+ */
+function MappingList() {
+ this._array = [];
+ this._sorted = true;
+ // Serves as infimum
+ this._last = {generatedLine: -1, generatedColumn: 0};
+}
+
+/**
+ * Iterate through internal items. This method takes the same arguments that
+ * `Array.prototype.forEach` takes.
+ *
+ * NOTE: The order of the mappings is NOT guaranteed.
+ */
+MappingList.prototype.unsortedForEach =
+ function MappingList_forEach(aCallback, aThisArg) {
+ this._array.forEach(aCallback, aThisArg);
+ };
+
+/**
+ * Add the given source mapping.
+ *
+ * @param Object aMapping
+ */
+MappingList.prototype.add = function MappingList_add(aMapping) {
+ if (generatedPositionAfter(this._last, aMapping)) {
+ this._last = aMapping;
+ this._array.push(aMapping);
+ } else {
+ this._sorted = false;
+ this._array.push(aMapping);
+ }
+};
+
+/**
+ * Returns the flat, sorted array of mappings. The mappings are sorted by
+ * generated position.
+ *
+ * WARNING: This method returns internal data without copying, for
+ * performance. The return value must NOT be mutated, and should be treated as
+ * an immutable borrow. If you want to take ownership, you must make your own
+ * copy.
+ */
+MappingList.prototype.toArray = function MappingList_toArray() {
+ if (!this._sorted) {
+ this._array.sort(util.compareByGeneratedPositionsInflated);
+ this._sorted = true;
+ }
+ return this._array;
+};
+
+exports.MappingList = MappingList;
diff --git a/frontend/node_modules/source-map-js/lib/quick-sort.js b/frontend/node_modules/source-map-js/lib/quick-sort.js
new file mode 100644
index 0000000..23f9eda
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/quick-sort.js
@@ -0,0 +1,132 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+// It turns out that some (most?) JavaScript engines don't self-host
+// `Array.prototype.sort`. This makes sense because C++ will likely remain
+// faster than JS when doing raw CPU-intensive sorting. However, when using a
+// custom comparator function, calling back and forth between the VM's C++ and
+// JIT'd JS is rather slow *and* loses JIT type information, resulting in
+// worse generated code for the comparator function than would be optimal. In
+// fact, when sorting with a comparator, these costs outweigh the benefits of
+// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
+// a ~3500ms mean speed-up in `bench/bench.html`.
+
+function SortTemplate(comparator) {
+
+/**
+ * Swap the elements indexed by `x` and `y` in the array `ary`.
+ *
+ * @param {Array} ary
+ * The array.
+ * @param {Number} x
+ * The index of the first item.
+ * @param {Number} y
+ * The index of the second item.
+ */
+function swap(ary, x, y) {
+ var temp = ary[x];
+ ary[x] = ary[y];
+ ary[y] = temp;
+}
+
+/**
+ * Returns a random integer within the range `low .. high` inclusive.
+ *
+ * @param {Number} low
+ * The lower bound on the range.
+ * @param {Number} high
+ * The upper bound on the range.
+ */
+function randomIntInRange(low, high) {
+ return Math.round(low + (Math.random() * (high - low)));
+}
+
+/**
+ * The Quick Sort algorithm.
+ *
+ * @param {Array} ary
+ * An array to sort.
+ * @param {function} comparator
+ * Function to use to compare two items.
+ * @param {Number} p
+ * Start index of the array
+ * @param {Number} r
+ * End index of the array
+ */
+function doQuickSort(ary, comparator, p, r) {
+ // If our lower bound is less than our upper bound, we (1) partition the
+ // array into two pieces and (2) recurse on each half. If it is not, this is
+ // the empty array and our base case.
+
+ if (p < r) {
+ // (1) Partitioning.
+ //
+ // The partitioning chooses a pivot between `p` and `r` and moves all
+ // elements that are less than or equal to the pivot to the before it, and
+ // all the elements that are greater than it after it. The effect is that
+ // once partition is done, the pivot is in the exact place it will be when
+ // the array is put in sorted order, and it will not need to be moved
+ // again. This runs in O(n) time.
+
+ // Always choose a random pivot so that an input array which is reverse
+ // sorted does not cause O(n^2) running time.
+ var pivotIndex = randomIntInRange(p, r);
+ var i = p - 1;
+
+ swap(ary, pivotIndex, r);
+ var pivot = ary[r];
+
+ // Immediately after `j` is incremented in this loop, the following hold
+ // true:
+ //
+ // * Every element in `ary[p .. i]` is less than or equal to the pivot.
+ //
+ // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
+ for (var j = p; j < r; j++) {
+ if (comparator(ary[j], pivot, false) <= 0) {
+ i += 1;
+ swap(ary, i, j);
+ }
+ }
+
+ swap(ary, i + 1, j);
+ var q = i + 1;
+
+ // (2) Recurse on each half.
+
+ doQuickSort(ary, comparator, p, q - 1);
+ doQuickSort(ary, comparator, q + 1, r);
+ }
+}
+
+ return doQuickSort;
+}
+
+function cloneSort(comparator) {
+ let template = SortTemplate.toString();
+ let templateFn = new Function(`return ${template}`)();
+ return templateFn(comparator);
+}
+
+/**
+ * Sort the given array in-place with the given comparator function.
+ *
+ * @param {Array} ary
+ * An array to sort.
+ * @param {function} comparator
+ * Function to use to compare two items.
+ */
+
+let sortCache = new WeakMap();
+exports.quickSort = function (ary, comparator, start = 0) {
+ let doQuickSort = sortCache.get(comparator);
+ if (doQuickSort === void 0) {
+ doQuickSort = cloneSort(comparator);
+ sortCache.set(comparator, doQuickSort);
+ }
+ doQuickSort(ary, comparator, start, ary.length - 1);
+};
diff --git a/frontend/node_modules/source-map-js/lib/source-map-consumer.d.ts b/frontend/node_modules/source-map-js/lib/source-map-consumer.d.ts
new file mode 100644
index 0000000..744bda7
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-map-consumer.d.ts
@@ -0,0 +1 @@
+export { SourceMapConsumer } from '..';
diff --git a/frontend/node_modules/source-map-js/lib/source-map-consumer.js b/frontend/node_modules/source-map-js/lib/source-map-consumer.js
new file mode 100644
index 0000000..ee66114
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-map-consumer.js
@@ -0,0 +1,1188 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var util = require('./util');
+var binarySearch = require('./binary-search');
+var ArraySet = require('./array-set').ArraySet;
+var base64VLQ = require('./base64-vlq');
+var quickSort = require('./quick-sort').quickSort;
+
+function SourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ return sourceMap.sections != null
+ ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
+ : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
+}
+
+SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
+ return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
+}
+
+/**
+ * The version of the source mapping spec that we are consuming.
+ */
+SourceMapConsumer.prototype._version = 3;
+
+// `__generatedMappings` and `__originalMappings` are arrays that hold the
+// parsed mapping coordinates from the source map's "mappings" attribute. They
+// are lazily instantiated, accessed via the `_generatedMappings` and
+// `_originalMappings` getters respectively, and we only parse the mappings
+// and create these arrays once queried for a source location. We jump through
+// these hoops because there can be many thousands of mappings, and parsing
+// them is expensive, so we only want to do it if we must.
+//
+// Each object in the arrays is of the form:
+//
+// {
+// generatedLine: The line number in the generated code,
+// generatedColumn: The column number in the generated code,
+// source: The path to the original source file that generated this
+// chunk of code,
+// originalLine: The line number in the original source that
+// corresponds to this chunk of generated code,
+// originalColumn: The column number in the original source that
+// corresponds to this chunk of generated code,
+// name: The name of the original symbol which generated this chunk of
+// code.
+// }
+//
+// All properties except for `generatedLine` and `generatedColumn` can be
+// `null`.
+//
+// `_generatedMappings` is ordered by the generated positions.
+//
+// `_originalMappings` is ordered by the original positions.
+
+SourceMapConsumer.prototype.__generatedMappings = null;
+Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ if (!this.__generatedMappings) {
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__generatedMappings;
+ }
+});
+
+SourceMapConsumer.prototype.__originalMappings = null;
+Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ if (!this.__originalMappings) {
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__originalMappings;
+ }
+});
+
+SourceMapConsumer.prototype._charIsMappingSeparator =
+ function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
+ var c = aStr.charAt(index);
+ return c === ";" || c === ",";
+ };
+
+/**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+SourceMapConsumer.prototype._parseMappings =
+ function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ throw new Error("Subclasses must implement _parseMappings");
+ };
+
+SourceMapConsumer.GENERATED_ORDER = 1;
+SourceMapConsumer.ORIGINAL_ORDER = 2;
+
+SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
+SourceMapConsumer.LEAST_UPPER_BOUND = 2;
+
+/**
+ * Iterate over each mapping between an original source/line/column and a
+ * generated line/column in this source map.
+ *
+ * @param Function aCallback
+ * The function that is called with each mapping.
+ * @param Object aContext
+ * Optional. If specified, this object will be the value of `this` every
+ * time that `aCallback` is called.
+ * @param aOrder
+ * Either `SourceMapConsumer.GENERATED_ORDER` or
+ * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
+ * iterate over the mappings sorted by the generated file's line/column
+ * order or the original's source/line/column order, respectively. Defaults to
+ * `SourceMapConsumer.GENERATED_ORDER`.
+ */
+SourceMapConsumer.prototype.eachMapping =
+ function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
+ var context = aContext || null;
+ var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
+
+ var mappings;
+ switch (order) {
+ case SourceMapConsumer.GENERATED_ORDER:
+ mappings = this._generatedMappings;
+ break;
+ case SourceMapConsumer.ORIGINAL_ORDER:
+ mappings = this._originalMappings;
+ break;
+ default:
+ throw new Error("Unknown order of iteration.");
+ }
+
+ var sourceRoot = this.sourceRoot;
+ var boundCallback = aCallback.bind(context);
+ var names = this._names;
+ var sources = this._sources;
+ var sourceMapURL = this._sourceMapURL;
+
+ for (var i = 0, n = mappings.length; i < n; i++) {
+ var mapping = mappings[i];
+ var source = mapping.source === null ? null : sources.at(mapping.source);
+ if(source !== null) {
+ source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
+ }
+ boundCallback({
+ source: source,
+ generatedLine: mapping.generatedLine,
+ generatedColumn: mapping.generatedColumn,
+ originalLine: mapping.originalLine,
+ originalColumn: mapping.originalColumn,
+ name: mapping.name === null ? null : names.at(mapping.name)
+ });
+ }
+ };
+
+/**
+ * Returns all generated line and column information for the original source,
+ * line, and column provided. If no column is provided, returns all mappings
+ * corresponding to a either the line we are searching for or the next
+ * closest line that has any mappings. Otherwise, returns all mappings
+ * corresponding to the given line and either the column we are searching for
+ * or the next closest column that has any offsets.
+ *
+ * The only argument is an object with the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number is 1-based.
+ * - column: Optional. the column number in the original source.
+ * The column number is 0-based.
+ *
+ * and an array of objects is returned, each with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+SourceMapConsumer.prototype.allGeneratedPositionsFor =
+ function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
+ var line = util.getArg(aArgs, 'line');
+
+ // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
+ // returns the index of the closest mapping less than the needle. By
+ // setting needle.originalColumn to 0, we thus find the last mapping for
+ // the given line, provided such a mapping exists.
+ var needle = {
+ source: util.getArg(aArgs, 'source'),
+ originalLine: line,
+ originalColumn: util.getArg(aArgs, 'column', 0)
+ };
+
+ needle.source = this._findSourceIndex(needle.source);
+ if (needle.source < 0) {
+ return [];
+ }
+
+ var mappings = [];
+
+ var index = this._findMapping(needle,
+ this._originalMappings,
+ "originalLine",
+ "originalColumn",
+ util.compareByOriginalPositions,
+ binarySearch.LEAST_UPPER_BOUND);
+ if (index >= 0) {
+ var mapping = this._originalMappings[index];
+
+ if (aArgs.column === undefined) {
+ var originalLine = mapping.originalLine;
+
+ // Iterate until either we run out of mappings, or we run into
+ // a mapping for a different line than the one we found. Since
+ // mappings are sorted, this is guaranteed to find all mappings for
+ // the line we found.
+ while (mapping && mapping.originalLine === originalLine) {
+ mappings.push({
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ });
+
+ mapping = this._originalMappings[++index];
+ }
+ } else {
+ var originalColumn = mapping.originalColumn;
+
+ // Iterate until either we run out of mappings, or we run into
+ // a mapping for a different line than the one we were searching for.
+ // Since mappings are sorted, this is guaranteed to find all mappings for
+ // the line we are searching for.
+ while (mapping &&
+ mapping.originalLine === line &&
+ mapping.originalColumn == originalColumn) {
+ mappings.push({
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ });
+
+ mapping = this._originalMappings[++index];
+ }
+ }
+ }
+
+ return mappings;
+ };
+
+exports.SourceMapConsumer = SourceMapConsumer;
+
+/**
+ * A BasicSourceMapConsumer instance represents a parsed source map which we can
+ * query for information about the original file positions by giving it a file
+ * position in the generated source.
+ *
+ * The first parameter is the raw source map (either as a JSON string, or
+ * already parsed to an object). According to the spec, source maps have the
+ * following attributes:
+ *
+ * - version: Which version of the source map spec this map is following.
+ * - sources: An array of URLs to the original source files.
+ * - names: An array of identifiers which can be referrenced by individual mappings.
+ * - sourceRoot: Optional. The URL root from which all sources are relative.
+ * - sourcesContent: Optional. An array of contents of the original source files.
+ * - mappings: A string of base64 VLQs which contain the actual mappings.
+ * - file: Optional. The generated file this source map is associated with.
+ *
+ * Here is an example source map, taken from the source map spec[0]:
+ *
+ * {
+ * version : 3,
+ * file: "out.js",
+ * sourceRoot : "",
+ * sources: ["foo.js", "bar.js"],
+ * names: ["src", "maps", "are", "fun"],
+ * mappings: "AA,AB;;ABCDE;"
+ * }
+ *
+ * The second parameter, if given, is a string whose value is the URL
+ * at which the source map was found. This URL is used to compute the
+ * sources array.
+ *
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
+ */
+function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ var version = util.getArg(sourceMap, 'version');
+ var sources = util.getArg(sourceMap, 'sources');
+ // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
+ // requires the array) to play nice here.
+ var names = util.getArg(sourceMap, 'names', []);
+ var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
+ var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
+ var mappings = util.getArg(sourceMap, 'mappings');
+ var file = util.getArg(sourceMap, 'file', null);
+
+ // Once again, Sass deviates from the spec and supplies the version as a
+ // string rather than a number, so we use loose equality checking here.
+ if (version != this._version) {
+ throw new Error('Unsupported version: ' + version);
+ }
+
+ if (sourceRoot) {
+ sourceRoot = util.normalize(sourceRoot);
+ }
+
+ sources = sources
+ .map(String)
+ // Some source maps produce relative source paths like "./foo.js" instead of
+ // "foo.js". Normalize these first so that future comparisons will succeed.
+ // See bugzil.la/1090768.
+ .map(util.normalize)
+ // Always ensure that absolute sources are internally stored relative to
+ // the source root, if the source root is absolute. Not doing this would
+ // be particularly problematic when the source root is a prefix of the
+ // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
+ .map(function (source) {
+ return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
+ ? util.relative(sourceRoot, source)
+ : source;
+ });
+
+ // Pass `true` below to allow duplicate names and sources. While source maps
+ // are intended to be compressed and deduplicated, the TypeScript compiler
+ // sometimes generates source maps with duplicates in them. See Github issue
+ // #72 and bugzil.la/889492.
+ this._names = ArraySet.fromArray(names.map(String), true);
+ this._sources = ArraySet.fromArray(sources, true);
+
+ this._absoluteSources = this._sources.toArray().map(function (s) {
+ return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
+ });
+
+ this.sourceRoot = sourceRoot;
+ this.sourcesContent = sourcesContent;
+ this._mappings = mappings;
+ this._sourceMapURL = aSourceMapURL;
+ this.file = file;
+}
+
+BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
+BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
+
+/**
+ * Utility function to find the index of a source. Returns -1 if not
+ * found.
+ */
+BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
+ var relativeSource = aSource;
+ if (this.sourceRoot != null) {
+ relativeSource = util.relative(this.sourceRoot, relativeSource);
+ }
+
+ if (this._sources.has(relativeSource)) {
+ return this._sources.indexOf(relativeSource);
+ }
+
+ // Maybe aSource is an absolute URL as returned by |sources|. In
+ // this case we can't simply undo the transform.
+ var i;
+ for (i = 0; i < this._absoluteSources.length; ++i) {
+ if (this._absoluteSources[i] == aSource) {
+ return i;
+ }
+ }
+
+ return -1;
+};
+
+/**
+ * Create a BasicSourceMapConsumer from a SourceMapGenerator.
+ *
+ * @param SourceMapGenerator aSourceMap
+ * The source map that will be consumed.
+ * @param String aSourceMapURL
+ * The URL at which the source map can be found (optional)
+ * @returns BasicSourceMapConsumer
+ */
+BasicSourceMapConsumer.fromSourceMap =
+ function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
+ var smc = Object.create(BasicSourceMapConsumer.prototype);
+
+ var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
+ var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
+ smc.sourceRoot = aSourceMap._sourceRoot;
+ smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
+ smc.sourceRoot);
+ smc.file = aSourceMap._file;
+ smc._sourceMapURL = aSourceMapURL;
+ smc._absoluteSources = smc._sources.toArray().map(function (s) {
+ return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
+ });
+
+ // Because we are modifying the entries (by converting string sources and
+ // names to indices into the sources and names ArraySets), we have to make
+ // a copy of the entry or else bad things happen. Shared mutable state
+ // strikes again! See github issue #191.
+
+ var generatedMappings = aSourceMap._mappings.toArray().slice();
+ var destGeneratedMappings = smc.__generatedMappings = [];
+ var destOriginalMappings = smc.__originalMappings = [];
+
+ for (var i = 0, length = generatedMappings.length; i < length; i++) {
+ var srcMapping = generatedMappings[i];
+ var destMapping = new Mapping;
+ destMapping.generatedLine = srcMapping.generatedLine;
+ destMapping.generatedColumn = srcMapping.generatedColumn;
+
+ if (srcMapping.source) {
+ destMapping.source = sources.indexOf(srcMapping.source);
+ destMapping.originalLine = srcMapping.originalLine;
+ destMapping.originalColumn = srcMapping.originalColumn;
+
+ if (srcMapping.name) {
+ destMapping.name = names.indexOf(srcMapping.name);
+ }
+
+ destOriginalMappings.push(destMapping);
+ }
+
+ destGeneratedMappings.push(destMapping);
+ }
+
+ quickSort(smc.__originalMappings, util.compareByOriginalPositions);
+
+ return smc;
+ };
+
+/**
+ * The version of the source mapping spec that we are consuming.
+ */
+BasicSourceMapConsumer.prototype._version = 3;
+
+/**
+ * The list of original sources.
+ */
+Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
+ get: function () {
+ return this._absoluteSources.slice();
+ }
+});
+
+/**
+ * Provide the JIT with a nice shape / hidden class.
+ */
+function Mapping() {
+ this.generatedLine = 0;
+ this.generatedColumn = 0;
+ this.source = null;
+ this.originalLine = null;
+ this.originalColumn = null;
+ this.name = null;
+}
+
+/**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+
+const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
+function sortGenerated(array, start) {
+ let l = array.length;
+ let n = array.length - start;
+ if (n <= 1) {
+ return;
+ } else if (n == 2) {
+ let a = array[start];
+ let b = array[start + 1];
+ if (compareGenerated(a, b) > 0) {
+ array[start] = b;
+ array[start + 1] = a;
+ }
+ } else if (n < 20) {
+ for (let i = start; i < l; i++) {
+ for (let j = i; j > start; j--) {
+ let a = array[j - 1];
+ let b = array[j];
+ if (compareGenerated(a, b) <= 0) {
+ break;
+ }
+ array[j - 1] = b;
+ array[j] = a;
+ }
+ }
+ } else {
+ quickSort(array, compareGenerated, start);
+ }
+}
+BasicSourceMapConsumer.prototype._parseMappings =
+ function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ var generatedLine = 1;
+ var previousGeneratedColumn = 0;
+ var previousOriginalLine = 0;
+ var previousOriginalColumn = 0;
+ var previousSource = 0;
+ var previousName = 0;
+ var length = aStr.length;
+ var index = 0;
+ var cachedSegments = {};
+ var temp = {};
+ var originalMappings = [];
+ var generatedMappings = [];
+ var mapping, str, segment, end, value;
+
+ let subarrayStart = 0;
+ while (index < length) {
+ if (aStr.charAt(index) === ';') {
+ generatedLine++;
+ index++;
+ previousGeneratedColumn = 0;
+
+ sortGenerated(generatedMappings, subarrayStart);
+ subarrayStart = generatedMappings.length;
+ }
+ else if (aStr.charAt(index) === ',') {
+ index++;
+ }
+ else {
+ mapping = new Mapping();
+ mapping.generatedLine = generatedLine;
+
+ for (end = index; end < length; end++) {
+ if (this._charIsMappingSeparator(aStr, end)) {
+ break;
+ }
+ }
+ str = aStr.slice(index, end);
+
+ segment = [];
+ while (index < end) {
+ base64VLQ.decode(aStr, index, temp);
+ value = temp.value;
+ index = temp.rest;
+ segment.push(value);
+ }
+
+ if (segment.length === 2) {
+ throw new Error('Found a source, but no line and column');
+ }
+
+ if (segment.length === 3) {
+ throw new Error('Found a source and line, but no column');
+ }
+
+ // Generated column.
+ mapping.generatedColumn = previousGeneratedColumn + segment[0];
+ previousGeneratedColumn = mapping.generatedColumn;
+
+ if (segment.length > 1) {
+ // Original source.
+ mapping.source = previousSource + segment[1];
+ previousSource += segment[1];
+
+ // Original line.
+ mapping.originalLine = previousOriginalLine + segment[2];
+ previousOriginalLine = mapping.originalLine;
+ // Lines are stored 0-based
+ mapping.originalLine += 1;
+
+ // Original column.
+ mapping.originalColumn = previousOriginalColumn + segment[3];
+ previousOriginalColumn = mapping.originalColumn;
+
+ if (segment.length > 4) {
+ // Original name.
+ mapping.name = previousName + segment[4];
+ previousName += segment[4];
+ }
+ }
+
+ generatedMappings.push(mapping);
+ if (typeof mapping.originalLine === 'number') {
+ let currentSource = mapping.source;
+ while (originalMappings.length <= currentSource) {
+ originalMappings.push(null);
+ }
+ if (originalMappings[currentSource] === null) {
+ originalMappings[currentSource] = [];
+ }
+ originalMappings[currentSource].push(mapping);
+ }
+ }
+ }
+
+ sortGenerated(generatedMappings, subarrayStart);
+ this.__generatedMappings = generatedMappings;
+
+ for (var i = 0; i < originalMappings.length; i++) {
+ if (originalMappings[i] != null) {
+ quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
+ }
+ }
+ this.__originalMappings = [].concat(...originalMappings);
+ };
+
+/**
+ * Find the mapping that best matches the hypothetical "needle" mapping that
+ * we are searching for in the given "haystack" of mappings.
+ */
+BasicSourceMapConsumer.prototype._findMapping =
+ function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
+ aColumnName, aComparator, aBias) {
+ // To return the position we are searching for, we must first find the
+ // mapping for the given position and then return the opposite position it
+ // points to. Because the mappings are sorted, we can use binary search to
+ // find the best mapping.
+
+ if (aNeedle[aLineName] <= 0) {
+ throw new TypeError('Line must be greater than or equal to 1, got '
+ + aNeedle[aLineName]);
+ }
+ if (aNeedle[aColumnName] < 0) {
+ throw new TypeError('Column must be greater than or equal to 0, got '
+ + aNeedle[aColumnName]);
+ }
+
+ return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
+ };
+
+/**
+ * Compute the last column for each generated mapping. The last column is
+ * inclusive.
+ */
+BasicSourceMapConsumer.prototype.computeColumnSpans =
+ function SourceMapConsumer_computeColumnSpans() {
+ for (var index = 0; index < this._generatedMappings.length; ++index) {
+ var mapping = this._generatedMappings[index];
+
+ // Mappings do not contain a field for the last generated columnt. We
+ // can come up with an optimistic estimate, however, by assuming that
+ // mappings are contiguous (i.e. given two consecutive mappings, the
+ // first mapping ends where the second one starts).
+ if (index + 1 < this._generatedMappings.length) {
+ var nextMapping = this._generatedMappings[index + 1];
+
+ if (mapping.generatedLine === nextMapping.generatedLine) {
+ mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
+ continue;
+ }
+ }
+
+ // The last mapping for each line spans the entire line.
+ mapping.lastGeneratedColumn = Infinity;
+ }
+ };
+
+/**
+ * Returns the original source, line, and column information for the generated
+ * source's line and column positions provided. The only argument is an object
+ * with the following properties:
+ *
+ * - line: The line number in the generated source. The line number
+ * is 1-based.
+ * - column: The column number in the generated source. The column
+ * number is 0-based.
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - source: The original source file, or null.
+ * - line: The line number in the original source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the original source, or null. The
+ * column number is 0-based.
+ * - name: The original identifier, or null.
+ */
+BasicSourceMapConsumer.prototype.originalPositionFor =
+ function SourceMapConsumer_originalPositionFor(aArgs) {
+ var needle = {
+ generatedLine: util.getArg(aArgs, 'line'),
+ generatedColumn: util.getArg(aArgs, 'column')
+ };
+
+ var index = this._findMapping(
+ needle,
+ this._generatedMappings,
+ "generatedLine",
+ "generatedColumn",
+ util.compareByGeneratedPositionsDeflated,
+ util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
+ );
+
+ if (index >= 0) {
+ var mapping = this._generatedMappings[index];
+
+ if (mapping.generatedLine === needle.generatedLine) {
+ var source = util.getArg(mapping, 'source', null);
+ if (source !== null) {
+ source = this._sources.at(source);
+ source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
+ }
+ var name = util.getArg(mapping, 'name', null);
+ if (name !== null) {
+ name = this._names.at(name);
+ }
+ return {
+ source: source,
+ line: util.getArg(mapping, 'originalLine', null),
+ column: util.getArg(mapping, 'originalColumn', null),
+ name: name
+ };
+ }
+ }
+
+ return {
+ source: null,
+ line: null,
+ column: null,
+ name: null
+ };
+ };
+
+/**
+ * Return true if we have the source content for every source in the source
+ * map, false otherwise.
+ */
+BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
+ function BasicSourceMapConsumer_hasContentsOfAllSources() {
+ if (!this.sourcesContent) {
+ return false;
+ }
+ return this.sourcesContent.length >= this._sources.size() &&
+ !this.sourcesContent.some(function (sc) { return sc == null; });
+ };
+
+/**
+ * Returns the original source content. The only argument is the url of the
+ * original source file. Returns null if no original source content is
+ * available.
+ */
+BasicSourceMapConsumer.prototype.sourceContentFor =
+ function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
+ if (!this.sourcesContent) {
+ return null;
+ }
+
+ var index = this._findSourceIndex(aSource);
+ if (index >= 0) {
+ return this.sourcesContent[index];
+ }
+
+ var relativeSource = aSource;
+ if (this.sourceRoot != null) {
+ relativeSource = util.relative(this.sourceRoot, relativeSource);
+ }
+
+ var url;
+ if (this.sourceRoot != null
+ && (url = util.urlParse(this.sourceRoot))) {
+ // XXX: file:// URIs and absolute paths lead to unexpected behavior for
+ // many users. We can help them out when they expect file:// URIs to
+ // behave like it would if they were running a local HTTP server. See
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
+ var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
+ if (url.scheme == "file"
+ && this._sources.has(fileUriAbsPath)) {
+ return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
+ }
+
+ if ((!url.path || url.path == "/")
+ && this._sources.has("/" + relativeSource)) {
+ return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
+ }
+ }
+
+ // This function is used recursively from
+ // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
+ // don't want to throw if we can't find the source - we just want to
+ // return null, so we provide a flag to exit gracefully.
+ if (nullOnMissing) {
+ return null;
+ }
+ else {
+ throw new Error('"' + relativeSource + '" is not in the SourceMap.');
+ }
+ };
+
+/**
+ * Returns the generated line and column information for the original source,
+ * line, and column positions provided. The only argument is an object with
+ * the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number
+ * is 1-based.
+ * - column: The column number in the original source. The column
+ * number is 0-based.
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+BasicSourceMapConsumer.prototype.generatedPositionFor =
+ function SourceMapConsumer_generatedPositionFor(aArgs) {
+ var source = util.getArg(aArgs, 'source');
+ source = this._findSourceIndex(source);
+ if (source < 0) {
+ return {
+ line: null,
+ column: null,
+ lastColumn: null
+ };
+ }
+
+ var needle = {
+ source: source,
+ originalLine: util.getArg(aArgs, 'line'),
+ originalColumn: util.getArg(aArgs, 'column')
+ };
+
+ var index = this._findMapping(
+ needle,
+ this._originalMappings,
+ "originalLine",
+ "originalColumn",
+ util.compareByOriginalPositions,
+ util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
+ );
+
+ if (index >= 0) {
+ var mapping = this._originalMappings[index];
+
+ if (mapping.source === needle.source) {
+ return {
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ };
+ }
+ }
+
+ return {
+ line: null,
+ column: null,
+ lastColumn: null
+ };
+ };
+
+exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
+
+/**
+ * An IndexedSourceMapConsumer instance represents a parsed source map which
+ * we can query for information. It differs from BasicSourceMapConsumer in
+ * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
+ * input.
+ *
+ * The first parameter is a raw source map (either as a JSON string, or already
+ * parsed to an object). According to the spec for indexed source maps, they
+ * have the following attributes:
+ *
+ * - version: Which version of the source map spec this map is following.
+ * - file: Optional. The generated file this source map is associated with.
+ * - sections: A list of section definitions.
+ *
+ * Each value under the "sections" field has two fields:
+ * - offset: The offset into the original specified at which this section
+ * begins to apply, defined as an object with a "line" and "column"
+ * field.
+ * - map: A source map definition. This source map could also be indexed,
+ * but doesn't have to be.
+ *
+ * Instead of the "map" field, it's also possible to have a "url" field
+ * specifying a URL to retrieve a source map from, but that's currently
+ * unsupported.
+ *
+ * Here's an example source map, taken from the source map spec[0], but
+ * modified to omit a section which uses the "url" field.
+ *
+ * {
+ * version : 3,
+ * file: "app.js",
+ * sections: [{
+ * offset: {line:100, column:10},
+ * map: {
+ * version : 3,
+ * file: "section.js",
+ * sources: ["foo.js", "bar.js"],
+ * names: ["src", "maps", "are", "fun"],
+ * mappings: "AAAA,E;;ABCDE;"
+ * }
+ * }],
+ * }
+ *
+ * The second parameter, if given, is a string whose value is the URL
+ * at which the source map was found. This URL is used to compute the
+ * sources array.
+ *
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
+ */
+function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ var version = util.getArg(sourceMap, 'version');
+ var sections = util.getArg(sourceMap, 'sections');
+
+ if (version != this._version) {
+ throw new Error('Unsupported version: ' + version);
+ }
+
+ this._sources = new ArraySet();
+ this._names = new ArraySet();
+
+ var lastOffset = {
+ line: -1,
+ column: 0
+ };
+ this._sections = sections.map(function (s) {
+ if (s.url) {
+ // The url field will require support for asynchronicity.
+ // See https://github.com/mozilla/source-map/issues/16
+ throw new Error('Support for url field in sections not implemented.');
+ }
+ var offset = util.getArg(s, 'offset');
+ var offsetLine = util.getArg(offset, 'line');
+ var offsetColumn = util.getArg(offset, 'column');
+
+ if (offsetLine < lastOffset.line ||
+ (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
+ throw new Error('Section offsets must be ordered and non-overlapping.');
+ }
+ lastOffset = offset;
+
+ return {
+ generatedOffset: {
+ // The offset fields are 0-based, but we use 1-based indices when
+ // encoding/decoding from VLQ.
+ generatedLine: offsetLine + 1,
+ generatedColumn: offsetColumn + 1
+ },
+ consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
+ }
+ });
+}
+
+IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
+IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
+
+/**
+ * The version of the source mapping spec that we are consuming.
+ */
+IndexedSourceMapConsumer.prototype._version = 3;
+
+/**
+ * The list of original sources.
+ */
+Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
+ get: function () {
+ var sources = [];
+ for (var i = 0; i < this._sections.length; i++) {
+ for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
+ sources.push(this._sections[i].consumer.sources[j]);
+ }
+ }
+ return sources;
+ }
+});
+
+/**
+ * Returns the original source, line, and column information for the generated
+ * source's line and column positions provided. The only argument is an object
+ * with the following properties:
+ *
+ * - line: The line number in the generated source. The line number
+ * is 1-based.
+ * - column: The column number in the generated source. The column
+ * number is 0-based.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - source: The original source file, or null.
+ * - line: The line number in the original source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the original source, or null. The
+ * column number is 0-based.
+ * - name: The original identifier, or null.
+ */
+IndexedSourceMapConsumer.prototype.originalPositionFor =
+ function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
+ var needle = {
+ generatedLine: util.getArg(aArgs, 'line'),
+ generatedColumn: util.getArg(aArgs, 'column')
+ };
+
+ // Find the section containing the generated position we're trying to map
+ // to an original position.
+ var sectionIndex = binarySearch.search(needle, this._sections,
+ function(needle, section) {
+ var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ return (needle.generatedColumn -
+ section.generatedOffset.generatedColumn);
+ });
+ var section = this._sections[sectionIndex];
+
+ if (!section) {
+ return {
+ source: null,
+ line: null,
+ column: null,
+ name: null
+ };
+ }
+
+ return section.consumer.originalPositionFor({
+ line: needle.generatedLine -
+ (section.generatedOffset.generatedLine - 1),
+ column: needle.generatedColumn -
+ (section.generatedOffset.generatedLine === needle.generatedLine
+ ? section.generatedOffset.generatedColumn - 1
+ : 0),
+ bias: aArgs.bias
+ });
+ };
+
+/**
+ * Return true if we have the source content for every source in the source
+ * map, false otherwise.
+ */
+IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
+ function IndexedSourceMapConsumer_hasContentsOfAllSources() {
+ return this._sections.every(function (s) {
+ return s.consumer.hasContentsOfAllSources();
+ });
+ };
+
+/**
+ * Returns the original source content. The only argument is the url of the
+ * original source file. Returns null if no original source content is
+ * available.
+ */
+IndexedSourceMapConsumer.prototype.sourceContentFor =
+ function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+
+ var content = section.consumer.sourceContentFor(aSource, true);
+ if (content || content === '') {
+ return content;
+ }
+ }
+ if (nullOnMissing) {
+ return null;
+ }
+ else {
+ throw new Error('"' + aSource + '" is not in the SourceMap.');
+ }
+ };
+
+/**
+ * Returns the generated line and column information for the original source,
+ * line, and column positions provided. The only argument is an object with
+ * the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number
+ * is 1-based.
+ * - column: The column number in the original source. The column
+ * number is 0-based.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+IndexedSourceMapConsumer.prototype.generatedPositionFor =
+ function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+
+ // Only consider this section if the requested source is in the list of
+ // sources of the consumer.
+ if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
+ continue;
+ }
+ var generatedPosition = section.consumer.generatedPositionFor(aArgs);
+ if (generatedPosition) {
+ var ret = {
+ line: generatedPosition.line +
+ (section.generatedOffset.generatedLine - 1),
+ column: generatedPosition.column +
+ (section.generatedOffset.generatedLine === generatedPosition.line
+ ? section.generatedOffset.generatedColumn - 1
+ : 0)
+ };
+ return ret;
+ }
+ }
+
+ return {
+ line: null,
+ column: null
+ };
+ };
+
+/**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+IndexedSourceMapConsumer.prototype._parseMappings =
+ function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ this.__generatedMappings = [];
+ this.__originalMappings = [];
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+ var sectionMappings = section.consumer._generatedMappings;
+ for (var j = 0; j < sectionMappings.length; j++) {
+ var mapping = sectionMappings[j];
+
+ var source = section.consumer._sources.at(mapping.source);
+ if(source !== null) {
+ source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
+ }
+ this._sources.add(source);
+ source = this._sources.indexOf(source);
+
+ var name = null;
+ if (mapping.name) {
+ name = section.consumer._names.at(mapping.name);
+ this._names.add(name);
+ name = this._names.indexOf(name);
+ }
+
+ // The mappings coming from the consumer for the section have
+ // generated positions relative to the start of the section, so we
+ // need to offset them to be relative to the start of the concatenated
+ // generated file.
+ var adjustedMapping = {
+ source: source,
+ generatedLine: mapping.generatedLine +
+ (section.generatedOffset.generatedLine - 1),
+ generatedColumn: mapping.generatedColumn +
+ (section.generatedOffset.generatedLine === mapping.generatedLine
+ ? section.generatedOffset.generatedColumn - 1
+ : 0),
+ originalLine: mapping.originalLine,
+ originalColumn: mapping.originalColumn,
+ name: name
+ };
+
+ this.__generatedMappings.push(adjustedMapping);
+ if (typeof adjustedMapping.originalLine === 'number') {
+ this.__originalMappings.push(adjustedMapping);
+ }
+ }
+ }
+
+ quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
+ quickSort(this.__originalMappings, util.compareByOriginalPositions);
+ };
+
+exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
diff --git a/frontend/node_modules/source-map-js/lib/source-map-generator.d.ts b/frontend/node_modules/source-map-js/lib/source-map-generator.d.ts
new file mode 100644
index 0000000..f59d70a
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-map-generator.d.ts
@@ -0,0 +1 @@
+export { SourceMapGenerator } from '..';
diff --git a/frontend/node_modules/source-map-js/lib/source-map-generator.js b/frontend/node_modules/source-map-js/lib/source-map-generator.js
new file mode 100644
index 0000000..bab04ff
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-map-generator.js
@@ -0,0 +1,444 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var base64VLQ = require('./base64-vlq');
+var util = require('./util');
+var ArraySet = require('./array-set').ArraySet;
+var MappingList = require('./mapping-list').MappingList;
+
+/**
+ * An instance of the SourceMapGenerator represents a source map which is
+ * being built incrementally. You may pass an object with the following
+ * properties:
+ *
+ * - file: The filename of the generated source.
+ * - sourceRoot: A root for all relative URLs in this source map.
+ */
+function SourceMapGenerator(aArgs) {
+ if (!aArgs) {
+ aArgs = {};
+ }
+ this._file = util.getArg(aArgs, 'file', null);
+ this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
+ this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
+ this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);
+ this._sources = new ArraySet();
+ this._names = new ArraySet();
+ this._mappings = new MappingList();
+ this._sourcesContents = null;
+}
+
+SourceMapGenerator.prototype._version = 3;
+
+/**
+ * Creates a new SourceMapGenerator based on a SourceMapConsumer
+ *
+ * @param aSourceMapConsumer The SourceMap.
+ */
+SourceMapGenerator.fromSourceMap =
+ function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
+ var sourceRoot = aSourceMapConsumer.sourceRoot;
+ var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
+ file: aSourceMapConsumer.file,
+ sourceRoot: sourceRoot
+ }));
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ var newMapping = {
+ generated: {
+ line: mapping.generatedLine,
+ column: mapping.generatedColumn
+ }
+ };
+
+ if (mapping.source != null) {
+ newMapping.source = mapping.source;
+ if (sourceRoot != null) {
+ newMapping.source = util.relative(sourceRoot, newMapping.source);
+ }
+
+ newMapping.original = {
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ };
+
+ if (mapping.name != null) {
+ newMapping.name = mapping.name;
+ }
+ }
+
+ generator.addMapping(newMapping);
+ });
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var sourceRelative = sourceFile;
+ if (sourceRoot !== null) {
+ sourceRelative = util.relative(sourceRoot, sourceFile);
+ }
+
+ if (!generator._sources.has(sourceRelative)) {
+ generator._sources.add(sourceRelative);
+ }
+
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ generator.setSourceContent(sourceFile, content);
+ }
+ });
+ return generator;
+ };
+
+/**
+ * Add a single mapping from original source line and column to the generated
+ * source's line and column for this source map being created. The mapping
+ * object should have the following properties:
+ *
+ * - generated: An object with the generated line and column positions.
+ * - original: An object with the original line and column positions.
+ * - source: The original source file (relative to the sourceRoot).
+ * - name: An optional original token name for this mapping.
+ */
+SourceMapGenerator.prototype.addMapping =
+ function SourceMapGenerator_addMapping(aArgs) {
+ var generated = util.getArg(aArgs, 'generated');
+ var original = util.getArg(aArgs, 'original', null);
+ var source = util.getArg(aArgs, 'source', null);
+ var name = util.getArg(aArgs, 'name', null);
+
+ if (!this._skipValidation) {
+ if (this._validateMapping(generated, original, source, name) === false) {
+ return;
+ }
+ }
+
+ if (source != null) {
+ source = String(source);
+ if (!this._sources.has(source)) {
+ this._sources.add(source);
+ }
+ }
+
+ if (name != null) {
+ name = String(name);
+ if (!this._names.has(name)) {
+ this._names.add(name);
+ }
+ }
+
+ this._mappings.add({
+ generatedLine: generated.line,
+ generatedColumn: generated.column,
+ originalLine: original != null && original.line,
+ originalColumn: original != null && original.column,
+ source: source,
+ name: name
+ });
+ };
+
+/**
+ * Set the source content for a source file.
+ */
+SourceMapGenerator.prototype.setSourceContent =
+ function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
+ var source = aSourceFile;
+ if (this._sourceRoot != null) {
+ source = util.relative(this._sourceRoot, source);
+ }
+
+ if (aSourceContent != null) {
+ // Add the source content to the _sourcesContents map.
+ // Create a new _sourcesContents map if the property is null.
+ if (!this._sourcesContents) {
+ this._sourcesContents = Object.create(null);
+ }
+ this._sourcesContents[util.toSetString(source)] = aSourceContent;
+ } else if (this._sourcesContents) {
+ // Remove the source file from the _sourcesContents map.
+ // If the _sourcesContents map is empty, set the property to null.
+ delete this._sourcesContents[util.toSetString(source)];
+ if (Object.keys(this._sourcesContents).length === 0) {
+ this._sourcesContents = null;
+ }
+ }
+ };
+
+/**
+ * Applies the mappings of a sub-source-map for a specific source file to the
+ * source map being generated. Each mapping to the supplied source file is
+ * rewritten using the supplied source map. Note: The resolution for the
+ * resulting mappings is the minimium of this map and the supplied map.
+ *
+ * @param aSourceMapConsumer The source map to be applied.
+ * @param aSourceFile Optional. The filename of the source file.
+ * If omitted, SourceMapConsumer's file property will be used.
+ * @param aSourceMapPath Optional. The dirname of the path to the source map
+ * to be applied. If relative, it is relative to the SourceMapConsumer.
+ * This parameter is needed when the two source maps aren't in the same
+ * directory, and the source map to be applied contains relative source
+ * paths. If so, those relative source paths need to be rewritten
+ * relative to the SourceMapGenerator.
+ */
+SourceMapGenerator.prototype.applySourceMap =
+ function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
+ var sourceFile = aSourceFile;
+ // If aSourceFile is omitted, we will use the file property of the SourceMap
+ if (aSourceFile == null) {
+ if (aSourceMapConsumer.file == null) {
+ throw new Error(
+ 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
+ 'or the source map\'s "file" property. Both were omitted.'
+ );
+ }
+ sourceFile = aSourceMapConsumer.file;
+ }
+ var sourceRoot = this._sourceRoot;
+ // Make "sourceFile" relative if an absolute Url is passed.
+ if (sourceRoot != null) {
+ sourceFile = util.relative(sourceRoot, sourceFile);
+ }
+ // Applying the SourceMap can add and remove items from the sources and
+ // the names array.
+ var newSources = new ArraySet();
+ var newNames = new ArraySet();
+
+ // Find mappings for the "sourceFile"
+ this._mappings.unsortedForEach(function (mapping) {
+ if (mapping.source === sourceFile && mapping.originalLine != null) {
+ // Check if it can be mapped by the source map, then update the mapping.
+ var original = aSourceMapConsumer.originalPositionFor({
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ });
+ if (original.source != null) {
+ // Copy mapping
+ mapping.source = original.source;
+ if (aSourceMapPath != null) {
+ mapping.source = util.join(aSourceMapPath, mapping.source)
+ }
+ if (sourceRoot != null) {
+ mapping.source = util.relative(sourceRoot, mapping.source);
+ }
+ mapping.originalLine = original.line;
+ mapping.originalColumn = original.column;
+ if (original.name != null) {
+ mapping.name = original.name;
+ }
+ }
+ }
+
+ var source = mapping.source;
+ if (source != null && !newSources.has(source)) {
+ newSources.add(source);
+ }
+
+ var name = mapping.name;
+ if (name != null && !newNames.has(name)) {
+ newNames.add(name);
+ }
+
+ }, this);
+ this._sources = newSources;
+ this._names = newNames;
+
+ // Copy sourcesContents of applied map.
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ if (aSourceMapPath != null) {
+ sourceFile = util.join(aSourceMapPath, sourceFile);
+ }
+ if (sourceRoot != null) {
+ sourceFile = util.relative(sourceRoot, sourceFile);
+ }
+ this.setSourceContent(sourceFile, content);
+ }
+ }, this);
+ };
+
+/**
+ * A mapping can have one of the three levels of data:
+ *
+ * 1. Just the generated position.
+ * 2. The Generated position, original position, and original source.
+ * 3. Generated and original position, original source, as well as a name
+ * token.
+ *
+ * To maintain consistency, we validate that any new mapping being added falls
+ * in to one of these categories.
+ */
+SourceMapGenerator.prototype._validateMapping =
+ function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
+ aName) {
+ // When aOriginal is truthy but has empty values for .line and .column,
+ // it is most likely a programmer error. In this case we throw a very
+ // specific error message to try to guide them the right way.
+ // For example: https://github.com/Polymer/polymer-bundler/pull/519
+ if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
+ var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +
+ 'the original mapping entirely and only map the generated position. If so, pass ' +
+ 'null for the original mapping instead of an object with empty or null values.'
+
+ if (this._ignoreInvalidMapping) {
+ if (typeof console !== 'undefined' && console.warn) {
+ console.warn(message);
+ }
+ return false;
+ } else {
+ throw new Error(message);
+ }
+ }
+
+ if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && !aOriginal && !aSource && !aName) {
+ // Case 1.
+ return;
+ }
+ else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aOriginal && 'line' in aOriginal && 'column' in aOriginal
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && aOriginal.line > 0 && aOriginal.column >= 0
+ && aSource) {
+ // Cases 2 and 3.
+ return;
+ }
+ else {
+ var message = 'Invalid mapping: ' + JSON.stringify({
+ generated: aGenerated,
+ source: aSource,
+ original: aOriginal,
+ name: aName
+ });
+
+ if (this._ignoreInvalidMapping) {
+ if (typeof console !== 'undefined' && console.warn) {
+ console.warn(message);
+ }
+ return false;
+ } else {
+ throw new Error(message)
+ }
+ }
+ };
+
+/**
+ * Serialize the accumulated mappings in to the stream of base 64 VLQs
+ * specified by the source map format.
+ */
+SourceMapGenerator.prototype._serializeMappings =
+ function SourceMapGenerator_serializeMappings() {
+ var previousGeneratedColumn = 0;
+ var previousGeneratedLine = 1;
+ var previousOriginalColumn = 0;
+ var previousOriginalLine = 0;
+ var previousName = 0;
+ var previousSource = 0;
+ var result = '';
+ var next;
+ var mapping;
+ var nameIdx;
+ var sourceIdx;
+
+ var mappings = this._mappings.toArray();
+ for (var i = 0, len = mappings.length; i < len; i++) {
+ mapping = mappings[i];
+ next = ''
+
+ if (mapping.generatedLine !== previousGeneratedLine) {
+ previousGeneratedColumn = 0;
+ while (mapping.generatedLine !== previousGeneratedLine) {
+ next += ';';
+ previousGeneratedLine++;
+ }
+ }
+ else {
+ if (i > 0) {
+ if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
+ continue;
+ }
+ next += ',';
+ }
+ }
+
+ next += base64VLQ.encode(mapping.generatedColumn
+ - previousGeneratedColumn);
+ previousGeneratedColumn = mapping.generatedColumn;
+
+ if (mapping.source != null) {
+ sourceIdx = this._sources.indexOf(mapping.source);
+ next += base64VLQ.encode(sourceIdx - previousSource);
+ previousSource = sourceIdx;
+
+ // lines are stored 0-based in SourceMap spec version 3
+ next += base64VLQ.encode(mapping.originalLine - 1
+ - previousOriginalLine);
+ previousOriginalLine = mapping.originalLine - 1;
+
+ next += base64VLQ.encode(mapping.originalColumn
+ - previousOriginalColumn);
+ previousOriginalColumn = mapping.originalColumn;
+
+ if (mapping.name != null) {
+ nameIdx = this._names.indexOf(mapping.name);
+ next += base64VLQ.encode(nameIdx - previousName);
+ previousName = nameIdx;
+ }
+ }
+
+ result += next;
+ }
+
+ return result;
+ };
+
+SourceMapGenerator.prototype._generateSourcesContent =
+ function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
+ return aSources.map(function (source) {
+ if (!this._sourcesContents) {
+ return null;
+ }
+ if (aSourceRoot != null) {
+ source = util.relative(aSourceRoot, source);
+ }
+ var key = util.toSetString(source);
+ return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
+ ? this._sourcesContents[key]
+ : null;
+ }, this);
+ };
+
+/**
+ * Externalize the source map.
+ */
+SourceMapGenerator.prototype.toJSON =
+ function SourceMapGenerator_toJSON() {
+ var map = {
+ version: this._version,
+ sources: this._sources.toArray(),
+ names: this._names.toArray(),
+ mappings: this._serializeMappings()
+ };
+ if (this._file != null) {
+ map.file = this._file;
+ }
+ if (this._sourceRoot != null) {
+ map.sourceRoot = this._sourceRoot;
+ }
+ if (this._sourcesContents) {
+ map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
+ }
+
+ return map;
+ };
+
+/**
+ * Render the source map being generated to a string.
+ */
+SourceMapGenerator.prototype.toString =
+ function SourceMapGenerator_toString() {
+ return JSON.stringify(this.toJSON());
+ };
+
+exports.SourceMapGenerator = SourceMapGenerator;
diff --git a/frontend/node_modules/source-map-js/lib/source-node.d.ts b/frontend/node_modules/source-map-js/lib/source-node.d.ts
new file mode 100644
index 0000000..4df6a1a
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-node.d.ts
@@ -0,0 +1 @@
+export { SourceNode } from '..';
diff --git a/frontend/node_modules/source-map-js/lib/source-node.js b/frontend/node_modules/source-map-js/lib/source-node.js
new file mode 100644
index 0000000..8bcdbe3
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/source-node.js
@@ -0,0 +1,413 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
+var util = require('./util');
+
+// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
+// operating systems these days (capturing the result).
+var REGEX_NEWLINE = /(\r?\n)/;
+
+// Newline character code for charCodeAt() comparisons
+var NEWLINE_CODE = 10;
+
+// Private symbol for identifying `SourceNode`s when multiple versions of
+// the source-map library are loaded. This MUST NOT CHANGE across
+// versions!
+var isSourceNode = "$$$isSourceNode$$$";
+
+/**
+ * SourceNodes provide a way to abstract over interpolating/concatenating
+ * snippets of generated JavaScript source code while maintaining the line and
+ * column information associated with the original source code.
+ *
+ * @param aLine The original line number.
+ * @param aColumn The original column number.
+ * @param aSource The original source's filename.
+ * @param aChunks Optional. An array of strings which are snippets of
+ * generated JS, or other SourceNodes.
+ * @param aName The original identifier.
+ */
+function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
+ this.children = [];
+ this.sourceContents = {};
+ this.line = aLine == null ? null : aLine;
+ this.column = aColumn == null ? null : aColumn;
+ this.source = aSource == null ? null : aSource;
+ this.name = aName == null ? null : aName;
+ this[isSourceNode] = true;
+ if (aChunks != null) this.add(aChunks);
+}
+
+/**
+ * Creates a SourceNode from generated code and a SourceMapConsumer.
+ *
+ * @param aGeneratedCode The generated code
+ * @param aSourceMapConsumer The SourceMap for the generated code
+ * @param aRelativePath Optional. The path that relative sources in the
+ * SourceMapConsumer should be relative to.
+ */
+SourceNode.fromStringWithSourceMap =
+ function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
+ // The SourceNode we want to fill with the generated code
+ // and the SourceMap
+ var node = new SourceNode();
+
+ // All even indices of this array are one line of the generated code,
+ // while all odd indices are the newlines between two adjacent lines
+ // (since `REGEX_NEWLINE` captures its match).
+ // Processed fragments are accessed by calling `shiftNextLine`.
+ var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
+ var remainingLinesIndex = 0;
+ var shiftNextLine = function() {
+ var lineContents = getNextLine();
+ // The last line of a file might not have a newline.
+ var newLine = getNextLine() || "";
+ return lineContents + newLine;
+
+ function getNextLine() {
+ return remainingLinesIndex < remainingLines.length ?
+ remainingLines[remainingLinesIndex++] : undefined;
+ }
+ };
+
+ // We need to remember the position of "remainingLines"
+ var lastGeneratedLine = 1, lastGeneratedColumn = 0;
+
+ // The generate SourceNodes we need a code range.
+ // To extract it current and last mapping is used.
+ // Here we store the last mapping.
+ var lastMapping = null;
+
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ if (lastMapping !== null) {
+ // We add the code from "lastMapping" to "mapping":
+ // First check if there is a new line in between.
+ if (lastGeneratedLine < mapping.generatedLine) {
+ // Associate first line with "lastMapping"
+ addMappingWithCode(lastMapping, shiftNextLine());
+ lastGeneratedLine++;
+ lastGeneratedColumn = 0;
+ // The remaining code is added without mapping
+ } else {
+ // There is no new line in between.
+ // Associate the code between "lastGeneratedColumn" and
+ // "mapping.generatedColumn" with "lastMapping"
+ var nextLine = remainingLines[remainingLinesIndex] || '';
+ var code = nextLine.substr(0, mapping.generatedColumn -
+ lastGeneratedColumn);
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
+ lastGeneratedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ addMappingWithCode(lastMapping, code);
+ // No more remaining code, continue
+ lastMapping = mapping;
+ return;
+ }
+ }
+ // We add the generated code until the first mapping
+ // to the SourceNode without any mapping.
+ // Each line is added as separate string.
+ while (lastGeneratedLine < mapping.generatedLine) {
+ node.add(shiftNextLine());
+ lastGeneratedLine++;
+ }
+ if (lastGeneratedColumn < mapping.generatedColumn) {
+ var nextLine = remainingLines[remainingLinesIndex] || '';
+ node.add(nextLine.substr(0, mapping.generatedColumn));
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ }
+ lastMapping = mapping;
+ }, this);
+ // We have processed all mappings.
+ if (remainingLinesIndex < remainingLines.length) {
+ if (lastMapping) {
+ // Associate the remaining code in the current line with "lastMapping"
+ addMappingWithCode(lastMapping, shiftNextLine());
+ }
+ // and add the remaining lines without any mapping
+ node.add(remainingLines.splice(remainingLinesIndex).join(""));
+ }
+
+ // Copy sourcesContent into SourceNode
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ if (aRelativePath != null) {
+ sourceFile = util.join(aRelativePath, sourceFile);
+ }
+ node.setSourceContent(sourceFile, content);
+ }
+ });
+
+ return node;
+
+ function addMappingWithCode(mapping, code) {
+ if (mapping === null || mapping.source === undefined) {
+ node.add(code);
+ } else {
+ var source = aRelativePath
+ ? util.join(aRelativePath, mapping.source)
+ : mapping.source;
+ node.add(new SourceNode(mapping.originalLine,
+ mapping.originalColumn,
+ source,
+ code,
+ mapping.name));
+ }
+ }
+ };
+
+/**
+ * Add a chunk of generated JS to this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+SourceNode.prototype.add = function SourceNode_add(aChunk) {
+ if (Array.isArray(aChunk)) {
+ aChunk.forEach(function (chunk) {
+ this.add(chunk);
+ }, this);
+ }
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") {
+ if (aChunk) {
+ this.children.push(aChunk);
+ }
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+};
+
+/**
+ * Add a chunk of generated JS to the beginning of this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
+ if (Array.isArray(aChunk)) {
+ for (var i = aChunk.length-1; i >= 0; i--) {
+ this.prepend(aChunk[i]);
+ }
+ }
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") {
+ this.children.unshift(aChunk);
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+};
+
+/**
+ * Walk over the tree of JS snippets in this node and its children. The
+ * walking function is called once for each snippet of JS and is passed that
+ * snippet and the its original associated source's line/column location.
+ *
+ * @param aFn The traversal function.
+ */
+SourceNode.prototype.walk = function SourceNode_walk(aFn) {
+ var chunk;
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ chunk = this.children[i];
+ if (chunk[isSourceNode]) {
+ chunk.walk(aFn);
+ }
+ else {
+ if (chunk !== '') {
+ aFn(chunk, { source: this.source,
+ line: this.line,
+ column: this.column,
+ name: this.name });
+ }
+ }
+ }
+};
+
+/**
+ * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
+ * each of `this.children`.
+ *
+ * @param aSep The separator.
+ */
+SourceNode.prototype.join = function SourceNode_join(aSep) {
+ var newChildren;
+ var i;
+ var len = this.children.length;
+ if (len > 0) {
+ newChildren = [];
+ for (i = 0; i < len-1; i++) {
+ newChildren.push(this.children[i]);
+ newChildren.push(aSep);
+ }
+ newChildren.push(this.children[i]);
+ this.children = newChildren;
+ }
+ return this;
+};
+
+/**
+ * Call String.prototype.replace on the very right-most source snippet. Useful
+ * for trimming whitespace from the end of a source node, etc.
+ *
+ * @param aPattern The pattern to replace.
+ * @param aReplacement The thing to replace the pattern with.
+ */
+SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
+ var lastChild = this.children[this.children.length - 1];
+ if (lastChild[isSourceNode]) {
+ lastChild.replaceRight(aPattern, aReplacement);
+ }
+ else if (typeof lastChild === 'string') {
+ this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
+ }
+ else {
+ this.children.push(''.replace(aPattern, aReplacement));
+ }
+ return this;
+};
+
+/**
+ * Set the source content for a source file. This will be added to the SourceMapGenerator
+ * in the sourcesContent field.
+ *
+ * @param aSourceFile The filename of the source file
+ * @param aSourceContent The content of the source file
+ */
+SourceNode.prototype.setSourceContent =
+ function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
+ this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
+ };
+
+/**
+ * Walk over the tree of SourceNodes. The walking function is called for each
+ * source file content and is passed the filename and source content.
+ *
+ * @param aFn The traversal function.
+ */
+SourceNode.prototype.walkSourceContents =
+ function SourceNode_walkSourceContents(aFn) {
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ if (this.children[i][isSourceNode]) {
+ this.children[i].walkSourceContents(aFn);
+ }
+ }
+
+ var sources = Object.keys(this.sourceContents);
+ for (var i = 0, len = sources.length; i < len; i++) {
+ aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
+ }
+ };
+
+/**
+ * Return the string representation of this source node. Walks over the tree
+ * and concatenates all the various snippets together to one string.
+ */
+SourceNode.prototype.toString = function SourceNode_toString() {
+ var str = "";
+ this.walk(function (chunk) {
+ str += chunk;
+ });
+ return str;
+};
+
+/**
+ * Returns the string representation of this source node along with a source
+ * map.
+ */
+SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
+ var generated = {
+ code: "",
+ line: 1,
+ column: 0
+ };
+ var map = new SourceMapGenerator(aArgs);
+ var sourceMappingActive = false;
+ var lastOriginalSource = null;
+ var lastOriginalLine = null;
+ var lastOriginalColumn = null;
+ var lastOriginalName = null;
+ this.walk(function (chunk, original) {
+ generated.code += chunk;
+ if (original.source !== null
+ && original.line !== null
+ && original.column !== null) {
+ if(lastOriginalSource !== original.source
+ || lastOriginalLine !== original.line
+ || lastOriginalColumn !== original.column
+ || lastOriginalName !== original.name) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ lastOriginalSource = original.source;
+ lastOriginalLine = original.line;
+ lastOriginalColumn = original.column;
+ lastOriginalName = original.name;
+ sourceMappingActive = true;
+ } else if (sourceMappingActive) {
+ map.addMapping({
+ generated: {
+ line: generated.line,
+ column: generated.column
+ }
+ });
+ lastOriginalSource = null;
+ sourceMappingActive = false;
+ }
+ for (var idx = 0, length = chunk.length; idx < length; idx++) {
+ if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
+ generated.line++;
+ generated.column = 0;
+ // Mappings end at eol
+ if (idx + 1 === length) {
+ lastOriginalSource = null;
+ sourceMappingActive = false;
+ } else if (sourceMappingActive) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ } else {
+ generated.column++;
+ }
+ }
+ });
+ this.walkSourceContents(function (sourceFile, sourceContent) {
+ map.setSourceContent(sourceFile, sourceContent);
+ });
+
+ return { code: generated.code, map: map };
+};
+
+exports.SourceNode = SourceNode;
diff --git a/frontend/node_modules/source-map-js/lib/util.js b/frontend/node_modules/source-map-js/lib/util.js
new file mode 100644
index 0000000..430e2d0
--- /dev/null
+++ b/frontend/node_modules/source-map-js/lib/util.js
@@ -0,0 +1,594 @@
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+/**
+ * This is a helper function for getting values from parameter/options
+ * objects.
+ *
+ * @param args The object we are extracting values from
+ * @param name The name of the property we are getting.
+ * @param defaultValue An optional value to return if the property is missing
+ * from the object. If this is not specified and the property is missing, an
+ * error will be thrown.
+ */
+function getArg(aArgs, aName, aDefaultValue) {
+ if (aName in aArgs) {
+ return aArgs[aName];
+ } else if (arguments.length === 3) {
+ return aDefaultValue;
+ } else {
+ throw new Error('"' + aName + '" is a required argument.');
+ }
+}
+exports.getArg = getArg;
+
+var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
+var dataUrlRegexp = /^data:.+\,.+$/;
+
+function urlParse(aUrl) {
+ var match = aUrl.match(urlRegexp);
+ if (!match) {
+ return null;
+ }
+ return {
+ scheme: match[1],
+ auth: match[2],
+ host: match[3],
+ port: match[4],
+ path: match[5]
+ };
+}
+exports.urlParse = urlParse;
+
+function urlGenerate(aParsedUrl) {
+ var url = '';
+ if (aParsedUrl.scheme) {
+ url += aParsedUrl.scheme + ':';
+ }
+ url += '//';
+ if (aParsedUrl.auth) {
+ url += aParsedUrl.auth + '@';
+ }
+ if (aParsedUrl.host) {
+ url += aParsedUrl.host;
+ }
+ if (aParsedUrl.port) {
+ url += ":" + aParsedUrl.port
+ }
+ if (aParsedUrl.path) {
+ url += aParsedUrl.path;
+ }
+ return url;
+}
+exports.urlGenerate = urlGenerate;
+
+var MAX_CACHED_INPUTS = 32;
+
+/**
+ * Takes some function `f(input) -> result` and returns a memoized version of
+ * `f`.
+ *
+ * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
+ * memoization is a dumb-simple, linear least-recently-used cache.
+ */
+function lruMemoize(f) {
+ var cache = [];
+
+ return function(input) {
+ for (var i = 0; i < cache.length; i++) {
+ if (cache[i].input === input) {
+ var temp = cache[0];
+ cache[0] = cache[i];
+ cache[i] = temp;
+ return cache[0].result;
+ }
+ }
+
+ var result = f(input);
+
+ cache.unshift({
+ input,
+ result,
+ });
+
+ if (cache.length > MAX_CACHED_INPUTS) {
+ cache.pop();
+ }
+
+ return result;
+ };
+}
+
+/**
+ * Normalizes a path, or the path portion of a URL:
+ *
+ * - Replaces consecutive slashes with one slash.
+ * - Removes unnecessary '.' parts.
+ * - Removes unnecessary '<dir>/..' parts.
+ *
+ * Based on code in the Node.js 'path' core module.
+ *
+ * @param aPath The path or url to normalize.
+ */
+var normalize = lruMemoize(function normalize(aPath) {
+ var path = aPath;
+ var url = urlParse(aPath);
+ if (url) {
+ if (!url.path) {
+ return aPath;
+ }
+ path = url.path;
+ }
+ var isAbsolute = exports.isAbsolute(path);
+ // Split the path into parts between `/` characters. This is much faster than
+ // using `.split(/\/+/g)`.
+ var parts = [];
+ var start = 0;
+ var i = 0;
+ while (true) {
+ start = i;
+ i = path.indexOf("/", start);
+ if (i === -1) {
+ parts.push(path.slice(start));
+ break;
+ } else {
+ parts.push(path.slice(start, i));
+ while (i < path.length && path[i] === "/") {
+ i++;
+ }
+ }
+ }
+
+ for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
+ part = parts[i];
+ if (part === '.') {
+ parts.splice(i, 1);
+ } else if (part === '..') {
+ up++;
+ } else if (up > 0) {
+ if (part === '') {
+ // The first part is blank if the path is absolute. Trying to go
+ // above the root is a no-op. Therefore we can remove all '..' parts
+ // directly after the root.
+ parts.splice(i + 1, up);
+ up = 0;
+ } else {
+ parts.splice(i, 2);
+ up--;
+ }
+ }
+ }
+ path = parts.join('/');
+
+ if (path === '') {
+ path = isAbsolute ? '/' : '.';
+ }
+
+ if (url) {
+ url.path = path;
+ return urlGenerate(url);
+ }
+ return path;
+});
+exports.normalize = normalize;
+
+/**
+ * Joins two paths/URLs.
+ *
+ * @param aRoot The root path or URL.
+ * @param aPath The path or URL to be joined with the root.
+ *
+ * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
+ * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
+ * first.
+ * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
+ * is updated with the result and aRoot is returned. Otherwise the result
+ * is returned.
+ * - If aPath is absolute, the result is aPath.
+ * - Otherwise the two paths are joined with a slash.
+ * - Joining for example 'http://' and 'www.example.com' is also supported.
+ */
+function join(aRoot, aPath) {
+ if (aRoot === "") {
+ aRoot = ".";
+ }
+ if (aPath === "") {
+ aPath = ".";
+ }
+ var aPathUrl = urlParse(aPath);
+ var aRootUrl = urlParse(aRoot);
+ if (aRootUrl) {
+ aRoot = aRootUrl.path || '/';
+ }
+
+ // `join(foo, '//www.example.org')`
+ if (aPathUrl && !aPathUrl.scheme) {
+ if (aRootUrl) {
+ aPathUrl.scheme = aRootUrl.scheme;
+ }
+ return urlGenerate(aPathUrl);
+ }
+
+ if (aPathUrl || aPath.match(dataUrlRegexp)) {
+ return aPath;
+ }
+
+ // `join('http://', 'www.example.com')`
+ if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
+ aRootUrl.host = aPath;
+ return urlGenerate(aRootUrl);
+ }
+
+ var joined = aPath.charAt(0) === '/'
+ ? aPath
+ : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
+
+ if (aRootUrl) {
+ aRootUrl.path = joined;
+ return urlGenerate(aRootUrl);
+ }
+ return joined;
+}
+exports.join = join;
+
+exports.isAbsolute = function (aPath) {
+ return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
+};
+
+/**
+ * Make a path relative to a URL or another path.
+ *
+ * @param aRoot The root path or URL.
+ * @param aPath The path or URL to be made relative to aRoot.
+ */
+function relative(aRoot, aPath) {
+ if (aRoot === "") {
+ aRoot = ".";
+ }
+
+ aRoot = aRoot.replace(/\/$/, '');
+
+ // It is possible for the path to be above the root. In this case, simply
+ // checking whether the root is a prefix of the path won't work. Instead, we
+ // need to remove components from the root one by one, until either we find
+ // a prefix that fits, or we run out of components to remove.
+ var level = 0;
+ while (aPath.indexOf(aRoot + '/') !== 0) {
+ var index = aRoot.lastIndexOf("/");
+ if (index < 0) {
+ return aPath;
+ }
+
+ // If the only part of the root that is left is the scheme (i.e. http://,
+ // file:///, etc.), one or more slashes (/), or simply nothing at all, we
+ // have exhausted all components, so the path is not relative to the root.
+ aRoot = aRoot.slice(0, index);
+ if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
+ return aPath;
+ }
+
+ ++level;
+ }
+
+ // Make sure we add a "../" for each component we removed from the root.
+ return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
+}
+exports.relative = relative;
+
+var supportsNullProto = (function () {
+ var obj = Object.create(null);
+ return !('__proto__' in obj);
+}());
+
+function identity (s) {
+ return s;
+}
+
+/**
+ * Because behavior goes wacky when you set `__proto__` on objects, we
+ * have to prefix all the strings in our set with an arbitrary character.
+ *
+ * See https://github.com/mozilla/source-map/pull/31 and
+ * https://github.com/mozilla/source-map/issues/30
+ *
+ * @param String aStr
+ */
+function toSetString(aStr) {
+ if (isProtoString(aStr)) {
+ return '$' + aStr;
+ }
+
+ return aStr;
+}
+exports.toSetString = supportsNullProto ? identity : toSetString;
+
+function fromSetString(aStr) {
+ if (isProtoString(aStr)) {
+ return aStr.slice(1);
+ }
+
+ return aStr;
+}
+exports.fromSetString = supportsNullProto ? identity : fromSetString;
+
+function isProtoString(s) {
+ if (!s) {
+ return false;
+ }
+
+ var length = s.length;
+
+ if (length < 9 /* "__proto__".length */) {
+ return false;
+ }
+
+ if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 2) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
+ s.charCodeAt(length - 4) !== 116 /* 't' */ ||
+ s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
+ s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
+ s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
+ s.charCodeAt(length - 8) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 9) !== 95 /* '_' */) {
+ return false;
+ }
+
+ for (var i = length - 10; i >= 0; i--) {
+ if (s.charCodeAt(i) !== 36 /* '$' */) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Comparator between two mappings where the original positions are compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same original source/line/column, but different generated
+ * line and column the same. Useful when searching for a mapping with a
+ * stubbed out mapping.
+ */
+function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
+ var cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0 || onlyCompareOriginal) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+}
+exports.compareByOriginalPositions = compareByOriginalPositions;
+
+function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
+ var cmp
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0 || onlyCompareOriginal) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+}
+exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
+
+/**
+ * Comparator between two mappings with deflated source and name indices where
+ * the generated positions are compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same generated line and column, but different
+ * source/name/original line and column the same. Useful when searching for a
+ * mapping with a stubbed out mapping.
+ */
+function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0 || onlyCompareGenerated) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+}
+exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
+
+function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
+ var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0 || onlyCompareGenerated) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+}
+exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
+
+function strcmp(aStr1, aStr2) {
+ if (aStr1 === aStr2) {
+ return 0;
+ }
+
+ if (aStr1 === null) {
+ return 1; // aStr2 !== null
+ }
+
+ if (aStr2 === null) {
+ return -1; // aStr1 !== null
+ }
+
+ if (aStr1 > aStr2) {
+ return 1;
+ }
+
+ return -1;
+}
+
+/**
+ * Comparator between two mappings with inflated source and name strings where
+ * the generated positions are compared.
+ */
+function compareByGeneratedPositionsInflated(mappingA, mappingB) {
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+}
+exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
+
+/**
+ * Strip any JSON XSSI avoidance prefix from the string (as documented
+ * in the source maps specification), and then parse the string as
+ * JSON.
+ */
+function parseSourceMapInput(str) {
+ return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
+}
+exports.parseSourceMapInput = parseSourceMapInput;
+
+/**
+ * Compute the URL of a source given the the source root, the source's
+ * URL, and the source map's URL.
+ */
+function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
+ sourceURL = sourceURL || '';
+
+ if (sourceRoot) {
+ // This follows what Chrome does.
+ if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
+ sourceRoot += '/';
+ }
+ // The spec says:
+ // Line 4: An optional source root, useful for relocating source
+ // files on a server or removing repeated values in the
+ // “sources” entry. This value is prepended to the individual
+ // entries in the “source” field.
+ sourceURL = sourceRoot + sourceURL;
+ }
+
+ // Historically, SourceMapConsumer did not take the sourceMapURL as
+ // a parameter. This mode is still somewhat supported, which is why
+ // this code block is conditional. However, it's preferable to pass
+ // the source map URL to SourceMapConsumer, so that this function
+ // can implement the source URL resolution algorithm as outlined in
+ // the spec. This block is basically the equivalent of:
+ // new URL(sourceURL, sourceMapURL).toString()
+ // ... except it avoids using URL, which wasn't available in the
+ // older releases of node still supported by this library.
+ //
+ // The spec says:
+ // If the sources are not absolute URLs after prepending of the
+ // “sourceRoot”, the sources are resolved relative to the
+ // SourceMap (like resolving script src in a html document).
+ if (sourceMapURL) {
+ var parsed = urlParse(sourceMapURL);
+ if (!parsed) {
+ throw new Error("sourceMapURL could not be parsed");
+ }
+ if (parsed.path) {
+ // Strip the last path component, but keep the "/".
+ var index = parsed.path.lastIndexOf('/');
+ if (index >= 0) {
+ parsed.path = parsed.path.substring(0, index + 1);
+ }
+ }
+ sourceURL = join(urlGenerate(parsed), sourceURL);
+ }
+
+ return normalize(sourceURL);
+}
+exports.computeSourceURL = computeSourceURL;
diff --git a/frontend/node_modules/source-map-js/package.json b/frontend/node_modules/source-map-js/package.json
new file mode 100644
index 0000000..f58dbeb
--- /dev/null
+++ b/frontend/node_modules/source-map-js/package.json
@@ -0,0 +1,71 @@
+{
+ "name": "source-map-js",
+ "description": "Generates and consumes source maps",
+ "version": "1.2.1",
+ "homepage": "https://github.com/7rulnik/source-map-js",
+ "author": "Valentin 7rulnik Semirulnik <[email protected]>",
+ "contributors": [
+ "Nick Fitzgerald <[email protected]>",
+ "Tobias Koppers <[email protected]>",
+ "Duncan Beevers <[email protected]>",
+ "Stephen Crane <[email protected]>",
+ "Ryan Seddon <[email protected]>",
+ "Miles Elam <[email protected]>",
+ "Mihai Bazon <[email protected]>",
+ "Michael Ficarra <[email protected]>",
+ "Todd Wolfson <[email protected]>",
+ "Alexander Solovyov <[email protected]>",
+ "Felix Gnass <[email protected]>",
+ "Conrad Irwin <[email protected]>",
+ "usrbincc <[email protected]>",
+ "David Glasser <[email protected]>",
+ "Chase Douglas <[email protected]>",
+ "Evan Wallace <[email protected]>",
+ "Heather Arthur <[email protected]>",
+ "Hugh Kennedy <[email protected]>",
+ "David Glasser <[email protected]>",
+ "Simon Lydell <[email protected]>",
+ "Jmeas Smith <[email protected]>",
+ "Michael Z Goddard <[email protected]>",
+ "John Gozde <[email protected]>",
+ "Adam Kirkton <[email protected]>",
+ "Chris Montgomery <[email protected]>",
+ "J. Ryan Stinnett <[email protected]>",
+ "Jack Herrington <[email protected]>",
+ "Chris Truter <[email protected]>",
+ "Daniel Espeset <[email protected]>",
+ "Jamie Wong <[email protected]>",
+ "Eddy Bruël <[email protected]>",
+ "Hawken Rives <[email protected]>",
+ "Gilad Peleg <[email protected]>",
+ "djchie <[email protected]>",
+ "Gary Ye <[email protected]>",
+ "Nicolas Lalevée <[email protected]>"
+ ],
+ "repository": "7rulnik/source-map-js",
+ "main": "./source-map.js",
+ "files": [
+ "source-map.js",
+ "source-map.d.ts",
+ "lib/"
+ ],
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "license": "BSD-3-Clause",
+ "scripts": {
+ "test": "npm run build && node test/run-tests.js",
+ "build": "webpack --color",
+ "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
+ },
+ "devDependencies": {
+ "clean-publish": "^3.1.0",
+ "doctoc": "^0.15.0",
+ "webpack": "^1.12.0"
+ },
+ "clean-publish": {
+ "cleanDocs": true
+ },
+ "typings": "source-map.d.ts"
+}
diff --git a/frontend/node_modules/source-map-js/source-map.d.ts b/frontend/node_modules/source-map-js/source-map.d.ts
new file mode 100644
index 0000000..ec8892f
--- /dev/null
+++ b/frontend/node_modules/source-map-js/source-map.d.ts
@@ -0,0 +1,104 @@
+export interface StartOfSourceMap {
+ file?: string;
+ sourceRoot?: string;
+}
+
+export interface RawSourceMap extends StartOfSourceMap {
+ version: string;
+ sources: string[];
+ names: string[];
+ sourcesContent?: string[];
+ mappings: string;
+}
+
+export interface Position {
+ line: number;
+ column: number;
+}
+
+export interface LineRange extends Position {
+ lastColumn: number;
+}
+
+export interface FindPosition extends Position {
+ // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
+ bias?: number;
+}
+
+export interface SourceFindPosition extends FindPosition {
+ source: string;
+}
+
+export interface MappedPosition extends Position {
+ source: string;
+ name?: string;
+}
+
+export interface MappingItem {
+ source: string | null;
+ generatedLine: number;
+ generatedColumn: number;
+ originalLine: number | null;
+ originalColumn: number | null;
+ name: string | null;
+}
+
+export class SourceMapConsumer {
+ static GENERATED_ORDER: number;
+ static ORIGINAL_ORDER: number;
+
+ static GREATEST_LOWER_BOUND: number;
+ static LEAST_UPPER_BOUND: number;
+
+ constructor(rawSourceMap: RawSourceMap);
+ readonly file: string | undefined | null;
+ readonly sourceRoot: string | undefined | null;
+ readonly sourcesContent: readonly string[] | null | undefined;
+ readonly sources: readonly string[]
+
+ computeColumnSpans(): void;
+ originalPositionFor(generatedPosition: FindPosition): MappedPosition;
+ generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
+ allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
+ hasContentsOfAllSources(): boolean;
+ sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null;
+ eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
+}
+
+export interface Mapping {
+ generated: Position;
+ original?: Position | null;
+ source?: string | null;
+ name?: string | null;
+}
+
+export class SourceMapGenerator {
+ constructor(startOfSourceMap?: StartOfSourceMap);
+ static fromSourceMap(sourceMapConsumer: SourceMapConsumer, startOfSourceMap?: StartOfSourceMap): SourceMapGenerator;
+ addMapping(mapping: Mapping): void;
+ setSourceContent(sourceFile: string, sourceContent: string | null | undefined): void;
+ applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
+ toString(): string;
+ toJSON(): RawSourceMap;
+}
+
+export interface CodeWithSourceMap {
+ code: string;
+ map: SourceMapGenerator;
+}
+
+export class SourceNode {
+ constructor();
+ constructor(line: number, column: number, source: string);
+ constructor(line: number, column: number, source: string, chunk?: string, name?: string);
+ static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
+ add(chunk: string): void;
+ prepend(chunk: string): void;
+ setSourceContent(sourceFile: string, sourceContent: string): void;
+ walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
+ walkSourceContents(fn: (file: string, content: string) => void): void;
+ join(sep: string): SourceNode;
+ replaceRight(pattern: string, replacement: string): SourceNode;
+ toString(): string;
+ toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
+}
diff --git a/frontend/node_modules/source-map-js/source-map.js b/frontend/node_modules/source-map-js/source-map.js
new file mode 100644
index 0000000..bc88fe8
--- /dev/null
+++ b/frontend/node_modules/source-map-js/source-map.js
@@ -0,0 +1,8 @@
+/*
+ * Copyright 2009-2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE.txt or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
+exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
+exports.SourceNode = require('./lib/source-node').SourceNode;
diff --git a/frontend/node_modules/tinyglobby/LICENSE b/frontend/node_modules/tinyglobby/LICENSE
new file mode 100644
index 0000000..8657364
--- /dev/null
+++ b/frontend/node_modules/tinyglobby/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 Madeline Gurriarán
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/frontend/node_modules/tinyglobby/README.md b/frontend/node_modules/tinyglobby/README.md
new file mode 100644
index 0000000..15695e6
--- /dev/null
+++ b/frontend/node_modules/tinyglobby/README.md
@@ -0,0 +1,25 @@
+# tinyglobby
+
+[![npm version](https://img.shields.io/npm/v/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby)
+[![monthly downloads](https://img.shields.io/npm/dm/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby)
+
+A fast and minimal alternative to globby and fast-glob, meant to behave the same way.
+
+Both globby and fast-glob present some behavior no other globbing lib has,
+which makes it hard to manually replace with something smaller and better.
+
+This library uses only two subdependencies, compared to `globby`'s [23](https://npmgraph.js.org/[email protected])
+and `fast-glob`'s [17](https://npmgraph.js.org/[email protected]).
+
+## Usage
+
+```js
+import { glob, globSync } from 'tinyglobby';
+
+await glob(['files/*.ts', '!**/*.d.ts'], { cwd: 'src' });
+globSync('src/**/*.ts', { ignore: '**/*.d.ts' });
+```
+
+## Documentation
+
+Visit https://superchupu.dev/tinyglobby to read the full documentation.
diff --git a/frontend/node_modules/tinyglobby/package.json b/frontend/node_modules/tinyglobby/package.json
new file mode 100644
index 0000000..d0247c2
--- /dev/null
+++ b/frontend/node_modules/tinyglobby/package.json
@@ -0,0 +1,73 @@
+{
+ "name": "tinyglobby",
+ "version": "0.2.15",
+ "description": "A fast and minimal alternative to globby and fast-glob",
+ "type": "module",
+ "main": "./dist/index.cjs",
+ "module": "./dist/index.mjs",
+ "types": "./dist/index.d.cts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.mjs",
+ "require": "./dist/index.cjs"
+ },
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "files": [
+ "dist"
+ ],
+ "author": "Superchupu",
+ "license": "MIT",
+ "keywords": [
+ "glob",
+ "patterns",
+ "fast",
+ "implementation"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/SuperchupuDev/tinyglobby.git"
+ },
+ "bugs": {
+ "url": "https://github.com/SuperchupuDev/tinyglobby/issues"
+ },
+ "homepage": "https://superchupu.dev/tinyglobby",
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ },
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "^2.2.3",
+ "@types/node": "^24.3.1",
+ "@types/picomatch": "^4.0.2",
+ "fast-glob": "^3.3.3",
+ "fs-fixture": "^2.8.1",
+ "glob": "^11.0.3",
+ "tinybench": "^5.0.1",
+ "tsdown": "^0.14.2",
+ "typescript": "^5.9.2"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "publishConfig": {
+ "provenance": true
+ },
+ "scripts": {
+ "bench": "node benchmark/bench.ts",
+ "bench:setup": "node benchmark/setup.ts",
+ "build": "tsdown",
+ "check": "biome check",
+ "check:fix": "biome check --write --unsafe",
+ "format": "biome format --write",
+ "lint": "biome lint",
+ "test": "node --test \"test/**/*.ts\"",
+ "test:coverage": "node --test --experimental-test-coverage \"test/**/*.ts\"",
+ "test:only": "node --test --test-only \"test/**/*.ts\"",
+ "typecheck": "tsc --noEmit"
+ }
+}
\ No newline at end of file
diff --git a/frontend/node_modules/vite/LICENSE.md b/frontend/node_modules/vite/LICENSE.md
new file mode 100644
index 0000000..ed5c856
--- /dev/null
+++ b/frontend/node_modules/vite/LICENSE.md
@@ -0,0 +1,2144 @@
+# Vite core license
+Vite is released under the MIT license:
+
+MIT License
+
+Copyright (c) 2019-present, VoidZero Inc. and Vite contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+# Licenses of bundled dependencies
+The published Vite artifact additionally contains code with the following licenses:
+BSD-2-Clause, CC0-1.0, ISC, MIT
+
+# Bundled dependencies:
+## @jridgewell/gen-mapping, @jridgewell/remapping, @jridgewell/sourcemap-codec, @jridgewell/trace-mapping
+License: MIT
+By: Justin Ridgewell
+Repositories: git+https://github.com/jridgewell/sourcemaps.git, git+https://github.com/jridgewell/sourcemaps.git, git+https://github.com/jridgewell/sourcemaps.git, git+https://github.com/jridgewell/sourcemaps.git
+
+> Copyright 2024 Justin Ridgewell <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## @jridgewell/resolve-uri
+License: MIT
+By: Justin Ridgewell
+Repository: https://github.com/jridgewell/resolve-uri
+
+> Copyright 2019 Justin Ridgewell <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## @polka/compression
+License: MIT
+Repository: lukeed/polka
+
+---------------------------------------
+
+## @polka/url
+License: MIT
+By: Luke Edwards
+Repository: lukeed/polka
+
+---------------------------------------
+
+## @rolldown/pluginutils
+License: MIT
+Repository: git+https://github.com/rolldown/rolldown.git
+
+> MIT License
+>
+> Copyright (c) 2024-present VoidZero Inc. & Contributors
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+>
+> end of terms and conditions
+>
+> The licenses of externally maintained libraries from which parts of the Software is derived are listed [here](https://github.com/rolldown/rolldown/blob/main/THIRD-PARTY-LICENSE).
+
+---------------------------------------
+
+## @rollup/plugin-alias, @rollup/plugin-commonjs, @rollup/plugin-dynamic-import-vars, @rollup/pluginutils
+License: MIT
+By: Johannes Stein
+Repository: rollup/plugins
+
+License: MIT
+By: Rich Harris
+Repository: rollup/plugins
+
+License: MIT
+By: LarsDenBakker
+Repository: rollup/plugins
+
+License: MIT
+By: Rich Harris
+Repository: rollup/plugins
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## anymatch
+License: ISC
+By: Elan Shanker
+Repository: https://github.com/micromatch/anymatch
+
+> The ISC License
+>
+> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com)
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## artichokie
+License: MIT
+By: sapphi-red, Evan You
+Repository: git+https://github.com/sapphi-red/artichokie.git
+
+> MIT License
+>
+> Copyright (c) 2020-present, Yuxi (Evan) You
+> Copyright (c) 2023-present, sapphi-red
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## binary-extensions
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/binary-extensions
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+> Copyright (c) Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## braces, fill-range, is-number
+License: MIT
+By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm
+Repository: micromatch/braces
+
+License: MIT
+By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling
+Repository: jonschlinkert/fill-range
+
+License: MIT
+By: Jon Schlinkert, Olsten Larck, Rouven Weßling
+Repository: jonschlinkert/is-number
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## bundle-name, default-browser, default-browser-id, define-lazy-prop, is-docker, is-inside-container, is-wsl, open, run-applescript, wsl-utils
+License: MIT
+By: Sindre Sorhus
+Repositories: sindresorhus/bundle-name, sindresorhus/default-browser, sindresorhus/default-browser-id, sindresorhus/define-lazy-prop, sindresorhus/is-docker, sindresorhus/is-inside-container, sindresorhus/is-wsl, sindresorhus/open, sindresorhus/run-applescript, sindresorhus/wsl-utils
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## cac
+License: MIT
+By: egoist
+Repository: egoist/cac
+
+> The MIT License (MIT)
+>
+> Copyright (c) EGOIST <[email protected]> (https://github.com/egoist)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## chokidar
+License: MIT
+By: Paul Miller, Elan Shanker
+Repository: git+https://github.com/paulmillr/chokidar.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the “Software”), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## commondir, shell-quote
+License: MIT
+By: James Halliday
+Repositories: http://github.com/substack/node-commondir.git, http://github.com/ljharb/shell-quote.git
+
+> The MIT License
+>
+> Copyright (c) 2013 James Halliday ([email protected])
+>
+> Permission is hereby granted, free of charge,
+> to any person obtaining a copy of this software and
+> associated documentation files (the "Software"), to
+> deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify,
+> merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom
+> the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice
+> shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+> ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## connect
+License: MIT
+By: TJ Holowaychuk, Douglas Christopher Wilson, Jonathan Ong, Tim Caswell
+Repository: senchalabs/connect
+
+> (The MIT License)
+>
+> Copyright (c) 2010 Sencha Inc.
+> Copyright (c) 2011 LearnBoost
+> Copyright (c) 2011-2014 TJ Holowaychuk
+> Copyright (c) 2015 Douglas Christopher Wilson
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## convert-source-map
+License: MIT
+By: Thorsten Lorenz
+Repository: git://github.com/thlorenz/convert-source-map.git
+
+> Copyright 2013 Thorsten Lorenz.
+> All rights reserved.
+>
+> Permission is hereby granted, free of charge, to any person
+> obtaining a copy of this software and associated documentation
+> files (the "Software"), to deal in the Software without
+> restriction, including without limitation the rights to use,
+> copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the
+> Software is furnished to do so, subject to the following
+> conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+> OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## cors
+License: MIT
+By: Troy Goode
+Repository: expressjs/cors
+
+> (The MIT License)
+>
+> Copyright (c) 2013 Troy Goode <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## cross-spawn
+License: MIT
+By: André Cruz
+Repository: [email protected]:moxystudio/node-cross-spawn.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2018 Made With MOXY Lda <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## cssesc
+License: MIT
+By: Mathias Bynens
+Repository: https://github.com/mathiasbynens/cssesc.git
+
+> Copyright Mathias Bynens <https://mathiasbynens.be/>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> "Software"), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## debug
+License: MIT
+By: Josh Junon, TJ Holowaychuk, Nathan Rajlich, Andrew Rhyne
+Repository: git://github.com/debug-js/debug.git
+
+> (The MIT License)
+>
+> Copyright (c) 2014-2017 TJ Holowaychuk <[email protected]>
+> Copyright (c) 2018-2021 Josh Junon
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+> and associated documentation files (the 'Software'), to deal in the Software without restriction,
+> including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
+> and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial
+> portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+> LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## dotenv
+License: BSD-2-Clause
+Repository: git://github.com/motdotla/dotenv.git
+
+> Copyright (c) 2015, Scott Motte
+> All rights reserved.
+>
+> Redistribution and use in source and binary forms, with or without
+> modification, are permitted provided that the following conditions are met:
+>
+> * Redistributions of source code must retain the above copyright notice, this
+> list of conditions and the following disclaimer.
+>
+> * Redistributions in binary form must reproduce the above copyright notice,
+> this list of conditions and the following disclaimer in the documentation
+> and/or other materials provided with the distribution.
+>
+> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+---------------------------------------
+
+## dotenv-expand
+License: BSD-2-Clause
+By: motdotla
+Repository: https://github.com/motdotla/dotenv-expand
+
+> Copyright (c) 2016, Scott Motte
+> All rights reserved.
+>
+> Redistribution and use in source and binary forms, with or without
+> modification, are permitted provided that the following conditions are met:
+>
+> * Redistributions of source code must retain the above copyright notice, this
+> list of conditions and the following disclaimer.
+>
+> * Redistributions in binary form must reproduce the above copyright notice,
+> this list of conditions and the following disclaimer in the documentation
+> and/or other materials provided with the distribution.
+>
+> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+---------------------------------------
+
+## ee-first
+License: MIT
+By: Jonathan Ong, Douglas Christopher Wilson
+Repository: jonathanong/ee-first
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014 Jonathan Ong [email protected]
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## encodeurl
+License: MIT
+By: Douglas Christopher Wilson
+Repository: pillarjs/encodeurl
+
+> (The MIT License)
+>
+> Copyright (c) 2016 Douglas Christopher Wilson
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## entities
+License: BSD-2-Clause
+By: Felix Boehm
+Repository: git://github.com/fb55/entities.git
+
+> Copyright (c) Felix Böhm
+> All rights reserved.
+>
+> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+>
+> Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+>
+> Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+>
+> THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
+> EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+---------------------------------------
+
+## es-module-lexer
+License: MIT
+By: Guy Bedford
+Repository: git+https://github.com/guybedford/es-module-lexer.git
+
+> MIT License
+> -----------
+>
+> Copyright (C) 2018-2022 Guy Bedford
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## escape-html
+License: MIT
+Repository: component/escape-html
+
+> (The MIT License)
+>
+> Copyright (c) 2012-2013 TJ Holowaychuk
+> Copyright (c) 2015 Andreas Lubbe
+> Copyright (c) 2015 Tiancheng "Timothy" Gu
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## estree-walker
+License: MIT
+By: Rich Harris
+Repository: https://github.com/Rich-Harris/estree-walker
+
+> Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## etag
+License: MIT
+By: Douglas Christopher Wilson, David Björklund
+Repository: jshttp/etag
+
+> (The MIT License)
+>
+> Copyright (c) 2014-2016 Douglas Christopher Wilson
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## finalhandler
+License: MIT
+By: Douglas Christopher Wilson
+Repository: pillarjs/finalhandler
+
+> (The MIT License)
+>
+> Copyright (c) 2014-2017 Douglas Christopher Wilson <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## follow-redirects
+License: MIT
+By: Ruben Verborgh, Olivier Lalonde, James Talmage
+Repository: git+ssh://[email protected]/follow-redirects/follow-redirects.git
+
+> Copyright 2014–present Olivier Lalonde <[email protected]>, James Talmage <[email protected]>, Ruben Verborgh
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+> of the Software, and to permit persons to whom the Software is furnished to do
+> so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+> IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## generic-names
+License: MIT
+By: Alexey Litvinov
+Repository: git+https://github.com/css-modules/generic-names.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2015 Alexey Litvinov
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## glob-parent
+License: ISC
+By: Gulp Team, Elan Shanker, Blaine Bublitz
+Repository: gulpjs/glob-parent
+
+> The ISC License
+>
+> Copyright (c) 2015, 2019 Elan Shanker
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## host-validation-middleware
+License: MIT
+By: sapphi-red
+Repository: git+https://github.com/sapphi-red/host-validation-middleware.git
+
+> MIT License
+>
+> Copyright (c) 2025 sapphi-red
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## http-proxy-3
+License: MIT
+By: William Stein, Charlie Robbins, Jimb Esser, jcrugzz
+Repository: https://github.com/sagemathinc/http-proxy-3.git
+
+> node-http-3
+>
+> Copyright (c) 2010-2025 William Stein, Charlie Robbins, Jarrett Cruger & the Contributors.
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> "Software"), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## icss-utils
+License: ISC
+By: Glen Maddern
+Repository: git+https://github.com/css-modules/icss-utils.git
+
+> ISC License (ISC)
+> Copyright 2018 Glen Maddern
+>
+> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## is-binary-path
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/is-binary-path
+
+> MIT License
+>
+> Copyright (c) 2019 Sindre Sorhus <[email protected]> (https://sindresorhus.com), Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## is-extglob
+License: MIT
+By: Jon Schlinkert
+Repository: jonschlinkert/is-extglob
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2016, Jon Schlinkert
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## is-glob
+License: MIT
+By: Jon Schlinkert, Brian Woodward, Daniel Perez
+Repository: micromatch/is-glob
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2017, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## is-reference
+License: MIT
+By: Rich Harris
+Repository: git+https://github.com/Rich-Harris/is-reference.git
+
+---------------------------------------
+
+## isexe, which
+License: ISC
+By: Isaac Z. Schlueter
+Repositories: git+https://github.com/isaacs/isexe.git, git://github.com/isaacs/node-which.git
+
+> The ISC License
+>
+> Copyright (c) Isaac Z. Schlueter and Contributors
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## js-tokens
+License: MIT
+By: Simon Lydell
+Repository: lydell/js-tokens
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024 Simon Lydell
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## launch-editor, launch-editor-middleware
+License: MIT
+By: Evan You
+Repositories: git+https://github.com/yyx990803/launch-editor.git, git+https://github.com/yyx990803/launch-editor.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2017-present, Yuxi (Evan) You
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## lilconfig
+License: MIT
+By: antonk52
+Repository: https://github.com/antonk52/lilconfig
+
+> MIT License
+>
+> Copyright (c) 2022 Anton Kastritskiy
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## loader-utils
+License: MIT
+By: Tobias Koppers @sokra
+Repository: https://github.com/webpack/loader-utils.git
+
+> Copyright JS Foundation and other contributors
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## lodash.camelcase
+License: MIT
+By: John-David Dalton, Blaine Bublitz, Mathias Bynens
+Repository: lodash/lodash
+
+> Copyright jQuery Foundation and other contributors <https://jquery.org/>
+>
+> Based on Underscore.js, copyright Jeremy Ashkenas,
+> DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
+>
+> This software consists of voluntary contributions made by many
+> individuals. For exact contribution history, see the revision history
+> available at https://github.com/lodash/lodash
+>
+> The following license applies to all parts of this software except as
+> documented below:
+>
+> ====
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> "Software"), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+>
+> ====
+>
+> Copyright and related rights for sample code are waived via CC0. Sample
+> code is defined as all source code displayed within the prose of the
+> documentation.
+>
+> CC0: http://creativecommons.org/publicdomain/zero/1.0/
+>
+> ====
+>
+> Files located in the node_modules and vendor directories are externally
+> maintained libraries used by this software which have their own
+> licenses; we recommend you read them, as their terms may differ from the
+> terms above.
+
+---------------------------------------
+
+## magic-string
+License: MIT
+By: Rich Harris
+Repository: https://github.com/rich-harris/magic-string.git
+
+> Copyright 2018 Rich Harris
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## mlly, ufo
+License: MIT
+Repositories: unjs/mlly, unjs/ufo
+
+> MIT License
+>
+> Copyright (c) Pooya Parsa <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## mrmime
+License: MIT
+By: Luke Edwards
+Repository: lukeed/mrmime
+
+> The MIT License (MIT)
+>
+> Copyright (c) Luke Edwards <[email protected]> (https://lukeed.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## ms
+License: MIT
+Repository: vercel/ms
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2020 Vercel, Inc.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## normalize-path
+License: MIT
+By: Jon Schlinkert, Blaine Bublitz
+Repository: jonschlinkert/normalize-path
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014-2018, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## object-assign
+License: MIT
+By: Sindre Sorhus
+Repository: sindresorhus/object-assign
+
+> The MIT License (MIT)
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## on-finished
+License: MIT
+By: Douglas Christopher Wilson, Jonathan Ong
+Repository: jshttp/on-finished
+
+> (The MIT License)
+>
+> Copyright (c) 2013 Jonathan Ong <[email protected]>
+> Copyright (c) 2014 Douglas Christopher Wilson <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## parse5
+License: MIT
+By: Ivan Nikulin, https://github.com/inikulin/parse5/graphs/contributors
+Repository: git://github.com/inikulin/parse5.git
+
+> Copyright (c) 2013-2019 Ivan Nikulin ([email protected], https://github.com/inikulin)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## parseurl
+License: MIT
+By: Douglas Christopher Wilson, Jonathan Ong
+Repository: pillarjs/parseurl
+
+> (The MIT License)
+>
+> Copyright (c) 2014 Jonathan Ong <[email protected]>
+> Copyright (c) 2014-2017 Douglas Christopher Wilson <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## path-key, shebang-regex
+License: MIT
+By: Sindre Sorhus
+Repositories: sindresorhus/path-key, sindresorhus/shebang-regex
+
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## periscopic
+License: MIT
+Repository: Rich-Harris/periscopic
+
+> Copyright (c) 2019 Rich Harris
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## picocolors
+License: ISC
+By: Alexey Raspopov
+Repository: alexeyraspopov/picocolors
+
+> ISC License
+>
+> Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
+>
+> Permission to use, copy, modify, and/or distribute this software for any
+> purpose with or without fee is hereby granted, provided that the above
+> copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+> OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## postcss-import
+License: MIT
+By: Maxime Thirouin
+Repository: https://github.com/postcss/postcss-import.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## postcss-load-config
+License: MIT
+By: Michael Ciniawky, Ryan Dunckel, Mateusz Derks, Dalton Santos, Patrick Gilday, François Wouts
+Repository: postcss/postcss-load-config
+
+> The MIT License (MIT)
+>
+> Copyright Michael Ciniawsky <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## postcss-modules
+License: MIT
+By: Alexander Madyankin
+Repository: https://github.com/css-modules/postcss-modules.git
+
+> The MIT License (MIT)
+>
+> Copyright 2015-present Alexander Madyankin <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## postcss-modules-extract-imports
+License: ISC
+By: Glen Maddern
+Repository: https://github.com/css-modules/postcss-modules-extract-imports.git
+
+> Copyright 2015 Glen Maddern
+>
+> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## postcss-modules-local-by-default
+License: MIT
+By: Mark Dalgleish
+Repository: https://github.com/css-modules/postcss-modules-local-by-default.git
+
+> The MIT License (MIT)
+>
+> Copyright 2015 Mark Dalgleish <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## postcss-modules-scope
+License: ISC
+By: Glen Maddern
+Repository: https://github.com/css-modules/postcss-modules-scope.git
+
+> ISC License (ISC)
+>
+> Copyright (c) 2015, Glen Maddern
+>
+> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## postcss-modules-values
+License: ISC
+By: Glen Maddern
+Repository: git+https://github.com/css-modules/postcss-modules-values.git
+
+> ISC License (ISC)
+>
+> Copyright (c) 2015, Glen Maddern
+>
+> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
+>
+> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---------------------------------------
+
+## postcss-selector-parser
+License: MIT
+By: Ben Briggs, Chris Eppstein
+Repository: postcss/postcss-selector-parser
+
+> Copyright (c) Ben Briggs <[email protected]> (http://beneb.info)
+>
+> Permission is hereby granted, free of charge, to any person
+> obtaining a copy of this software and associated documentation
+> files (the "Software"), to deal in the Software without
+> restriction, including without limitation the rights to use,
+> copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the
+> Software is furnished to do so, subject to the following
+> conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+> OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## postcss-value-parser
+License: MIT
+By: Bogdan Chadkin
+Repository: https://github.com/TrySound/postcss-value-parser.git
+
+> Copyright (c) Bogdan Chadkin <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person
+> obtaining a copy of this software and associated documentation
+> files (the "Software"), to deal in the Software without
+> restriction, including without limitation the rights to use,
+> copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the
+> Software is furnished to do so, subject to the following
+> conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+> OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## readdirp
+License: MIT
+By: Thorsten Lorenz, Paul Miller
+Repository: git://github.com/paulmillr/readdirp.git
+
+> MIT License
+>
+> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## resolve.exports, totalist
+License: MIT
+By: Luke Edwards
+Repositories: lukeed/resolve.exports, lukeed/totalist
+
+> The MIT License (MIT)
+>
+> Copyright (c) Luke Edwards <[email protected]> (lukeed.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## shebang-command
+License: MIT
+By: Kevin Mårtensson
+Repository: kevva/shebang-command
+
+> MIT License
+>
+> Copyright (c) Kevin Mårtensson <[email protected]> (github.com/kevva)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## sirv
+License: MIT
+By: Luke Edwards
+Repository: lukeed/sirv
+
+---------------------------------------
+
+## statuses
+License: MIT
+By: Douglas Christopher Wilson, Jonathan Ong
+Repository: jshttp/statuses
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2014 Jonathan Ong <[email protected]>
+> Copyright (c) 2016 Douglas Christopher Wilson <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## string-hash
+License: CC0-1.0
+By: The Dark Sky Company
+Repository: git://github.com/darkskyapp/string-hash.git
+
+---------------------------------------
+
+## strip-literal
+License: MIT
+By: Anthony Fu
+Repository: git+https://github.com/antfu/strip-literal.git
+
+> MIT License
+>
+> Copyright (c) 2022 Anthony Fu <https://github.com/antfu>
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## to-regex-range
+License: MIT
+By: Jon Schlinkert, Rouven Weßling
+Repository: micromatch/to-regex-range
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2015-present, Jon Schlinkert.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+---------------------------------------
+
+## tsconfck
+License: MIT
+By: dominikg
+Repository: git+https://github.com/dominikg/tsconfck.git
+
+> MIT License
+>
+> Copyright (c) 2021-present dominikg and [contributors](https://github.com/dominikg/tsconfck/graphs/contributors)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+>
+> -- Licenses for 3rd-party code included in tsconfck --
+>
+> # strip-bom and strip-json-comments
+> MIT License
+>
+> Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
+## unpipe
+License: MIT
+By: Douglas Christopher Wilson
+Repository: stream-utils/unpipe
+
+> (The MIT License)
+>
+> Copyright (c) 2015 Douglas Christopher Wilson <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## util-deprecate
+License: MIT
+By: Nathan Rajlich
+Repository: git://github.com/TooTallNate/util-deprecate.git
+
+> (The MIT License)
+>
+> Copyright (c) 2014 Nathan Rajlich <[email protected]>
+>
+> Permission is hereby granted, free of charge, to any person
+> obtaining a copy of this software and associated documentation
+> files (the "Software"), to deal in the Software without
+> restriction, including without limitation the rights to use,
+> copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the
+> Software is furnished to do so, subject to the following
+> conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+> OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## utils-merge
+License: MIT
+By: Jared Hanson
+Repository: git://github.com/jaredhanson/utils-merge.git
+
+> The MIT License (MIT)
+>
+> Copyright (c) 2013-2017 Jared Hanson
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## vary
+License: MIT
+By: Douglas Christopher Wilson
+Repository: jshttp/vary
+
+> (The MIT License)
+>
+> Copyright (c) 2014-2017 Douglas Christopher Wilson
+>
+> Permission is hereby granted, free of charge, to any person obtaining
+> a copy of this software and associated documentation files (the
+> 'Software'), to deal in the Software without restriction, including
+> without limitation the rights to use, copy, modify, merge, publish,
+> distribute, sublicense, and/or sell copies of the Software, and to
+> permit persons to whom the Software is furnished to do so, subject to
+> the following conditions:
+>
+> The above copyright notice and this permission notice shall be
+> included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------------------------
+
+## ws
+License: MIT
+By: Einar Otto Stangvik
+Repository: git+https://github.com/websockets/ws.git
+
+> Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
+> Copyright (c) 2013 Arnout Kazemier and contributors
+> Copyright (c) 2016 Luigi Pinca and contributors
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of
+> this software and associated documentation files (the "Software"), to deal in
+> the Software without restriction, including without limitation the rights to
+> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+> the Software, and to permit persons to whom the Software is furnished to do so,
+> subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/frontend/node_modules/vite/README.md b/frontend/node_modules/vite/README.md
new file mode 100644
index 0000000..b0e348b
--- /dev/null
+++ b/frontend/node_modules/vite/README.md
@@ -0,0 +1,20 @@
+# Vite ⚡
+
+> Next Generation Frontend Tooling
+
+- 💡 Instant Server Start
+- ⚡️ Lightning Fast HMR
+- 🛠️ Rich Features
+- 📦 Optimized Build
+- 🔩 Universal Plugin Interface
+- 🔑 Fully Typed APIs
+
+Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts:
+
+- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vite.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement).
+
+- A [build command](https://vite.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production.
+
+In addition, Vite is highly extensible via its [Plugin API](https://vite.dev/guide/api-plugin.html) and [JavaScript API](https://vite.dev/guide/api-javascript.html) with full typing support.
+
+[Read the Docs to Learn More](https://vite.dev).
diff --git a/frontend/node_modules/vite/bin/openChrome.js b/frontend/node_modules/vite/bin/openChrome.js
new file mode 100644
index 0000000..5a4aa95
--- /dev/null
+++ b/frontend/node_modules/vite/bin/openChrome.js
@@ -0,0 +1,68 @@
+/*
+Copyright (c) 2015-present, Facebook, Inc.
+
+This source code is licensed under the MIT license found in the
+LICENSE file at
+https://github.com/facebook/create-react-app/blob/main/LICENSE
+*/
+
+/* global Application */
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+function run(argv) {
+ const urlToOpen = argv[0]
+ // Allow requested program to be optional, default to Google Chrome
+ const programName = argv[1] ?? 'Google Chrome'
+
+ const app = Application(programName)
+
+ if (app.windows.length === 0) {
+ app.Window().make()
+ }
+
+ // 1: Looking for tab running debugger then,
+ // Reload debugging tab if found, then return
+ const found = lookupTabWithUrl(urlToOpen, app)
+ if (found) {
+ found.targetWindow.activeTabIndex = found.targetTabIndex
+ found.targetTab.reload()
+ found.targetWindow.index = 1
+ app.activate()
+ return
+ }
+
+ // 2: Looking for Empty tab
+ // In case debugging tab was not found
+ // We try to find an empty tab instead
+ const emptyTabFound = lookupTabWithUrl('chrome://newtab/', app)
+ if (emptyTabFound) {
+ emptyTabFound.targetWindow.activeTabIndex = emptyTabFound.targetTabIndex
+ emptyTabFound.targetTab.url = urlToOpen
+ app.activate()
+ return
+ }
+
+ // 3: Create new tab
+ // both debugging and empty tab were not found make a new tab with url
+ const firstWindow = app.windows[0]
+ firstWindow.tabs.push(app.Tab({ url: urlToOpen }))
+ app.activate()
+}
+
+/**
+ * Lookup tab with given url
+ */
+function lookupTabWithUrl(lookupUrl, app) {
+ const windows = app.windows()
+ for (const window of windows) {
+ for (const [tabIndex, tab] of window.tabs().entries()) {
+ if (tab.url().includes(lookupUrl)) {
+ return {
+ targetTab: tab,
+ targetTabIndex: tabIndex + 1,
+ targetWindow: window,
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/node_modules/vite/bin/vite.js b/frontend/node_modules/vite/bin/vite.js
new file mode 100644
index 0000000..79c49ab
--- /dev/null
+++ b/frontend/node_modules/vite/bin/vite.js
@@ -0,0 +1,79 @@
+#!/usr/bin/env node
+import { performance } from 'node:perf_hooks'
+import module from 'node:module'
+
+if (!import.meta.url.includes('node_modules')) {
+ if (!process.env.DEBUG_DISABLE_SOURCE_MAP) {
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins -- only used in dev
+ process.setSourceMapsEnabled(true)
+ }
+
+ process.on('unhandledRejection', (err) => {
+ throw new Error('UNHANDLED PROMISE REJECTION', { cause: err })
+ })
+}
+
+global.__vite_start_time = performance.now()
+
+// check debug mode first before requiring the CLI.
+const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
+const filterIndex = process.argv.findIndex((arg) =>
+ /^(?:-f|--filter)$/.test(arg),
+)
+const profileIndex = process.argv.indexOf('--profile')
+
+if (debugIndex > 0) {
+ let value = process.argv[debugIndex + 1]
+ if (!value || value[0] === '-') {
+ value = 'vite:*'
+ } else {
+ // support debugging multiple flags with comma-separated list
+ value = value
+ .split(',')
+ .map((v) => `vite:${v}`)
+ .join(',')
+ }
+ process.env.DEBUG = `${
+ process.env.DEBUG ? process.env.DEBUG + ',' : ''
+ }${value}`
+
+ if (filterIndex > 0) {
+ const filter = process.argv[filterIndex + 1]
+ if (filter && filter[0] !== '-') {
+ process.env.VITE_DEBUG_FILTER = filter
+ }
+ }
+}
+
+function start() {
+ try {
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists
+ module.enableCompileCache?.()
+ // flush the cache after 10s because the cache is not flushed until process end
+ // for dev server, the cache is never flushed unless manually flushed because the process.exit is called
+ // also flushing the cache in SIGINT handler seems to cause the process to hang
+ setTimeout(() => {
+ try {
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists
+ module.flushCompileCache?.()
+ } catch {}
+ }, 10 * 1000).unref()
+ } catch {}
+ return import('../dist/node/cli.js')
+}
+
+if (profileIndex > 0) {
+ process.argv.splice(profileIndex, 1)
+ const next = process.argv[profileIndex]
+ if (next && next[0] !== '-') {
+ process.argv.splice(profileIndex, 1)
+ }
+ const inspector = await import('node:inspector').then((r) => r.default)
+ const session = (global.__vite_profile_session = new inspector.Session())
+ session.connect()
+ session.post('Profiler.enable', () => {
+ session.post('Profiler.start', start)
+ })
+} else {
+ start()
+}
diff --git a/frontend/node_modules/vite/client.d.ts b/frontend/node_modules/vite/client.d.ts
new file mode 100644
index 0000000..3a9dd88
--- /dev/null
+++ b/frontend/node_modules/vite/client.d.ts
@@ -0,0 +1,279 @@
+/// <reference path="./types/importMeta.d.ts" />
+
+// CSS modules
+type CSSModuleClasses = { readonly [key: string]: string }
+
+declare module '*.module.css' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.scss' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.sass' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.less' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.styl' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.stylus' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.pcss' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+declare module '*.module.sss' {
+ const classes: CSSModuleClasses
+ export default classes
+}
+
+// CSS
+declare module '*.css' {}
+declare module '*.scss' {}
+declare module '*.sass' {}
+declare module '*.less' {}
+declare module '*.styl' {}
+declare module '*.stylus' {}
+declare module '*.pcss' {}
+declare module '*.sss' {}
+
+// Built-in asset types
+// see `src/node/constants.ts`
+
+// images
+declare module '*.apng' {
+ const src: string
+ export default src
+}
+declare module '*.bmp' {
+ const src: string
+ export default src
+}
+declare module '*.png' {
+ const src: string
+ export default src
+}
+declare module '*.jpg' {
+ const src: string
+ export default src
+}
+declare module '*.jpeg' {
+ const src: string
+ export default src
+}
+declare module '*.jfif' {
+ const src: string
+ export default src
+}
+declare module '*.pjpeg' {
+ const src: string
+ export default src
+}
+declare module '*.pjp' {
+ const src: string
+ export default src
+}
+declare module '*.gif' {
+ const src: string
+ export default src
+}
+declare module '*.svg' {
+ const src: string
+ export default src
+}
+declare module '*.ico' {
+ const src: string
+ export default src
+}
+declare module '*.webp' {
+ const src: string
+ export default src
+}
+declare module '*.avif' {
+ const src: string
+ export default src
+}
+declare module '*.cur' {
+ const src: string
+ export default src
+}
+declare module '*.jxl' {
+ const src: string
+ export default src
+}
+
+// media
+declare module '*.mp4' {
+ const src: string
+ export default src
+}
+declare module '*.webm' {
+ const src: string
+ export default src
+}
+declare module '*.ogg' {
+ const src: string
+ export default src
+}
+declare module '*.mp3' {
+ const src: string
+ export default src
+}
+declare module '*.wav' {
+ const src: string
+ export default src
+}
+declare module '*.flac' {
+ const src: string
+ export default src
+}
+declare module '*.aac' {
+ const src: string
+ export default src
+}
+declare module '*.opus' {
+ const src: string
+ export default src
+}
+declare module '*.mov' {
+ const src: string
+ export default src
+}
+declare module '*.m4a' {
+ const src: string
+ export default src
+}
+declare module '*.vtt' {
+ const src: string
+ export default src
+}
+
+// fonts
+declare module '*.woff' {
+ const src: string
+ export default src
+}
+declare module '*.woff2' {
+ const src: string
+ export default src
+}
+declare module '*.eot' {
+ const src: string
+ export default src
+}
+declare module '*.ttf' {
+ const src: string
+ export default src
+}
+declare module '*.otf' {
+ const src: string
+ export default src
+}
+
+// other
+declare module '*.webmanifest' {
+ const src: string
+ export default src
+}
+declare module '*.pdf' {
+ const src: string
+ export default src
+}
+declare module '*.txt' {
+ const src: string
+ export default src
+}
+
+// wasm?init
+declare module '*.wasm?init' {
+ const initWasm: (
+ options?: WebAssembly.Imports,
+ ) => Promise<WebAssembly.Instance>
+ export default initWasm
+}
+
+// web worker
+declare module '*?worker' {
+ const workerConstructor: {
+ new (options?: { name?: string }): Worker
+ }
+ export default workerConstructor
+}
+
+declare module '*?worker&inline' {
+ const workerConstructor: {
+ new (options?: { name?: string }): Worker
+ }
+ export default workerConstructor
+}
+
+declare module '*?worker&url' {
+ const src: string
+ export default src
+}
+
+declare module '*?sharedworker' {
+ const sharedWorkerConstructor: {
+ new (options?: { name?: string }): SharedWorker
+ }
+ export default sharedWorkerConstructor
+}
+
+declare module '*?sharedworker&inline' {
+ const sharedWorkerConstructor: {
+ new (options?: { name?: string }): SharedWorker
+ }
+ export default sharedWorkerConstructor
+}
+
+declare module '*?sharedworker&url' {
+ const src: string
+ export default src
+}
+
+declare module '*?raw' {
+ const src: string
+ export default src
+}
+
+declare module '*?url' {
+ const src: string
+ export default src
+}
+
+declare module '*?inline' {
+ const src: string
+ export default src
+}
+
+declare module '*?no-inline' {
+ const src: string
+ export default src
+}
+
+declare module '*?url&inline' {
+ const src: string
+ export default src
+}
+
+declare module '*?url&no-inline' {
+ const src: string
+ export default src
+}
+
+declare interface VitePreloadErrorEvent extends Event {
+ payload: Error
+}
+
+declare interface WindowEventMap {
+ 'vite:preloadError': VitePreloadErrorEvent
+}
diff --git a/frontend/node_modules/vite/misc/false.js b/frontend/node_modules/vite/misc/false.js
new file mode 100644
index 0000000..2693369
--- /dev/null
+++ b/frontend/node_modules/vite/misc/false.js
@@ -0,0 +1 @@
+export default false
diff --git a/frontend/node_modules/vite/misc/true.js b/frontend/node_modules/vite/misc/true.js
new file mode 100644
index 0000000..186b120
--- /dev/null
+++ b/frontend/node_modules/vite/misc/true.js
@@ -0,0 +1 @@
+export default true
diff --git a/frontend/node_modules/vite/package.json b/frontend/node_modules/vite/package.json
new file mode 100644
index 0000000..db2438d
--- /dev/null
+++ b/frontend/node_modules/vite/package.json
@@ -0,0 +1,199 @@
+{
+ "name": "vite",
+ "version": "7.1.12",
+ "type": "module",
+ "license": "MIT",
+ "author": "Evan You",
+ "description": "Native-ESM powered web dev build tool",
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "keywords": [
+ "frontend",
+ "framework",
+ "hmr",
+ "dev-server",
+ "build-tool",
+ "vite"
+ ],
+ "main": "./dist/node/index.js",
+ "types": "./dist/node/index.d.ts",
+ "exports": {
+ ".": "./dist/node/index.js",
+ "./client": {
+ "types": "./client.d.ts"
+ },
+ "./module-runner": "./dist/node/module-runner.js",
+ "./dist/client/*": "./dist/client/*",
+ "./types/*": {
+ "types": "./types/*"
+ },
+ "./types/internal/*": null,
+ "./package.json": "./package.json"
+ },
+ "typesVersions": {
+ "*": {
+ "module-runner": [
+ "dist/node/module-runner.d.ts"
+ ]
+ }
+ },
+ "imports": {
+ "#module-sync-enabled": {
+ "module-sync": "./misc/true.js",
+ "default": "./misc/false.js"
+ },
+ "#types/*": "./types/*.d.ts",
+ "#dep-types/*": "./src/types/*.d.ts"
+ },
+ "files": [
+ "bin",
+ "dist",
+ "misc/**/*.js",
+ "client.d.ts",
+ "types"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/vitejs/vite.git",
+ "directory": "packages/vite"
+ },
+ "bugs": {
+ "url": "https://github.com/vitejs/vite/issues"
+ },
+ "homepage": "https://vite.dev",
+ "funding": "https://github.com/vitejs/vite?sponsor=1",
+ "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
+ "dependencies": {
+ "esbuild": "^0.25.0",
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3",
+ "postcss": "^8.5.6",
+ "rollup": "^4.43.0",
+ "tinyglobby": "^0.2.15"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "devDependencies": {
+ "@babel/parser": "^7.28.4",
+ "@jridgewell/remapping": "^2.3.5",
+ "@jridgewell/trace-mapping": "^0.3.31",
+ "@oxc-project/types": "0.90.0",
+ "@polka/compression": "^1.0.0-next.25",
+ "@rolldown/pluginutils": "^1.0.0-beta.43",
+ "@rollup/plugin-alias": "^5.1.1",
+ "@rollup/plugin-commonjs": "28.0.6",
+ "@rollup/plugin-dynamic-import-vars": "2.1.4",
+ "@rollup/pluginutils": "^5.3.0",
+ "@types/escape-html": "^1.0.4",
+ "@types/pnpapi": "^0.0.5",
+ "artichokie": "^0.4.2",
+ "baseline-browser-mapping": "^2.8.18",
+ "cac": "^6.7.14",
+ "chokidar": "^3.6.0",
+ "connect": "^3.7.0",
+ "convert-source-map": "^2.0.0",
+ "cors": "^2.8.5",
+ "cross-spawn": "^7.0.6",
+ "debug": "^4.4.3",
+ "dotenv": "^17.2.3",
+ "dotenv-expand": "^12.0.3",
+ "es-module-lexer": "^1.7.0",
+ "escape-html": "^1.0.3",
+ "estree-walker": "^3.0.3",
+ "etag": "^1.8.1",
+ "host-validation-middleware": "^0.1.2",
+ "http-proxy-3": "^1.22.0",
+ "launch-editor-middleware": "^2.11.1",
+ "lightningcss": "^1.30.2",
+ "magic-string": "^0.30.19",
+ "mlly": "^1.8.0",
+ "mrmime": "^2.0.1",
+ "nanoid": "^5.1.6",
+ "open": "^10.2.0",
+ "parse5": "^8.0.0",
+ "pathe": "^2.0.3",
+ "periscopic": "^4.0.2",
+ "picocolors": "^1.1.1",
+ "postcss-import": "^16.1.1",
+ "postcss-load-config": "^6.0.1",
+ "postcss-modules": "^6.0.1",
+ "premove": "^4.0.0",
+ "resolve.exports": "^2.0.3",
+ "rolldown": "^1.0.0-beta.43",
+ "rolldown-plugin-dts": "^0.16.11",
+ "rollup-plugin-license": "^3.6.0",
+ "sass": "^1.93.2",
+ "sass-embedded": "^1.93.2",
+ "sirv": "^3.0.2",
+ "strip-literal": "^3.1.0",
+ "terser": "^5.44.0",
+ "tsconfck": "^3.1.6",
+ "ufo": "^1.6.1",
+ "ws": "^8.18.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "lightningcss": "^1.21.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ },
+ "scripts": {
+ "dev": "premove dist && pnpm build-bundle -w",
+ "build": "premove dist && pnpm build-bundle && pnpm build-types",
+ "build-bundle": "rolldown --config rolldown.config.ts",
+ "build-types": "pnpm build-types-roll && pnpm build-types-check",
+ "build-types-roll": "rolldown --config rolldown.dts.config.ts",
+ "build-types-check": "tsc --project tsconfig.check.json",
+ "typecheck": "tsc && tsc -p src/node",
+ "lint": "eslint --cache --ext .ts src/**",
+ "format": "prettier --write --cache --parser typescript \"src/**/*.ts\"",
+ "generate-target": "tsx scripts/generateTarget.ts"
+ }
+}
\ No newline at end of file
diff --git a/frontend/node_modules/vite/types/customEvent.d.ts b/frontend/node_modules/vite/types/customEvent.d.ts
new file mode 100644
index 0000000..96145a6
--- /dev/null
+++ b/frontend/node_modules/vite/types/customEvent.d.ts
@@ -0,0 +1,45 @@
+import type {
+ ErrorPayload,
+ FullReloadPayload,
+ PrunePayload,
+ UpdatePayload,
+} from './hmrPayload'
+
+export interface CustomEventMap {
+ 'vite:beforeUpdate': UpdatePayload
+ 'vite:afterUpdate': UpdatePayload
+ 'vite:beforePrune': PrunePayload
+ 'vite:beforeFullReload': FullReloadPayload
+ 'vite:error': ErrorPayload
+ 'vite:invalidate': InvalidatePayload
+ 'vite:ws:connect': WebSocketConnectionPayload
+ 'vite:ws:disconnect': WebSocketConnectionPayload
+}
+
+export interface WebSocketConnectionPayload {
+ /**
+ * @experimental
+ * We expose this instance experimentally to see potential usage.
+ * This might be removed in the future if we didn't find reasonable use cases.
+ * If you find this useful, please open an issue with details so we can discuss and make it stable API.
+ */
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
+ webSocket: WebSocket
+}
+
+export interface InvalidatePayload {
+ path: string
+ message: string | undefined
+ firstInvalidatedBy: string
+}
+
+/**
+ * provides types for payloads of built-in Vite events
+ */
+export type InferCustomEventPayload<T extends string> =
+ T extends keyof CustomEventMap ? CustomEventMap[T] : any
+
+/**
+ * provides types for names of built-in Vite events
+ */
+export type CustomEventName = keyof CustomEventMap | (string & {})
diff --git a/frontend/node_modules/vite/types/hmrPayload.d.ts b/frontend/node_modules/vite/types/hmrPayload.d.ts
new file mode 100644
index 0000000..0cbd649
--- /dev/null
+++ b/frontend/node_modules/vite/types/hmrPayload.d.ts
@@ -0,0 +1,74 @@
+/** @deprecated use HotPayload */
+export type HMRPayload = HotPayload
+export type HotPayload =
+ | ConnectedPayload
+ | PingPayload
+ | UpdatePayload
+ | FullReloadPayload
+ | CustomPayload
+ | ErrorPayload
+ | PrunePayload
+
+export interface ConnectedPayload {
+ type: 'connected'
+}
+
+export interface PingPayload {
+ type: 'ping'
+}
+
+export interface UpdatePayload {
+ type: 'update'
+ updates: Update[]
+}
+
+export interface Update {
+ type: 'js-update' | 'css-update'
+ path: string
+ acceptedPath: string
+ timestamp: number
+ /** @internal */
+ explicitImportRequired?: boolean
+ /** @internal */
+ isWithinCircularImport?: boolean
+ /** @internal */
+ firstInvalidatedBy?: string
+ /** @internal */
+ invalidates?: string[]
+}
+
+export interface PrunePayload {
+ type: 'prune'
+ paths: string[]
+}
+
+export interface FullReloadPayload {
+ type: 'full-reload'
+ path?: string
+ /** @internal */
+ triggeredBy?: string
+}
+
+export interface CustomPayload {
+ type: 'custom'
+ event: string
+ data?: any
+}
+
+export interface ErrorPayload {
+ type: 'error'
+ err: {
+ [name: string]: any
+ message: string
+ stack: string
+ id?: string
+ frame?: string
+ plugin?: string
+ pluginCode?: string
+ loc?: {
+ file?: string
+ line: number
+ column: number
+ }
+ }
+}
diff --git a/frontend/node_modules/vite/types/hot.d.ts b/frontend/node_modules/vite/types/hot.d.ts
new file mode 100644
index 0000000..bc09e99
--- /dev/null
+++ b/frontend/node_modules/vite/types/hot.d.ts
@@ -0,0 +1,39 @@
+import type { CustomEventName, InferCustomEventPayload } from './customEvent'
+
+export type ModuleNamespace = Record<string, any> & {
+ [Symbol.toStringTag]: 'Module'
+}
+
+export interface ViteHotContext {
+ readonly data: any
+
+ accept(): void
+ accept(cb: (mod: ModuleNamespace | undefined) => void): void
+ accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
+ accept(
+ deps: readonly string[],
+ cb: (mods: Array<ModuleNamespace | undefined>) => void,
+ ): void
+
+ acceptExports(
+ exportNames: string | readonly string[],
+ cb?: (mod: ModuleNamespace | undefined) => void,
+ ): void
+
+ dispose(cb: (data: any) => void): void
+ prune(cb: (data: any) => void): void
+ invalidate(message?: string): void
+
+ on<T extends CustomEventName>(
+ event: T,
+ cb: (payload: InferCustomEventPayload<T>) => void,
+ ): void
+ off<T extends CustomEventName>(
+ event: T,
+ cb: (payload: InferCustomEventPayload<T>) => void,
+ ): void
+ send<T extends CustomEventName>(
+ event: T,
+ data?: InferCustomEventPayload<T>,
+ ): void
+}
diff --git a/frontend/node_modules/vite/types/import-meta.d.ts b/frontend/node_modules/vite/types/import-meta.d.ts
new file mode 100644
index 0000000..ee00ff5
--- /dev/null
+++ b/frontend/node_modules/vite/types/import-meta.d.ts
@@ -0,0 +1,5 @@
+/// <reference path="./importMeta.d.ts" />
+
+// https://github.com/microsoft/TypeScript/issues/45096
+// TypeScript has a bug that makes <reference types="vite/types/importMeta" />
+// not possible in userland. This file provides a workaround for now.
diff --git a/frontend/node_modules/vite/types/importGlob.d.ts b/frontend/node_modules/vite/types/importGlob.d.ts
new file mode 100644
index 0000000..dfd6f6f
--- /dev/null
+++ b/frontend/node_modules/vite/types/importGlob.d.ts
@@ -0,0 +1,89 @@
+export interface ImportGlobOptions<
+ Eager extends boolean,
+ AsType extends string,
+> {
+ /**
+ * Import type for the import url.
+ *
+ * @deprecated Use `query` instead, e.g. `as: 'url'` -> `query: '?url', import: 'default'`
+ */
+ as?: AsType
+ /**
+ * Import as static or dynamic
+ *
+ * @default false
+ */
+ eager?: Eager
+ /**
+ * Import only the specific named export. Set to `default` to import the default export.
+ */
+ import?: string
+ /**
+ * Custom queries
+ */
+ query?: string | Record<string, string | number | boolean>
+ /**
+ * Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance.
+ *
+ * @default false
+ */
+ exhaustive?: boolean
+ /**
+ * Base path to resolve relative paths.
+ */
+ base?: string
+}
+
+export type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>
+
+/**
+ * Declare Worker in case DOM is not added to the tsconfig lib causing
+ * Worker interface is not defined. For developers with DOM lib added,
+ * the Worker interface will be merged correctly.
+ */
+declare global {
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
+ interface Worker {}
+}
+
+export interface KnownAsTypeMap {
+ raw: string
+ url: string
+ worker: Worker
+}
+
+export interface ImportGlobFunction {
+ /**
+ * Import a list of files with a glob pattern.
+ *
+ * Overload 1: No generic provided, infer the type from `eager` and `as`
+ */
+ <
+ Eager extends boolean,
+ As extends string,
+ T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown,
+ >(
+ glob: string | string[],
+ options?: ImportGlobOptions<Eager, As>,
+ ): (Eager extends true ? true : false) extends true
+ ? Record<string, T>
+ : Record<string, () => Promise<T>>
+ /**
+ * Import a list of files with a glob pattern.
+ *
+ * Overload 2: Module generic provided, infer the type from `eager: false`
+ */
+ <M>(
+ glob: string | string[],
+ options?: ImportGlobOptions<false, string>,
+ ): Record<string, () => Promise<M>>
+ /**
+ * Import a list of files with a glob pattern.
+ *
+ * Overload 3: Module generic provided, infer the type from `eager: true`
+ */
+ <M>(
+ glob: string | string[],
+ options: ImportGlobOptions<true, string>,
+ ): Record<string, M>
+}
diff --git a/frontend/node_modules/vite/types/importMeta.d.ts b/frontend/node_modules/vite/types/importMeta.d.ts
new file mode 100644
index 0000000..01d9d39
--- /dev/null
+++ b/frontend/node_modules/vite/types/importMeta.d.ts
@@ -0,0 +1,30 @@
+// This file is an augmentation to the built-in ImportMeta interface
+// Thus cannot contain any top-level imports
+// <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
+
+// This is tested in `packages/vite/src/node/__tests_dts__/typeOptions.ts`
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- to allow extending by users
+interface ViteTypeOptions {
+ // strictImportMetaEnv: unknown
+}
+
+type ImportMetaEnvFallbackKey =
+ 'strictImportMetaEnv' extends keyof ViteTypeOptions ? never : string
+
+interface ImportMetaEnv extends Record<ImportMetaEnvFallbackKey, any> {
+ BASE_URL: string
+ MODE: string
+ DEV: boolean
+ PROD: boolean
+ SSR: boolean
+}
+
+interface ImportMeta {
+ url: string
+
+ readonly hot?: import('./hot').ViteHotContext
+
+ readonly env: ImportMetaEnv
+
+ glob: import('./importGlob').ImportGlobFunction
+}
diff --git a/frontend/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts b/frontend/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts
new file mode 100644
index 0000000..ca87ba8
--- /dev/null
+++ b/frontend/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts
@@ -0,0 +1,44 @@
+/* eslint-disable @typescript-eslint/ban-ts-comment */
+
+// @ts-ignore `sass` may not be installed
+import type DartSass from 'sass'
+// @ts-ignore `sass-embedded` may not be installed
+import type SassEmbedded from 'sass-embedded'
+// @ts-ignore `less` may not be installed
+import type Less from 'less'
+// @ts-ignore `stylus` may not be installed
+import type Stylus from 'stylus'
+
+/* eslint-enable @typescript-eslint/ban-ts-comment */
+
+// https://github.com/type-challenges/type-challenges/issues/29285
+type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false
+
+type DartSassStringOptionsAsync = DartSass.StringOptions<'async'>
+type SassEmbeddedStringOptionsAsync = SassEmbedded.StringOptions<'async'>
+type SassStringOptionsAsync =
+ IsAny<SassEmbeddedStringOptionsAsync> extends false
+ ? SassEmbeddedStringOptionsAsync
+ : DartSassStringOptionsAsync
+
+export type SassModernPreprocessBaseOptions = Omit<
+ SassStringOptionsAsync,
+ 'url' | 'sourceMap'
+>
+
+export type LessPreprocessorBaseOptions = Omit<
+ Less.Options,
+ 'sourceMap' | 'filename'
+>
+
+export type StylusPreprocessorBaseOptions = Omit<
+ Stylus.RenderOptions,
+ 'filename'
+> & { define?: Record<string, any> }
+
+declare global {
+ // LESS' types somewhat references this which doesn't make sense in Node,
+ // so we have to shim it
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
+ interface HTMLLinkElement {}
+}
diff --git a/frontend/node_modules/vite/types/internal/lightningcssOptions.d.ts b/frontend/node_modules/vite/types/internal/lightningcssOptions.d.ts
new file mode 100644
index 0000000..48d7114
--- /dev/null
+++ b/frontend/node_modules/vite/types/internal/lightningcssOptions.d.ts
@@ -0,0 +1,18 @@
+/* eslint-disable @typescript-eslint/ban-ts-comment */
+
+// @ts-ignore `lightningcss` may not be installed
+import type Lightningcss from 'lightningcss'
+
+/* eslint-enable @typescript-eslint/ban-ts-comment */
+
+export type LightningCSSOptions = Omit<
+ Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>,
+ | 'filename'
+ | 'resolver'
+ | 'minify'
+ | 'sourceMap'
+ | 'analyzeDependencies'
+ // properties not overridden by Vite, but does not make sense to set by end users
+ | 'inputSourceMap'
+ | 'projectRoot'
+>
diff --git a/frontend/node_modules/vite/types/internal/terserOptions.d.ts b/frontend/node_modules/vite/types/internal/terserOptions.d.ts
new file mode 100644
index 0000000..3d5e08f
--- /dev/null
+++ b/frontend/node_modules/vite/types/internal/terserOptions.d.ts
@@ -0,0 +1,11 @@
+/* eslint-disable @typescript-eslint/ban-ts-comment */
+
+// @ts-ignore `terser` may not be installed
+export type * as Terser from 'terser'
+// @ts-ignore `terser` may not be installed
+import type * as Terser from 'terser'
+
+/* eslint-enable @typescript-eslint/ban-ts-comment */
+
+export type TerserMinifyOptions = Terser.MinifyOptions
+export type TerserMinifyOutput = Terser.MinifyOutput
diff --git a/frontend/node_modules/vite/types/metadata.d.ts b/frontend/node_modules/vite/types/metadata.d.ts
new file mode 100644
index 0000000..8765291
--- /dev/null
+++ b/frontend/node_modules/vite/types/metadata.d.ts
@@ -0,0 +1,33 @@
+export interface ChunkMetadata {
+ importedAssets: Set<string>
+ importedCss: Set<string>
+}
+
+export interface CustomPluginOptionsVite {
+ /**
+ * If this is a CSS Rollup module, you can scope to its importer's exports
+ * so that if those exports are treeshaken away, the CSS module will also
+ * be treeshaken.
+ *
+ * The "importerId" must import the CSS Rollup module statically.
+ *
+ * Example config if the CSS id is `/src/App.vue?vue&type=style&lang.css`:
+ * ```js
+ * cssScopeTo: ['/src/App.vue', 'default']
+ * ```
+ */
+ cssScopeTo?: readonly [importerId: string, exportName: string | undefined]
+
+ /** @deprecated no-op since Vite 6.1 */
+ lang?: string
+}
+
+declare module 'rollup' {
+ export interface RenderedChunk {
+ viteMetadata?: ChunkMetadata
+ }
+
+ export interface CustomPluginOptions {
+ vite?: CustomPluginOptionsVite
+ }
+}
diff --git a/frontend/node_modules/vite/types/package.json b/frontend/node_modules/vite/types/package.json
new file mode 100644
index 0000000..00efc39
--- /dev/null
+++ b/frontend/node_modules/vite/types/package.json
@@ -0,0 +1,4 @@
+{
+ "//": "this file is here to make typescript happy when moduleResolution=node16+",
+ "version": "0.0.0"
+}
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
new file mode 100644
index 0000000..4579c58
--- /dev/null
+++ b/frontend/package-lock.json
@@ -0,0 +1,1061 @@
+{
+ "name": "frontend",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "frontend",
+ "version": "1.0.0",
+ "license": "ISC",
+ "devDependencies": {
+ "vite": "^7.1.12"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz",
+ "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz",
+ "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz",
+ "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz",
+ "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz",
+ "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz",
+ "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz",
+ "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz",
+ "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz",
+ "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz",
+ "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz",
+ "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz",
+ "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz",
+ "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz",
+ "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz",
+ "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz",
+ "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz",
+ "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz",
+ "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz",
+ "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz",
+ "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz",
+ "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz",
+ "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz",
+ "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz",
+ "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz",
+ "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz",
+ "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz",
+ "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz",
+ "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz",
+ "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz",
+ "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz",
+ "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz",
+ "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz",
+ "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz",
+ "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz",
+ "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz",
+ "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz",
+ "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz",
+ "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz",
+ "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz",
+ "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz",
+ "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz",
+ "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz",
+ "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz",
+ "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz",
+ "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz",
+ "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.11",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz",
+ "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.11",
+ "@esbuild/android-arm": "0.25.11",
+ "@esbuild/android-arm64": "0.25.11",
+ "@esbuild/android-x64": "0.25.11",
+ "@esbuild/darwin-arm64": "0.25.11",
+ "@esbuild/darwin-x64": "0.25.11",
+ "@esbuild/freebsd-arm64": "0.25.11",
+ "@esbuild/freebsd-x64": "0.25.11",
+ "@esbuild/linux-arm": "0.25.11",
+ "@esbuild/linux-arm64": "0.25.11",
+ "@esbuild/linux-ia32": "0.25.11",
+ "@esbuild/linux-loong64": "0.25.11",
+ "@esbuild/linux-mips64el": "0.25.11",
+ "@esbuild/linux-ppc64": "0.25.11",
+ "@esbuild/linux-riscv64": "0.25.11",
+ "@esbuild/linux-s390x": "0.25.11",
+ "@esbuild/linux-x64": "0.25.11",
+ "@esbuild/netbsd-arm64": "0.25.11",
+ "@esbuild/netbsd-x64": "0.25.11",
+ "@esbuild/openbsd-arm64": "0.25.11",
+ "@esbuild/openbsd-x64": "0.25.11",
+ "@esbuild/openharmony-arm64": "0.25.11",
+ "@esbuild/sunos-x64": "0.25.11",
+ "@esbuild/win32-arm64": "0.25.11",
+ "@esbuild/win32-ia32": "0.25.11",
+ "@esbuild/win32-x64": "0.25.11"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.6",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.52.5",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz",
+ "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.52.5",
+ "@rollup/rollup-android-arm64": "4.52.5",
+ "@rollup/rollup-darwin-arm64": "4.52.5",
+ "@rollup/rollup-darwin-x64": "4.52.5",
+ "@rollup/rollup-freebsd-arm64": "4.52.5",
+ "@rollup/rollup-freebsd-x64": "4.52.5",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.52.5",
+ "@rollup/rollup-linux-arm-musleabihf": "4.52.5",
+ "@rollup/rollup-linux-arm64-gnu": "4.52.5",
+ "@rollup/rollup-linux-arm64-musl": "4.52.5",
+ "@rollup/rollup-linux-loong64-gnu": "4.52.5",
+ "@rollup/rollup-linux-ppc64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-gnu": "4.52.5",
+ "@rollup/rollup-linux-riscv64-musl": "4.52.5",
+ "@rollup/rollup-linux-s390x-gnu": "4.52.5",
+ "@rollup/rollup-linux-x64-gnu": "4.52.5",
+ "@rollup/rollup-linux-x64-musl": "4.52.5",
+ "@rollup/rollup-openharmony-arm64": "4.52.5",
+ "@rollup/rollup-win32-arm64-msvc": "4.52.5",
+ "@rollup/rollup-win32-ia32-msvc": "4.52.5",
+ "@rollup/rollup-win32-x64-gnu": "4.52.5",
+ "@rollup/rollup-win32-x64-msvc": "4.52.5",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/vite": {
+ "version": "7.1.12",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz",
+ "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.25.0",
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3",
+ "postcss": "^8.5.6",
+ "rollup": "^4.43.0",
+ "tinyglobby": "^0.2.15"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "lightningcss": "^1.21.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/package.json b/frontend/package.json
new file mode 100644
index 0000000..498e3a6
--- /dev/null
+++ b/frontend/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "frontend",
+ "version": "1.0.0",
+ "description": "",
+ "main": "auth-new.js",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "vite preview",
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "type": "commonjs",
+ "devDependencies": {
+ "vite": "^7.1.12"
+ }
+}
diff --git a/frontend/auth-redirect.js b/frontend/public/auth-redirect.js
similarity index 100%
rename from frontend/auth-redirect.js
rename to frontend/public/auth-redirect.js
diff --git a/frontend/chart.js b/frontend/public/chart.js
similarity index 100%
rename from frontend/chart.js
rename to frontend/public/chart.js
diff --git a/frontend/file-utils.js b/frontend/public/file-utils.js
similarity index 100%
rename from frontend/file-utils.js
rename to frontend/public/file-utils.js
diff --git a/frontend/footer-content.js b/frontend/public/footer-content.js
similarity index 100%
rename from frontend/footer-content.js
rename to frontend/public/footer-content.js
diff --git a/frontend/footer-fix.js b/frontend/public/footer-fix.js
similarity index 100%
rename from frontend/footer-fix.js
rename to frontend/public/footer-fix.js
diff --git a/frontend/js/i18n-debug.js b/frontend/public/js/i18n-debug.js
similarity index 100%
rename from frontend/js/i18n-debug.js
rename to frontend/public/js/i18n-debug.js
diff --git a/frontend/js/i18n.js b/frontend/public/js/i18n.js
similarity index 100%
rename from frontend/js/i18n.js
rename to frontend/public/js/i18n.js
diff --git a/frontend/js/lib/i18next.min.js b/frontend/public/js/lib/i18next.min.js
similarity index 100%
rename from frontend/js/lib/i18next.min.js
rename to frontend/public/js/lib/i18next.min.js
diff --git a/frontend/js/lib/i18nextBrowserLanguageDetector.min.js b/frontend/public/js/lib/i18nextBrowserLanguageDetector.min.js
similarity index 100%
rename from frontend/js/lib/i18nextBrowserLanguageDetector.min.js
rename to frontend/public/js/lib/i18nextBrowserLanguageDetector.min.js
diff --git a/frontend/js/lib/i18nextHttpBackend.min.js b/frontend/public/js/lib/i18nextHttpBackend.min.js
similarity index 100%
rename from frontend/js/lib/i18nextHttpBackend.min.js
rename to frontend/public/js/lib/i18nextHttpBackend.min.js
diff --git a/frontend/mobile-menu.js b/frontend/public/mobile-menu.js
similarity index 100%
rename from frontend/mobile-menu.js
rename to frontend/public/mobile-menu.js
diff --git a/frontend/script.js b/frontend/public/script.js
similarity index 100%
rename from frontend/script.js
rename to frontend/public/script.js
diff --git a/frontend/settings-new.js b/frontend/public/settings-new.js
similarity index 100%
rename from frontend/settings-new.js
rename to frontend/public/settings-new.js
diff --git a/frontend/settings-styles.css b/frontend/public/settings-styles.css
similarity index 100%
rename from frontend/settings-styles.css
rename to frontend/public/settings-styles.css
diff --git a/frontend/sw.js b/frontend/public/sw.js
similarity index 100%
rename from frontend/sw.js
rename to frontend/public/sw.js
diff --git a/frontend/theme-loader.js b/frontend/public/theme-loader.js
similarity index 100%
rename from frontend/theme-loader.js
rename to frontend/public/theme-loader.js
diff --git a/frontend/version-checker.js b/frontend/public/version-checker.js
similarity index 98%
rename from frontend/version-checker.js
rename to frontend/public/version-checker.js
index 3be2504..b1e5b78 100644
--- a/frontend/version-checker.js
+++ b/frontend/public/version-checker.js
@@ -1,6 +1,6 @@
// Version checker for Warracker
document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '1.0.2'; // Current version of the application
+ const currentVersion = '1.0.3'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');
const versionDisplay = document.getElementById('versionDisplay');
diff --git a/frontend/registration-status.js b/frontend/registration-status.js
deleted file mode 100644
index 388e94d..0000000
--- a/frontend/registration-status.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Registration Status Checker
- *
- * This script checks if registration is enabled on the site and hides registration buttons/links if disabled.
- * Include this script in all pages that have registration links or buttons.
- */
-
-document.addEventListener('DOMContentLoaded', function() {
- // Only check if user is not logged in
- if (!localStorage.getItem('auth_token')) {
- checkRegistrationStatus();
- }
-});
-
-/**
- * Check if registration is enabled and hide registration elements if disabled
- */
-function checkRegistrationStatus() {
- fetch('/api/auth/registration-status')
- .then(response => response.json())
- .then(data => {
- if (!data.enabled) {
- // Hide all registration links and buttons
- hideRegistrationElements();
- }
- })
- .catch(error => {
- console.error('Error checking registration status:', error);
- });
-}
-
-/**
- * Hide all registration-related elements on the page
- */
-function hideRegistrationElements() {
- // Hide elements with specific classes
- const elements = [
- '.register-btn', // Main navigation register button
- 'a[href="register.html"]', // Links to register page
- 'a[href="./register.html"]', // Links to register page (relative)
- 'a[href="/register.html"]' // Links to register page (root relative)
- ];
-
- // Apply to all matching elements
- elements.forEach(selector => {
- document.querySelectorAll(selector).forEach(element => {
- element.style.display = 'none';
- });
- });
-
- // Special case for auth container in the header
- const authContainer = document.getElementById('authContainer');
- if (authContainer) {
- // Check if it has multiple children and at least one is hidden
- const children = authContainer.children;
- let visibleCount = 0;
-
- for (let i = 0; i < children.length; i++) {
- if (children[i].style.display !== 'none') {
- visibleCount++;
- }
- }
-
- // If there's only one visible child, adjust the container styling
- if (visibleCount === 1) {
- authContainer.style.justifyContent = 'flex-end';
- }
- }
-
- // Special case for auth links in login/register pages
- const authLinks = document.querySelector('.auth-links');
- if (authLinks) {
- const links = authLinks.querySelectorAll('a');
- links.forEach(link => {
- if (link.textContent === 'Create Account' ||
- link.href.includes('register.html')) {
- link.style.display = 'none';
- }
- });
-
- // Add a message about registration being disabled if we're on the login page
- if (window.location.pathname.includes('login.html')) {
- const infoMessage = document.createElement('div');
- infoMessage.className = 'registration-info';
- infoMessage.innerHTML = '<small>New account registration is currently disabled</small>';
- infoMessage.style.color = 'var(--text-muted)';
- infoMessage.style.fontSize = '0.8em';
- infoMessage.style.marginTop = '10px';
- authLinks.appendChild(infoMessage);
- }
- }
-}
\ No newline at end of file
diff --git a/frontend/about.html b/frontend/src/about.html
similarity index 94%
rename from frontend/about.html
rename to frontend/src/about.html
index a7c52a8..3673861 100644
--- a/frontend/about.html
+++ b/frontend/src/about.html
@@ -7,31 +7,33 @@
<title data-i18n="about.title">About - Warracker</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
<!-- Stylesheets -->
- <link rel="stylesheet" href="style.css?v=20250119004"> <!-- Main stylesheet -->
- <link rel="stylesheet" href="styles.css?v=20250119001"> <!-- Additional styles -->
+ <link rel="stylesheet" href="/style.css?v=20250119004"> <!-- Main stylesheet -->
+ <link rel="stylesheet" href="/styles.css?v=20250119001"> <!-- Additional styles -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"> <!-- Font Awesome -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001"> <!-- Header specific styles -->
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001"> <!-- Header specific styles -->
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- Scripts loaded in head -->
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
- <script src="include-auth-new.js?v=20250119001"></script> <!-- Handles auth state display -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script> <!-- Fixes auth button display timing -->
- <script src="script.js?v=20250119001" defer></script>
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
+
+
+ <script src="/script.js?v=20250119001" defer></script>
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n initialization script -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<style>
.about-hero {
@@ -333,7 +335,7 @@
<!-- Hero Section -->
<div class="about-hero">
<h1><i class="fas fa-shield-alt"></i> Warracker</h1>
- <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.2</div>
+ <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.3</div>
<p class="description" data-i18n="about.description">
A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.
</p>
@@ -410,16 +412,16 @@
</div>
<!-- Scripts loaded at the end of body -->
- <script src="auth.js?v=20250119001"></script>
+
<!-- Version Checker -->
- <script src="version-checker.js?v=20251030001" defer></script> <!-- Version checker script -->
+ <script src="/version-checker.js?v=20251030001" defer></script> <!-- Version checker script -->
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
@@ -434,7 +436,7 @@
// Update version display dynamically
const versionDisplay = document.getElementById('versionDisplay');
if (versionDisplay && window.i18next) {
- const currentVersion = '1.0.2'; // This should match version-checker.js
+ const currentVersion = '1.0.3'; // This should match version-checker.js
versionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;
}
diff --git a/frontend/auth-redirect.html b/frontend/src/auth-redirect.html
similarity index 92%
rename from frontend/auth-redirect.html
rename to frontend/src/auth-redirect.html
index a52b3c8..61fc5bd 100644
--- a/frontend/auth-redirect.html
+++ b/frontend/src/auth-redirect.html
@@ -4,8 +4,10 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authenticating...</title>
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script>
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<style>
body {
display: flex;
@@ -159,20 +161,20 @@
</script>
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n Configuration -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
- <script src="auth-redirect.js?v=20250119001"></script>
+ <script src="/auth-redirect.js?v=20250119001"></script>
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/src/auth-redirect.js b/frontend/src/auth-redirect.js
new file mode 100644
index 0000000..da9fd43
--- /dev/null
+++ b/frontend/src/auth-redirect.js
@@ -0,0 +1,56 @@
+/**
+ * Authentication Redirect Script
+ *
+ * This script handles redirects based on authentication status:
+ * - Redirects unauthenticated users from protected pages to login
+ * - Redirects authenticated users from login/register to index
+ *
+ * Usage:
+ * Include this script at the very beginning of your HTML with:
+ * <script src="auth-redirect.js" data-protected="true|false"></script>
+ *
+ * Set data-protected="true" for pages that require authentication (index, status, settings)
+ * Set data-protected="false" for auth pages (login, register)
+ */
+
+(function() {
+ // Wait for DOM to be ready enough to execute script
+ const executeRedirect = () => {
+ try {
+ // Get current script element
+ const currentScript = document.currentScript;
+
+ // Check if isProtected attribute is set
+ const isProtected = currentScript.getAttribute('data-protected') === 'true';
+
+ // Check authentication status
+ const isAuthenticated = !!localStorage.getItem('auth_token');
+ const currentPath = window.location.pathname;
+
+ console.log('Auth redirect check - Protected page:', isProtected);
+ console.log('Auth redirect check - Is authenticated:', isAuthenticated);
+ console.log('Auth redirect check - Current path:', currentPath);
+
+ // Handle protected pages (index, status, settings)
+ if (isProtected && !isAuthenticated) {
+ console.log('Access to protected page without authentication, redirecting to login');
+ window.location.href = 'login.html';
+ return;
+ }
+
+ // Handle auth pages (login, register)
+ if (!isProtected && isAuthenticated) {
+ console.log('Already authenticated, redirecting from auth page to index');
+ window.location.href = 'index.html';
+ return;
+ }
+
+ console.log('No redirect needed');
+ } catch (error) {
+ console.error('Error in auth-redirect.js:', error);
+ }
+ };
+
+ // Execute immediately
+ executeRedirect();
+})();
\ No newline at end of file
diff --git a/frontend/src/chart.js b/frontend/src/chart.js
new file mode 100644
index 0000000..47cbcd9
--- /dev/null
+++ b/frontend/src/chart.js
@@ -0,0 +1,14 @@
+/*!
+ * Chart.js v4.4.9
+ * 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 Zo},get Decimation(){return ta},get Filler(){return xa},get Legend(){return va},get SubTitle(){return Sa},get Title(){return wa},get Tooltip(){return Wa}});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;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,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)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((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;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function Z(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function J(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return J(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>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 n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{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=J(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=J(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<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>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 Zt{constructor(t){if(t instanceof Zt)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 Zt(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 Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(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;e<s;++e){const s=i[e];t=t[s]||(t[s]=Object.create(null))}return t}function ce(t,e,i){return"string"==typeof e?x(he(t,e),i):x(he(t,""),e)}class de{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=t=>t.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=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(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;h<l;h++)if(u=i[h],null==u||n(u)){if(n(u))for(c=0,d=u.length;c<d;c++)f=u[c],null==f||n(f)||(r=Ce(t,o,a,r,f))}else r=Ce(t,o,a,r,u);t.restore();const g=a.length/2;if(g>i.length){for(h=0;h<g;h++)delete o[a[h]];a.splice(0,g)}return r}function Ae(t,e,i){const s=t.currentDevicePixelRatio,n=0!==i?Math.max(i/2,.5):0;return Math.round((e-n)*s)/s+n}function Te(t,e){(e||t)&&((e=e||t.getContext("2d")).save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function Le(t,e,i,s){Ee(t,e,i,s,null)}function Ee(t,e,i,s,n){let o,a,r,l,h,c,d,u;const f=e.pointStyle,g=e.rotation,p=e.radius;let m=(g||0)*L;if(f&&"object"==typeof f&&(o=f.toString(),"[object HTMLImageElement]"===o||"[object HTMLCanvasElement]"===o))return t.save(),t.translate(i,s),t.rotate(m),t.drawImage(f,-f.width/2,-f.height/2,f.width,f.height),void t.restore();if(!(isNaN(p)||p<=0)){switch(t.beginPath(),f){default:n?t.ellipse(i,s,n/2,p,0,0,O):t.arc(i,s,p,0,O),t.closePath();break;case"triangle":c=n?n/2:p,t.moveTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),t.closePath();break;case"rectRounded":h=.516*p,l=p-h,a=Math.cos(m+R)*l,d=Math.cos(m+R)*(n?n/2-h:l),r=Math.sin(m+R)*l,u=Math.sin(m+R)*(n?n/2-h:l),t.arc(i-d,s-r,h,m-C,m-E),t.arc(i+u,s-a,h,m-E,m),t.arc(i+d,s+r,h,m,m+E),t.arc(i-u,s+a,h,m+E,m+C),t.closePath();break;case"rect":if(!g){l=Math.SQRT1_2*p,c=n?n/2:l,t.rect(i-c,s-l,2*c,2*l);break}m+=R;case"rectRot":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+u,s-a),t.lineTo(i+d,s+r),t.lineTo(i-u,s+a),t.closePath();break;case"crossRot":m+=R;case"cross":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"star":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a),m+=R,d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"line":a=n?n/2:Math.cos(m)*p,r=Math.sin(m)*p,t.moveTo(i-a,s-r),t.lineTo(i+a,s+r);break;case"dash":t.moveTo(i,s),t.lineTo(i+Math.cos(m)*(n?n/2:p),s+Math.sin(m)*p);break;case!1:t.closePath()}t.fill(),e.borderWidth>0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.x<e.right+i&&t.y>e.top-i&&t.y<e.bottom+i}function Ie(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function ze(t){t.restore()}function Fe(t,e,i,s,n){if(!e)return t.lineTo(i.x,i.y);if("middle"===n){const s=(e.x+i.x)/2;t.lineTo(s,e.y),t.lineTo(s,i.y)}else"after"===n!=!!s?t.lineTo(e.x,i.y):t.lineTo(i.x,e.y);t.lineTo(i.x,i.y)}function Ve(t,e,i,s){if(!e)return t.lineTo(i.x,i.y);t.bezierCurveTo(s?e.cp1x:e.cp2x,s?e.cp1y:e.cp2y,s?i.cp2x:i.cp1x,s?i.cp2y:i.cp1y,i.x,i.y)}function Be(t,e,i,s,n){if(n.strikethrough||n.underline){const o=t.measureText(s),a=e-o.actualBoundingBoxLeft,r=e+o.actualBoundingBoxRight,l=i-o.actualBoundingBoxAscent,h=i+o.actualBoundingBoxDescent,c=n.strikethrough?(l+h)/2:h;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=n.decorationWidth||2,t.moveTo(a,c),t.lineTo(r,c),t.stroke()}}function We(t,e){const i=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=i}function Ne(t,e,i,o,a,r={}){const l=n(e)?e:[e],h=r.strokeWidth>0&&""!==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;c<l.length;++c)d=l[c],r.backdrop&&We(t,r.backdrop),h&&(r.strokeColor&&(t.strokeStyle=r.strokeColor),s(r.strokeWidth)||(t.lineWidth=r.strokeWidth),t.strokeText(d,i,o,r.maxWidth)),t.fillText(d,i,o,r.maxWidth),Be(t,i,o,d,r),o+=Number(a.lineHeight);t.restore()}function He(t,e){const{x:i,y:s,w:n,h:o,radius:a}=e;t.arc(i+a.topLeft,s+a.topLeft,a.topLeft,1.5*C,C,!0),t.lineTo(i,s+o-a.bottomLeft),t.arc(i+a.bottomLeft,s+o-a.bottomLeft,a.bottomLeft,C,E,!0),t.lineTo(i+n-a.bottomRight,s+o),t.arc(i+n-a.bottomRight,s+o-a.bottomRight,a.bottomRight,E,0,!0),t.lineTo(i+n,s+a.topRight),t.arc(i+n-a.topRight,s+a.topRight,a.topRight,0,-E,!0),t.lineTo(i+a.topLeft,s)}function je(t,e=[""],i,s,n=(()=>t[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)?Je(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=Je(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=Je(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 Ze(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 Je(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=Ze(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;r<l;++r)h=r+i,c=e[h],a[r]={r:n.parse(M(c,o),h)};return a}const si=Number.EPSILON||1e-14,ni=(t,e)=>e<t.length&&!t[e].skip&&t[e],oi=t=>"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<s;++a)if(r=l,l=h,h=ni(t,a+1),l){if(h){const t=h[e]-l[e];n[a]=0!==t?(h[i]-l[i])/t:0}o[a]=r?h?F(n[a-1])!==F(n[a])?0:(n[a-1]+n[a])/2:n[a-1]:n[a]}!function(t,e,i){const s=t.length;let n,o,a,r,l,h=ni(t,0);for(let c=0;c<s-1;++c)l=h,h=ni(t,c+1),l&&h&&(V(e[c],0,si)?i[c]=i[c+1]=0:(n=i[c]/e[c],o=i[c+1]/e[c],r=Math.pow(n,2)+Math.pow(o,2),r<=9||(a=3/Math.sqrt(r),i[c]=n*a*e[c],i[c+1]=o*a*e[c])))}(t,n,o),function(t,e,i="x"){const s=oi(i),n=t.length;let o,a,r,l=ni(t,0);for(let h=0;h<n;++h){if(a=r,r=l,l=ni(t,h+1),!r)continue;const n=r[i],c=r[s];a&&(o=(n-a[i])/3,r[`cp1${i}`]=n-o,r[`cp1${s}`]=c-o*e[h]),l&&(o=(l[i]-n)/3,r[`cp2${i}`]=n+o,r[`cp2${s}`]=c+o*e[h])}}(t,o,e)}function li(t,e,i){return Math.max(Math.min(t,i),e)}function hi(t,e,i,s,n){let o,a,r,l;if(e.spanGaps&&(t=t.filter((t=>!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o<a;++o)r=t[o],l=ai(i,r,t[Math.min(o+1,a-(s?0:1))%a],e.tension),r.cp1x=l.previous.x,r.cp1y=l.previous.y,r.cp2x=l.next.x,r.cp2y=l.next.y,i=r}e.capBezierPoints&&function(t,e){let i,s,n,o,a,r=Re(t[0],e);for(i=0,s=t.length;i<s;++i)a=o,o=r,r=i<s-1&&Re(t[i+1],e),o&&(n=t[i],a&&(n.cp1x=li(n.cp1x,e.left,e.right),n.cp1y=li(n.cp1y,e.top,e.bottom)),r&&(n.cp2x=li(n.cp2x,e.left,e.right),n.cp2y=li(n.cp2y,e.top,e.bottom)))}(t,i)}const ci=t=>0===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;o<a;++o)if(r=t[o],void 0!==r&&(void 0!==e&&"function"==typeof r&&(r=r(e),l=!1),void 0!==i&&n(r)&&(r=r[i%r.length],l=!1),void 0!==r))return s&&!l&&(s.cacheable=!1),r}function Di(t,e,i){const{min:s,max:n}=t,o=c(e,(n-s)/2),a=(t,e)=>i&&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:Z,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;h<c&&a(r(e[d%l][s]),n,o);++h)d--,u--;d%=l,u%=l}return u<d&&(u+=l),{start:d,end:u,loop:f,style:t.style}}(t,e,i),g=[];let p,m,x,b=!1,_=null;const y=()=>b||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;n<s.length;n++){const o=Ri(s[n],t.points,e);o.length&&i.push(...o)}return i}function zi(t,e){const i=t.points,s=t.options.spanGaps,n=i.length;if(!n)return[];const o=!!t._loop,{start:a,end:r}=function(t,e,i,s){let n=0,o=e-1;if(i&&!s)for(;n<e&&!t[n].skip;)n++;for(;n<e&&t[n].skip;)n++;for(n%=e,i&&(o+=n);o>n&&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<a?r+n:r,!!t._fullLoop&&0===a&&r===n-1),i,e)}function Fi(t,e,i,s){return s&&s.setContext&&i?function(t,e,i,s){const n=t._chart.getContext(),o=Vi(t.options),{_datasetIndex:a,options:{spanGaps:r}}=t,l=i.length,h=[];let c=o,d=e[0].start,u=d;function f(t,e,s,n){const o=r?-1:1;if(t!==e){for(t+=l;i[t%l].skip;)t-=o;for(;i[e%l].skip;)e+=o;t%l!=e%l&&(h.push({start:t%l,end:e%l,loop:s,style:n}),c=n,d=e%l)}}for(const t of e){d=r?d:t.start;let e,o=i[d%l];for(u=d+1;u<=t.end;u++){const r=i[u%l];e=Vi(s.setContext(Ci(n,{type:"segment",p0:o,p1:r,p0DataIndex:(u-1)%l,p1DataIndex:u%l,datasetIndex:a}))),Bi(e,c)&&f(d,u-1,t.loop,c),o=r,c=e}d<u-1&&f(d,u-1,t.loop,c)}return h}(t,e,i,s):e}function Vi(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function Bi(t,e){if(!e)return!1;const i=[],s=function(t,e){return Jt(e)?(i.includes(e)||i.push(e),i.indexOf(e)):e};return JSON.stringify(t,s)!==JSON.stringify(e,s)}function Wi(t,e,i){return t.options.clip?t[i]:e[i]}function Ni(t,e){const i=e._clip;if(i.disabled)return!1;const s=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:Wi(i,e,"left"),right:Wi(i,e,"right"),top:Wi(s,e,"top"),bottom:Wi(s,e,"bottom")}:e}(e,t.chartArea);return{left:!1===i.left?0:s.left-(!0===i.left?0:i.left),right:!1===i.right?t.width:s.right+(!0===i.right?0:i.right),top:!1===i.top?0:s.top-(!0===i.top?0:i.top),bottom:!1===i.bottom?t.height:s.bottom+(!0===i.bottom?0:i.bottom)}}var Hi=Object.freeze({__proto__:null,HALF_PI:E,INFINITY:T,PI:C,PITAU:A,QUARTER_PI:R,RAD_PER_DEG:L,TAU:O,TWO_THIRDS_PI:I,_addGrace:Di,_alignPixel:Ae,_alignStartEnd:ft,_angleBetween:Z,_angleDiff:K,_arrayUnique:lt,_attachContext:$e,_bezierCurveTo:Ve,_bezierInterpolation:mi,_boundSegment:Ri,_boundSegments:Ii,_capitalize:w,_computeSegments:zi,_createResolver:je,_decimalPlaces:U,_deprecated:function(t,e,i,s){void 0!==e&&console.warn(t+': "'+i+'" is deprecated. Please use "'+s+'" instead')},_descriptors:Ye,_elementsEqual:f,_factorize:W,_filterBetween:nt,_getParentNode:ge,_getStartAndCountOfVisiblePoints:pt,_int16Range:Q,_isBetween:tt,_isClickEvent:D,_isDomSupported:fe,_isPointInArea:Re,_limitValue:J,_longestText:Oe,_lookup:et,_lookupByKey:it,_measureText:Ce,_merger:m,_mergerIf:_,_normalizeAngle:G,_parseObjectDataRadialScale:ii,_pointInLine:gi,_readValueToProps:vi,_rlookupByKey:st,_scaleRangesChanged:mt,_setMinAndMaxByKey:j,_splitKey:v,_steppedInterpolation:pi,_steppedLineTo:Fe,_textX:gt,_toLeftRightCenter:ut,_updateBezierControlPoints:hi,addRoundedRectPath:He,almostEquals:V,almostWhole:H,callback:d,clearCanvas:Te,clipArea:Ie,clone:g,color:Qt,createContext:Ci,debounce:dt,defined:k,distanceBetweenPoints:q,drawPoint:Le,drawPointLegend:Ee,each:u,easingEffects:fi,finiteOrDefault:r,fontString:function(t,e,i){return e+" "+t+"px "+i},formatNumber:ne,getAngleFromPoint:X,getDatasetClipArea:Ni,getHoverColor:te,getMaximumSize:we,getRelativePosition:ve,getRtlAdapter:Oi,getStyle:xe,isArray:n,isFinite:a,isFunction:S,isNullOrUndef:s,isNumber:N,isObject:o,isPatternOrGradient:Jt,listenArrayEvents:at,log10:z,merge:x,mergeIf:b,niceNum:B,noop:e,overrideTextDirection:Ai,readUsedSize:Pe,renderText:Ne,requestAnimFrame:ht,resolve:Pi,resolveObjectKey:M,restoreTextDirection:Ti,retinaScale:ke,setsEqual:P,sign:F,splineCurve:ai,splineCurveMonotone:ri,supportsEventListenerOptions:Se,throttled:ct,toDegrees:Y,toDimension:c,toFont:Si,toFontString:De,toLineHeight:_i,toPadding:ki,toPercentage:h,toRadians:$,toTRBL:Mi,toTRBLCorners:wi,uid:i,unclipArea:ze,unlistenArrayEvents:rt,valueOrDefault:l});function ji(t,e,i,n){const{controller:o,data:a,_sorted:r}=t,l=o._cachedMeta.iScale,h=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(l&&e===l.axis&&"r"!==e&&r&&a.length){const r=l._reversePixels?st:it;if(!n){const n=r(a,e,i);if(h){const{vScale:e}=o._cachedMeta,{_parsed:i}=t,a=i.slice(0,n.lo+1).reverse().findIndex((t=>!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<i;++t){const{index:i,data:r}=o[t],{lo:l,hi:h}=ji(o[t],e,a,n);for(let t=l;t<=h;++t){const e=r[t];e.skip||s(e,i,t)}}}function Yi(t,e,i,s,n){const o=[];if(!n&&!t.isPointInArea(e))return o;return $i(t,i,e,(function(i,a,r){(n||Re(i,t.chartArea,0))&&i.inRange(e.x,e.y,s)&&o.push({element:i,datasetIndex:a,index:r})}),!0),o}function Ui(t,e,i,s,n,o){let a=[];const r=function(t){const e=-1!==t.indexOf("x"),i=-1!==t.indexOf("y");return function(t,s){const n=e?Math.abs(t.x-s.x):0,o=i?Math.abs(t.y-s.y):0;return Math.sqrt(Math.pow(n,2)+Math.pow(o,2))}}(i);let l=Number.POSITIVE_INFINITY;return $i(t,i,e,(function(i,h,c){const d=i.inRange(e.x,e.y,n);if(s&&!d)return;const u=i.getCenterPoint(n);if(!(!!o||t.isPointInArea(u))&&!d)return;const f=r(e,u);f<l?(a=[{element:i,datasetIndex:h,index:c}],l=f):f===l&&a.push({element:i,datasetIndex:h,index:c})})),a}function Xi(t,e,i,s,n,o){return o||t.isPointInArea(e)?"r"!==i||s?Ui(t,e,i,s,n,o):function(t,e,i,s){let n=[];return $i(t,i,e,(function(t,i,o){const{startAngle:a,endAngle:r}=t.getProps(["startAngle","endAngle"],s),{angle:l}=X(t,{x:e.x,y:e.y});Z(l,a,r)&&n.push({element:t,datasetIndex:i,index:o})})),n}(t,e,i,n):[]}function qi(t,e,i,s,n){const o=[],a="x"===i?"inXRange":"inYRange";let r=!1;return $i(t,i,e,((t,s,l)=>{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;t<i.length;++t)r.push({element:i[t],datasetIndex:e,index:t})}return r},point:(t,e,i,s)=>Yi(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 Zi(t,e){return t.filter((t=>t.pos===e))}function Ji(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<a;++o){r=t[o];const{fullSize:a}=r.box,l=i[r.stack],h=l&&r.stackWeight/l.weight;r.horizontal?(r.width=h?h*s:a&&e.availableWidth,r.height=n):(r.width=s,r.height=h?h*n:a&&e.availableHeight)}return i}function es(t,e,i,s){return Math.max(t[i],e[i])+Math.max(t[s],e[s])}function is(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function ss(t,e,i,s){const{pos:n,box:a}=i,r=t.maxPadding;if(!o(n)){i.size&&(t[n]-=i.size);const e=s[i.stack]||{size:0,count:1};e.size=Math.max(e.size,i.horizontal?a.height:a.width),i.size=e.size/e.count,t[n]+=i.size}a.getPadding&&is(r,a.getPadding());const l=Math.max(0,e.outerWidth-es(r,t,"left","right")),h=Math.max(0,e.outerHeight-es(r,t,"top","bottom")),c=l!==t.w,d=h!==t.h;return t.w=l,t.h=h,i.horizontal?{same:c,other:d}:{same:d,other:c}}function ns(t,e){const i=e.maxPadding;function s(t){const s={left:0,top:0,right:0,bottom:0};return t.forEach((t=>{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;o<a;++o){r=t[o],l=r.box,l.update(r.width||e.w,r.height||e.h,ns(r.horizontal,e));const{same:a,other:d}=ss(e,i,r,s);h|=a&&n.length,c=c||d,l.fullSize||n.push(r)}return h&&os(n,e,i,s)||c}function as(t,e,i,s,n){t.top=i,t.left=e,t.right=e+s,t.bottom=i+n,t.width=s,t.height=n}function rs(t,e,i,s){const n=i.padding;let{x:o,y:a}=e;for(const r of t){const t=r.box,l=s[r.stack]||{count:1,placed:0,weight:1},h=r.stackWeight/l.weight||1;if(r.horizontal){const s=e.w*h,o=l.size||t.height;k(l.start)&&(a=l.start),t.fullSize?as(t,n.left,a,i.outerWidth-n.right-n.left,o):as(t,e.left+l.placed,a,s,o),l.start=a,l.placed+=s,a=t.bottom}else{const s=e.h*h,a=l.size||t.width;k(l.start)&&(o=l.start),t.fullSize?as(t,o,n.top,a,i.outerHeight-n.bottom-n.top):as(t,o,e.top+l.placed,a,s),l.start=o,l.placed+=s,o=t.right}}e.x=o,e.y=a}var ls={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){const i=t.boxes?t.boxes.indexOf(e):-1;-1!==i&&t.boxes.splice(i,1)},configure(t,e,i){e.fullSize=i.fullSize,e.position=i.position,e.weight=i.weight},update(t,e,i,s){if(!t)return;const n=ki(t.options.layout.padding),o=Math.max(e-n.width,0),a=Math.max(i-n.height,0),r=function(t){const e=function(t){const e=[];let i,s,n,o,a,r;for(i=0,s=(t||[]).length;i<s;++i)n=t[i],({position:o,options:{stack:a,stackWeight:r=1}}=n),e.push({index:i,box:n,pos:o,horizontal:n.isHorizontal(),weight:n.weight,stack:a&&o+a,stackWeight:r});return e}(t),i=Qi(e.filter((t=>t.box.fullSize)),!0),s=Qi(Zi(e,"left"),!0),n=Qi(Zi(e,"right")),o=Qi(Zi(e,"top"),!0),a=Qi(Zi(e,"bottom")),r=Ji(e,"x"),l=Ji(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Zi(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<n.clientWidth&&i()}),window),a=new ResizeObserver((t=>{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||e<i),!this._active)return this._target[s]=a,void this._notify(!0);e<0?this._target[s]=n:(r=e/i%2,r=o&&r>1?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<i.length;t++)i[t][e]()}}class Ts{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!o(t))return;const e=Object.keys(ue.animation),i=this._properties;Object.getOwnPropertyNames(t).forEach((s=>{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<s.length;e++){const n=t[s[e]];n&&n.active()&&i.push(n.wait())}return Promise.all(i)}(t.options.$animations,i).then((()=>{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;n<o;++n)i.push(s[n].index);return i}function Rs(t,e,i,s={}){const n=t.keys,o="single"===s.mode;let r,l,h,c;if(null===e)return;let d=!1;for(r=0,l=n.length;r<l;++r){if(h=+n[r],h===i){if(d=!0,s.all)continue;break}c=t.values[h],a(c)&&(o||0===e||F(e)===F(c))&&(e+=c)}return d||s.all?e:0}function Is(t,e){const i=t&&t.options.stacked;return i||void 0===i&&void 0!==e.stack}function zs(t,e,i){const s=t[e]||(t[e]={});return s[i]||(s[i]={})}function Fs(t,e,i,s){for(const n of e.getMatchingVisibleMetas(s).reverse()){const e=t[n.index];if(i&&e>0||!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;t<d;++t){const i=e[t],{[l]:o,[h]:d}=i;u=(i._stacks||(i._stacks={}))[h]=zs(n,c,o),u[r]=d,u._top=Fs(u,a,!0,s.type),u._bottom=Fs(u,a,!1,s.type);(u._visualValues||(u._visualValues={}))[r]=d}}function Bs(t,e){const i=t.scales;return Object.keys(i).filter((t=>i[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;l<h;++l)c=a[l],r[l]={[n]:c,[o]:t[c]};return r}(e,t)}else if(i!==e){if(i){rt(i,this);const t=this._cachedMeta;Ws(t),t._parsed=[]}e&&Object.isExtensible(e)&&at(e,this),this._syncList=[],this._data=e}}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const e=this._cachedMeta,i=this.getDataset();let s=!1;this._dataCheck();const n=e._stacked;e._stacked=Is(e.vScale,e),e.stack!==i.stack&&(s=!0,Ws(e),e.stack=i.stack),this._resyncElements(t),(s||n!==e._stacked)&&(Vs(this,e._parsed),e._stacked=Is(e.vScale,e))}configure(){const t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){const{_cachedMeta:i,_data:s}=this,{iScale:a,_stacked:r}=i,l=a.axis;let h,c,d,u=0===t&&e===s.length||i._sorted,f=t>0&&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]<f[l];for(h=0;h<e;++h)i._parsed[h+t]=c=d[h],u&&(a()&&(u=!1),f=c);i._sorted=u}r&&Vs(this,d)}parsePrimitiveData(t,e,i,s){const{iScale:n,vScale:o}=t,a=n.axis,r=o.axis,l=n.getLabels(),h=n===o,c=new Array(s);let d,u,f;for(d=0,u=s;d<u;++d)f=d+i,c[d]={[a]:h||n.parse(l[f],f),[r]:o.parse(e[f],f)};return c}parseArrayData(t,e,i,s){const{xScale:n,yScale:o}=t,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={x:n.parse(c[0],h),y:o.parse(c[1],h)};return a}parseObjectData(t,e,i,s){const{xScale:n,yScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l=new Array(s);let h,c,d,u;for(h=0,c=s;h<c;++h)d=h+i,u=e[d],l[h]={x:n.parse(M(u,a),d),y:o.parse(M(u,r),d)};return l}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,e,i){const s=this.chart,n=this._cachedMeta,o=e[t.axis];return Rs({keys:Es(s,!0),values:e._stacks[t.axis]._visualValues},o,n.index,{mode:i})}updateRangeFromParsed(t,e,i,s){const n=i[e.axis];let o=null===n?NaN:n;const a=s&&i._stacks[e.axis];s&&a&&(s.values=a,o=Rs(s,n,this._cachedMeta.index)),t.min=Math.min(t.min,o),t.max=Math.max(t.max,o)}getMinMax(t,e){const i=this._cachedMeta,s=i._parsed,n=i._sorted&&t===i.iScale,o=s.length,r=this._getOtherScale(t),l=((t,e,i)=>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<e}for(u=0;u<o&&(g()||(this.updateRangeFromParsed(h,t,f,l),!n));++u);if(n)for(u=o-1;u>=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<n;++s)o=e[s][t.axis],a(o)&&i.push(o);return i}getMaxOverflow(){return!1}getLabelAndValue(t){const e=this._cachedMeta,i=e.iScale,s=e.vScale,n=this.getParsed(t);return{label:i?""+i.getLabelForValue(n[i.axis]):"",value:s?""+s.getLabelForValue(n[s.axis]):""}}_update(t){const e=this._cachedMeta;this.update(t||"default"),e._clip=function(t){let e,i,s,n;return o(t)?(e=t.top,i=t.right,s=t.bottom,n=t.left):e=i=s=n=t,{top:e,right:i,bottom:s,left:n,disabled:!1===t}}(l(this.options.clip,function(t,e,i){if(!1===i)return!1;const s=Ls(t,i),n=Ls(e,i);return{top:n.end,right:s.end,bottom:n.start,left:s.start}}(e.xScale,e.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,e=this.chart,i=this._cachedMeta,s=i.data||[],n=e.chartArea,o=[],a=this._drawStart||0,r=this._drawCount||s.length-a,l=this.options.drawActiveElementsOnTop;let h;for(i.dataset&&i.dataset.draw(t,n,a,r),h=a;h<a+r;++h){const e=s[h];e.hidden||(e.active&&l?o.push(e):e.draw(t,n))}for(h=0;h<o.length;++h)o[h].draw(t,n)}getStyle(t,e){const i=e?"active":"default";return void 0===t&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(i):this.resolveDataElementOptions(t||0,i)}getContext(t,e,i){const s=this.getDataset();let n;if(t>=0&&t<this._cachedMeta.data.length){const e=this._cachedMeta.data[t];n=e.$context||(e.$context=function(t,e,i){return Ci(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:i,index:e,mode:"default",type:"data"})}(this.getContext(),t,e)),n.parsed=this.getParsed(t),n.raw=s.data[t],n.index=n.dataIndex=t}else n=this.$context||(this.$context=function(t,e){return Ci(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}(this.chart.getContext(),this.index)),n.dataset=s,n.index=n.datasetIndex=this.index;return n.active=!!e,n.mode=i,n}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,e){return this._resolveElementOptions(this.dataElementType.id,e,t)}_resolveElementOptions(t,e="default",i){const s="active"===e,n=this._cachedDataOpts,o=t+"-"+e,a=n[o],r=this.enableOptionSharing&&k(i);if(a)return Hs(a,r);const l=this.chart.config,h=l.datasetElementScopeKeys(this._type,t),c=s?[`${t}Hover`,"hover",t,""]:[t,""],d=l.getOptionScopes(this.getDataset(),h),u=Object.keys(ue.elements[t]),f=l.resolveNamedOptions(d,u,(()=>this.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<s&&this._removeElements(n,s-n)}_insertElements(t,e,i=!0){const s=this._cachedMeta,n=s.data,o=t+e;let a;const r=t=>{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a<o;++a)n[a]=new this.dataElementType;this._parsing&&r(s._parsed),this.parse(t,e),i&&this.updateElements(n,t,e,"reset")}updateElements(t,e,i,s){}_removeElements(t,e){const i=this._cachedMeta;if(this._parsing){const s=i._parsed.splice(t,e);i._stacked&&Ws(i,s)}i.data.splice(t,e)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[e,i,s]=t;this[e](i,s)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-t,t])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(t,e){e&&this._sync(["_removeElements",t,e]);const i=arguments.length-2;i&&this._sync(["_insertElements",t,i])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}class $s{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}hasValue(){return N(this.x)&&N(this.y)}getProps(t,e){const i=this.$animations;if(!e||!i)return this;const s={};return t.forEach((t=>{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;i<s;i++)t[i].major&&e.push(i);return e}(e):[],r=a.length,l=a[0],h=a[r-1],c=[];if(r>o)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;n<t.length;n++)n===a&&(e.push(t[n]),o++,a=i[o*s])}(e,c,a,r/o),c;const d=function(t,e,i){const s=function(t){const e=t.length;let i,s;if(e<2)return!1;for(s=t[0],i=1;i<e;++i)if(t[i]-t[i-1]!==s)return!1;return s}(t),n=e.length/i;if(!s)return Math.max(n,1);const o=W(s);for(let t=0,e=o.length-1;t<e;t++){const e=o[t];if(e>n)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<i;t++)Us(e,c,d,a[t],a[t+1]);return Us(e,c,d,h,s(n)?e.length:h+n),c}return Us(e,c,d),c}function Us(t,e,i,s,n){const o=l(s,0),a=Math.min(l(n,t.length),t.length);let r,h,c,d=0;for(i=Math.ceil(i),n&&(r=n-s,i=r/Math.floor(r/i)),c=o;c<0;)d++,c=Math.round(o+d*i);for(h=Math.max(o,0);h<a;h++)h===c&&(e.push(t[h]),d++,c=Math.round(o+d*i))}const Xs=(t,e,i)=>"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(;o<n;o+=s)i.push(t[Math.floor(o)]);return i}function Gs(t,e,i){const s=t.ticks.length,n=Math.min(e,s-1),o=t._startPixel,a=t._endPixel,r=1e-6;let l,h=t.getPixelForTick(n);if(!(i&&(l=1===s?Math.max(h-o,a-h):0===e?(t.getPixelForTick(1)-h)/2:(h-t.getPixelForTick(n-1))/2,h+=n<e?l:-l,h<o-r||h>a+r)))return h}function Zs(t){return t.drawTicks?t.tickLength:0}function Js(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;r<l;++r)e=a[r].controller.getMinMax(this,t),n||(i=Math.min(i,e.min)),o||(s=Math.max(s,e.max));return i=o&&i>s?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<this.ticks.length;this._convertTicksToLabels(r?Ks(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),o.display&&(o.autoSkip||"auto"===o.source)&&(this.ticks=Ys(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),r&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t,e,i=this.options.reverse;this.isHorizontal()?(t=this.left,e=this.right):(t=this.top,e=this.bottom,i=!i),this._startPixel=t,this._endPixel=e,this._reversePixels=i,this._length=e-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){d(this.options.afterUpdate,[this])}beforeSetDimensions(){d(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){d(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),d(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){d(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const e=this.options.ticks;let i,s,n;for(i=0,s=t.length;i<s;i++)n=t[i],n.label=d(e.callback,[n.value,i,t],this)}afterTickToLabelConversion(){d(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){d(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,e=t.ticks,i=qs(this.ticks.length,t.ticks.maxTicksLimit),s=e.minRotation||0,n=e.maxRotation;let o,a,r,l=s;if(!this._isVisible()||!e.display||s>=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(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-Zs(t.grid)-e.padding-Js(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(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=Js(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Zs(n)+o):(t.height=this.maxHeight,t.width=Zs(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<i;e++)s(t[e].label)&&(t.splice(e,1),i--,e--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const e=this.options.ticks.sampleSize;let i=this.ticks;e<i.length&&(i=Ks(i,e)),this._labelSizes=t=this._computeLabelSizes(i,i.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,e,i){const{ctx:o,_longestTextCache:a}=this,r=[],l=[],h=Math.floor(e/qs(e,i));let c,d,f,g,p,m,x,b,_,y,v,M=0,w=0;for(c=0;c<e;c+=h){if(g=t[c].label,p=this._resolveTickFontOptions(c),o.font=m=p.string,x=a[m]=a[m]||{data:{},gc:[]},b=p.lineHeight,_=y=0,s(g)||n(g)){if(n(g))for(d=0,f=g.length;d<f;++d)v=g[d],s(v)||n(v)||(_=Ce(o,x.data,x.gc,_,v),y+=b)}else _=Ce(o,x.data,x.gc,_,g),y=b;r.push(_),l.push(y),M=Math.max(_,M),w=Math.max(y,w)}!function(t,e){u(t,(t=>{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n<s;++n)delete t.data[i[n]];i.splice(0,s)}}))}(a,e);const k=r.indexOf(M),S=l.indexOf(w),P=t=>({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&&t<e.length){const i=e[t];return i.$context||(i.$context=function(t,e,i){return Ci(t,{tick:i,index:e,type:"tick"})}(this.getContext(),t,i))}return this.$context||(this.$context=Ci(this.chart.getContext(),{scale:this,type:"scale"}))}_tickSize(){const t=this.options.ticks,e=$(this.labelRotation),i=Math.abs(Math.cos(e)),s=Math.abs(Math.sin(e)),n=this._getLabelSizes(),o=t.autoSkipPadding||0,a=n?n.widest.width+o:0,r=n?n.highest.height+o:0;return this.isHorizontal()?r*i>a*s?a/i:r/s:r*s<a*i?r/i:a/s}_isVisible(){const t=this.options.display;return"auto"!==t?!!t:this.getMatchingVisibleMetas().length>0}_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=Zs(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;_<d;_+=T){const t=this.getContext(_),e=n.setContext(t),s=r.setContext(t),o=e.lineWidth,a=e.color,l=s.dash||[],d=s.dashOffset,u=e.tickWidth,g=e.tickColor,p=e.tickBorderDash||[],m=e.tickBorderDashOffset;y=Gs(this,_,h),void 0!==y&&(v=Ae(i,y,o),c?M=k=P=C=v:w=S=D=O=v,f.push({tx1:M,ty1:w,tx2:k,ty2:S,x1:P,y1:D,x2:C,y2:O,width:o,color:a,borderDash:l,borderDashOffset:d,tickWidth:u,tickColor:g,tickBorderDash:p,tickBorderDashOffset:m}))}return this._ticksLength=d,this._borderValue=b,f}_computeLabelItems(t){const e=this.axis,i=this.options,{position:s,ticks:a}=i,r=this.isHorizontal(),l=this.ticks,{align:h,crossAlign:c,padding:d,mirror:u}=a,f=Zs(i.grid),g=f+d,p=u?-d:g,m=-$(this.labelRotation),x=[];let b,_,y,v,M,w,k,S,P,D,C,O,A="middle";if("top"===s)w=this.bottom-p,k=this._getXAxisLabelAlignment();else if("bottom"===s)w=this.top+p,k=this._getXAxisLabelAlignment();else if("left"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("right"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("x"===e){if("center"===s)w=(t.top+t.bottom)/2+g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];w=this.chart.scales[t].getPixelForValue(e)+g}k=this._getXAxisLabelAlignment()}else if("y"===e){if("center"===s)M=(t.left+t.right)/2-g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];M=this.chart.scales[t].getPixelForValue(e)}k=this._getYAxisLabelAlignment(f).textAlign}"y"===e&&("start"===h?A="top":"end"===h&&(A="bottom"));const T=this._getLabelSizes();for(b=0,_=l.length;b<_;++b){y=l[b],v=y.label;const t=a.setContext(this.getContext(b));S=this.getPixelForTick(b)+a.labelOffset,P=this._resolveTickFontOptions(b),D=P.lineHeight,C=n(v)?v.length:1;const e=C/2,i=t.color,o=t.textStrokeColor,h=t.textStrokeWidth;let d,f=k;if(r?(M=S,"inner"===k&&(f=b===_-1?this.options.reverse?"left":"right":0===b?this.options.reverse?"right":"left":"center"),O="top"===s?"near"===c||0!==m?-C*D+D/2:"center"===c?-T.highest.height/2-e*D+D:-T.highest.height+D/2:"near"===c||0!==m?D/2:"center"===c?T.highest.height/2-e*D:T.highest.height-C*D,u&&(O*=-1),0===m||t.showLabelBackdrop||(M+=D/2*Math.sin(m))):(w=S,O=(1-C)*D/2),t.showLabelBackdrop){const e=ki(t.backdropPadding),i=T.heights[b],s=T.widths[b];let n=O-e.top,o=0-e.left;switch(A){case"middle":n-=i/2;break;case"bottom":n-=i}switch(k){case"center":o-=s/2;break;case"right":o-=s;break;case"inner":b===_-1?o-=s:b>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<o;++n){const t=s[n];e.drawOnChartArea&&a({x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t),e.drawTicks&&a({x:t.tx1,y:t.ty1},{x:t.tx2,y:t.ty2},{color:t.tickColor,width:t.tickWidth,borderDash:t.tickBorderDash,borderDashOffset:t.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:e,options:{border:i,grid:s}}=this,n=i.setContext(this.getContext()),o=i.display?n.width:0;if(!o)return;const a=s.setContext(this.getContext(0)).lineWidth,r=this._borderValue;let l,h,c,d;this.isHorizontal()?(l=Ae(t,this.left,o)-o/2,h=Ae(t,this.right,a)+a/2,c=d=r):(c=Ae(t,this.top,o)-o/2,d=Ae(t,this.bottom,a)+a/2,l=h=r),e.save(),e.lineWidth=n.width,e.strokeStyle=n.color,e.beginPath(),e.moveTo(l,c),e.lineTo(h,d),e.stroke(),e.restore()}drawLabels(t){if(!this.options.ticks.display)return;const e=this.ctx,i=this._computeLabelArea();i&&Ie(e,i);const s=this.getLabelItems(t);for(const t of s){const i=t.options,s=t.font;Ne(e,t.label,0,t.textOffset,s,i)}i&&ze(e)}drawTitle(){const{ctx:t,options:{position:e,title:i,reverse:s}}=this;if(!i.display)return;const a=Si(i.font),r=ki(i.padding),l=i.align;let h=a.lineHeight/2;"bottom"===e||"center"===e||o(e)?(h+=r.bottom,n(i.text)&&(h+=a.lineHeight*(i.text.length-1))):h+=r.top;const{titleX:c,titleY:d,maxWidth:u,rotation:f}=function(t,e,i,s){const{top:n,left:a,bottom:r,right:l,chart:h}=t,{chartArea:c,scales:d}=h;let u,f,g,p=0;const m=r-n,x=l-a;if(t.isHorizontal()){if(f=ft(s,a,l),o(i)){const t=Object.keys(i)[0],s=i[t];g=d[t].getPixelForValue(s)+m-e}else g="center"===i?(c.bottom+c.top)/2+m-e:Xs(t,i,e);u=l-a}else{if(o(i)){const t=Object.keys(i)[0],s=i[t];f=d[t].getPixelForValue(s)-x+e}else f="center"===i?(c.left+c.right)/2-x+e:Xs(t,i,e);g=ft(s,r,n),p="left"===i?-E:E}return{titleX:f,titleY:g,maxWidth:u,rotation:p}}(this,h,e,l);Ne(t,i.text,0,0,a,{color:i.color,maxWidth:u,rotation:f,textAlign:Qs(l,e,s),textBaseline:"middle",translation:[c,d]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,e=t.ticks&&t.ticks.z||0,i=l(t.grid&&t.grid.z,-1),s=l(t.border&&t.border.z,0);return this._isVisible()&&this.draw===tn.prototype.draw?[{z:i,draw:t=>{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<o;++n){const o=e[n];o[i]!==this.id||t&&o.type!==t||s.push(o)}return s}_resolveTickFontOptions(t){return Si(this.options.ticks.setContext(this.getContext(t)).font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class en{constructor(t,e,i){this.type=t,this.scope=e,this.override=i,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const e=Object.getPrototypeOf(t);let i;(function(t){return"id"in t&&"defaults"in t})(e)&&(i=this.register(e));const s=this.items,n=t.id,o=this.scope+"."+n;if(!n)throw new Error("class does not have id: "+t);return n in s||(s[n]=t,function(t,e,i){const s=x(Object.create(null),[i?ue.get(i):{},ue.get(e),t.defaults]);ue.set(e,s),t.defaultRoutes&&function(t,e){Object.keys(e).forEach((i=>{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;e<this._typedRegistries.length;e++){const i=this._typedRegistries[e];if(i.isForType(t))return i}return this.plugins}_get(t,e,i){const s=e.get(t);if(void 0===s)throw new Error('"'+t+'" is not a registered '+i+".");return s}}var nn=new sn;class on{constructor(){this._init=[]}notify(t,e,i,s){"beforeInit"===e&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install"));const n=s?this._descriptors(t).filter(s):this._descriptors(t),o=this._notify(n,t,e,i);return"afterDestroy"===e&&(this._notify(n,t,"stop"),this._notify(this._init,t,"uninstall")),o}_notify(t,e,i,s){s=s||{};for(const n of t){const t=n.plugin;if(!1===d(t[i],[e,s,n.options],t)&&s.cancelable)return!1}return!0}invalidate(){s(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const e=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),e}_createDescriptors(t,e){const i=t&&t.config,s=l(i.options&&i.options.plugins,{}),n=function(t){const e={},i=[],s=Object.keys(nn.plugins.items);for(let t=0;t<s.length;t++)i.push(nn.getPlugin(s[t]));const n=t.plugins||[];for(let t=0;t<n.length;t++){const s=n[t];-1===i.indexOf(s)&&(i.push(s),e[s.id]=!0)}return{plugins:i,localIds:e}}(i);return!1!==s||e?function(t,{plugins:e,localIds:i},s,n){const o=[],a=t.getContext();for(const r of e){const e=r.id,l=an(s[e],n);null!==l&&o.push({plugin:r,options:rn(t.config,{plugin:r,local:i[e]},l,a)})}return o}(t,n,s,e):[]}_notifyStateChanges(t){const e=this._oldCache||[],i=this._cache,s=(t,e)=>t.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.4.9";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;t<i;++t)this._destroyDatasetMeta(t);t.splice(e,i-e)}this._sortedMetasets=t.slice(0).sort(kn("order","index"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:e}}=this;t.length>e.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<s;i++){const s=e[i];let n=this.getDatasetMeta(i);const o=s.type||this.config.type;if(n.type&&n.type!==o&&(this._destroyDatasetMeta(i),n=this.getDatasetMeta(i)),n.type=o,n.indexAxis=s.indexAxis||ln(o,this.options),n.order=s.order||0,n.index=i,n.label=""+s.label,n.visible=this.isDatasetVisible(i),n.controller)n.controller.updateIndex(i),n.controller.linkScales();else{const e=nn.getController(o),{datasetElementType:s,dataElementType:a}=ue.datasets[o];Object.assign(e,{dataElementType:nn.getElement(a),datasetElementType:s&&nn.getElement(s)}),n.controller=new e(this,i),t.push(n.controller)}}return this._updateMetasets(),t}_resetElements(){u(this.data.datasets,((t,e)=>{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<e;t++){const{controller:e}=this.getDatasetMeta(t),i=!s&&-1===n.indexOf(e);e.buildOrUpdateElements(i),o=Math.max(+e.getMaxOverflow(),o)}o=this._minPadding=i.layout.autoPadding?o:0,this._updateLayout(o),s||u(n,(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;t<e;t++)if(!P(s,i(t)))return;return Array.from(s).map((t=>t.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<e;++t)this.getDatasetMeta(t).controller.configure();for(let e=0,i=this.data.datasets.length;e<i;++e)this._updateDataset(e,S(t)?t({datasetIndex:e}):t);this.notifyPlugins("afterDatasetsUpdate",{mode:t})}}_updateDataset(t,e){const i=this.getDatasetMeta(t),s={meta:i,index:t,mode:e,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetUpdate",s)&&(i.controller._update(e),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){!1!==this.notifyPlugins("beforeRender",{cancelable:!0})&&(bt.has(this)?this.attached&&!bt.running(this)&&bt.start(this):(this.draw(),Sn({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:t,height:e}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(t,e)}if(this.clear(),this.width<=0||this.height<=0)return;if(!1===this.notifyPlugins("beforeDraw",{cancelable:!0}))return;const e=this._layers;for(t=0;t<e.length&&e[t].z<=0;++t)e[t].draw(this.chartArea);for(this._drawDatasets();t<e.length;++t)e[t].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(t){const e=this._sortedMetasets,i=[];let s,n;for(s=0,n=e.length;s<n;++s){const n=e[s];t&&!n.visible||i.push(n)}return i}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(!1===this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0}))return;const t=this.getSortedVisibleDatasetMetas();for(let e=t.length-1;e>=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;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:t,ctx:e}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),Te(t,e),this.platform.releaseContext(e),this.canvas=null,this.ctx=null),delete Cn[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,e=this.platform,i=(i,s)=>{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<r;++a){o=t[a];const e=o&&this.getDatasetMeta(o.datasetIndex).controller;e&&e[s+"HoverStyle"](o.element,o.datasetIndex,o.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const e=this._active||[],i=t.map((({datasetIndex:t,index:e})=>{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;e<n;e++)s=s.concat(i[e].controller.getAllParsedValues(t));t._cache.$bar=lt(s.sort(((t,e)=>t-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;s<n;++s)o=e.getPixelForValue(i[s]),l();for(a=void 0,s=0,n=e.ticks.length;s<n;++s)o=e.getPixelForTick(s),l();return r}function Fn(t,e,i,s){return n(t)?function(t,e,i,s){const n=i.parse(t[0],s),o=i.parse(t[1],s),a=Math.min(n,o),r=Math.max(n,o);let l=a,h=r;Math.abs(a)>Math.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;h<c;++h)u=e[h],d={},d[n.axis]=r||n.parse(a[h],h),l.push(Fn(u,d,o,h));return l}function Bn(t){return t&&void 0!==t.barStart&&void 0!==t.barEnd}function Wn(t,e,i,s){let n=e.borderSkipped;const o={};if(!n)return void(t.borderSkipped=o);if(!0===n)return void(t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0});const{start:a,end:r,reverse:l,top:h,bottom:c}=function(t){let e,i,s,n,o;return t.horizontal?(e=t.base>t.x,i="left",s="right"):(e=t.base<t.y,i="bottom",s="top"),e?(n="end",o="start"):(n="start",o="end"),{start:i,end:s,reverse:e,top:n,bottom:o}}(t);"middle"===n&&i&&(t.enableBorderRadius=!0,(i._top||0)===s?n=h:(i._bottom||0)===s?n=c:(o[Nn(c,a,r,l)]=!0,n=h)),o[Nn(n,a,r,l)]=!0,t.borderSkipped=o}function Nn(t,e,i,s){var n,o,a;return s?(a=i,t=Hn(t=(n=t)===(o=e)?a:n===a?o:n,i,e)):t=Hn(t,e,i),t}function Hn(t,e,i){return"start"===t?e:"end"===t?i:t}function jn(t,{inflateAmount:e},i){t.inflateAmount="auto"===e?1===i?.33:0:e}class $n extends js{static id="doughnut";static defaults={datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"};static descriptors={_scriptable:t=>"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;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{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()}}}};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;n<a;++n)s._parsed[n]=r(n)}}_getRotation(){return $(this.options.rotation-90)}_getCircumference(){return $(this.options.circumference)}_getRotationExtents(){let t=O,e=-O;for(let i=0;i<this.chart.data.datasets.length;++i)if(this.chart.isDatasetVisible(i)&&this.chart.getDatasetMeta(i).type===this._type){const s=this.chart.getDatasetMeta(i).controller,n=s._getRotation(),o=s._getCircumference();t=Math.min(t,n),e=Math.max(e,n+o)}return{rotation:t,circumference:e-t}}update(t){const e=this.chart,{chartArea:i}=e,s=this._cachedMeta,n=s.data,o=this.getMaxBorderWidth()+this.getMaxOffset(n)+this.options.spacing,a=Math.max((Math.min(i.width,i.height)-o)/2,0),r=Math.min(h(this.options.cutout,a),1),l=this._getRingWeight(this.index),{circumference:d,rotation:u}=this._getRotationExtents(),{ratioX:f,ratioY:g,offsetX:p,offsetY:m}=function(t,e,i){let s=1,n=1,o=0,a=0;if(e<O){const r=t,l=r+e,h=Math.cos(r),c=Math.sin(r),d=Math.cos(l),u=Math.sin(l),f=(t,e,s)=>Z(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(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;p<e;++p)m+=this._circumference(p,n);for(p=e;p<e+i;++p){const e=this._circumference(p,n),i=t[p],o={x:l+this.offsetX,y:h+this.offsetY,startAngle:m,endAngle:m+e,circumference:e,outerRadius:u,innerRadius:d};g&&(o.options=f||this.resolveDataElementOptions(p,i.active?"active":s)),m+=e,this.updateElement(i,p,o,s)}}calculateTotal(){const t=this._cachedMeta,e=t.data;let i,s=0;for(i=0;i<e.length;i++){const n=t._parsed[i];null===n||isNaN(n)||!this.chart.getDataVisibility(i)||e[i].hidden||(s+=Math.abs(n))}return s}calculateCircumference(t){const e=this._cachedMeta.total;return e>0&&!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<n;++s)if(i.isDatasetVisible(s)){o=i.getDatasetMeta(s),t=o.data,a=o.controller;break}if(!t)return 0;for(s=0,n=t.length;s<n;++s)r=a.resolveDataElementOptions(s),"inner"!==r.borderAlign&&(e=Math.max(e,r.borderWidth||0,r.hoverBorderWidth||0));return e}getMaxOffset(t){let e=0;for(let i=0,s=t.length;i<s;++i){const t=this.resolveDataElementOptions(i);e=Math.max(e,t.offset||0,t.hoverOffset||0)}return e}_getRingWeightOffset(t){let e=0;for(let i=0;i<t;++i)this.chart.isDatasetVisible(i)&&(e+=this._getRingWeight(i));return e}_getRingWeight(t){return Math.max(l(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}class Yn extends js{static id="polarArea";static defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{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)&&(s<e.min&&(e.min=s),s>e.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<e;++d)u+=this._computeAngle(d,s,f);for(d=e;d<e+i;d++){const e=t[d];let i=u,g=u+this._computeAngle(d,s,f),p=o.getDataVisibility(d)?r.getDistanceFromCenterForValue(this.getParsed(d).r):0;u=g,n&&(a.animateScale&&(p=0),a.animateRotate&&(i=g=c));const m={x:l,y:h,innerRadius:0,outerRadius:p,startAngle:i,endAngle:g,options:this.resolveDataElementOptions(d,e.active?"active":s)};this.updateElement(e,d,m,s)}}countVisibleElements(){const t=this._cachedMeta;let e=0;return t.data.forEach(((t,i)=>{!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;d<u;++d)g=e[d],f={},f[n.axis]=n.parse(M(g,l),d),c.push(Fn(M(g,h),f,o,d));return c}updateRangeFromParsed(t,e,i,s){super.updateRangeFromParsed(t,e,i,s);const n=i._custom;n&&e===this._cachedMeta.vScale&&(t.min=Math.min(t.min,n.min),t.max=Math.max(t.max,n.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const e=this._cachedMeta,{iScale:i,vScale:s}=e,n=this.getParsed(t),o=n._custom,a=Bn(o)?"["+o.start+", "+o.end+"]":""+s.getLabelForValue(n[s.axis]);return{label:""+i.getLabelForValue(n[i.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();this._cachedMeta.stack=this.getDataset().stack}update(t){const e=this._cachedMeta;this.updateElements(e.data,0,e.data.length,t)}updateElements(t,e,i,n){const o="reset"===n,{index:a,_cachedMeta:{vScale:r}}=this,l=r.getBasePixel(),h=r.isHorizontal(),c=this._getRuler(),{sharedOptions:d,includeOptions:u}=this._getSharedOptions(e,n);for(let f=e;f<e+i;f++){const e=this.getParsed(f),i=o||s(e[r.axis])?{base:l,head:l}:this._calculateBarValuePixels(f),g=this._calculateBarIndexPixels(f,c),p=(e._stacks||{})[r.axis],m={horizontal:h,base:i.base,enableBorderRadius:!p||Bn(e._custom)||a===p._top||a===p._bottom,x:h?i.head:g.center,y:h?g.center:i.head,height:h?g.size:Math.abs(i.size),width:h?Math.abs(i.size):g.size};u&&(m.options=d||this.resolveDataElementOptions(f,t[f].active?"active":n));const x=m.options||t[f].options;Wn(m,x,p,a),jn(m,x,c.ratio),this.updateElement(t[f],f,m,n)}}_getStacks(t,e){const{iScale:i}=this._cachedMeta,n=i.getMatchingVisibleMetas(this._type).filter((t=>t.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}_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<o;++n)s.push(i.getPixelForValue(this.getParsed(n)[i.axis],n));const a=t.barThickness;return{min:a||zn(e),pixels:s,start:i._startPixel,end:i._endPixel,stackCount:this._getStackCount(),scale:i,grouped:t.grouped,ratio:a?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:e,_stacked:i,index:n},options:{base:o,minBarLength:a}}=this,r=o||0,l=this.getParsed(t),h=l._custom,c=Bn(h);let d,u,f=l[e.axis],g=0,p=i?this.applyStack(e,l,i):f;p!==f&&(g=p-f,p=f),c&&(f=h.barStart,p=h.barEnd-h.barStart,0!==f&&F(f)!==F(h.barEnd)&&(g=0),g+=f);const m=s(o)||c?g:o;let x=e.getPixelForValue(m);if(d=this.chart.getDataVisibility(t)?e.getPixelForValue(g+p):x,u=d-x,Math.abs(u)<a){u=function(t,e,i){return 0!==t?F(t):(e.isHorizontal()?1:-1)*(e.min>=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;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="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<n.length-1?n[t+1]:null;const l=i.categoryPercentage;null===a&&(a=o-(null===r?e.end-e.start:r-o)),null===r&&(r=o+o-a);const h=o-(o-Math.min(a,r))/2*l;return{chunk:Math.abs(r-a)/2*l/s,ratio:i.barPercentage,start:h}}(t,e,n,i):function(t,e,i,n){const o=i.barThickness;let a,r;return s(o)?(a=e.min*i.categoryPercentage,r=i.barPercentage):(a=o*n,r=1),{chunk:a/n,ratio:r,start:e.pixels[t]-a/2}}(t,e,n,i),c=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0);r=l.start+l.chunk*c+l.chunk/2,h=Math.min(a,l.chunk*l.ratio)}else r=i.getPixelForValue(this.getParsed(t)[i.axis],t),h=Math.min(a,e.min*e.ratio);return{base:r-h/2,head:r+h/2,center:r,size:h}}draw(){const t=this._cachedMeta,e=t.vScale,i=t.data,s=i.length;let n=0;for(;n<s;++n)null===this.getParsed(n)[e.axis]||i[n].hidden||i[n].draw(this._ctx)}},BubbleController:class extends js{static id="bubble";static defaults={datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}};static overrides={scales:{x:{type:"linear"},y:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,e,i,s){const n=super.parsePrimitiveData(t,e,i,s);for(let t=0;t<n.length;t++)n[t]._custom=this.resolveDataElementOptions(t+i).radius;return n}parseArrayData(t,e,i,s){const n=super.parseArrayData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s[2],this.resolveDataElementOptions(t+i).radius)}return n}parseObjectData(t,e,i,s){const n=super.parseObjectData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s&&s.r&&+s.r,this.resolveDataElementOptions(t+i).radius)}return n}getMaxOverflow(){const t=this._cachedMeta.data;let e=0;for(let i=t.length-1;i>=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;d<e+i;d++){const e=t[d],i=!n&&this.getParsed(d),u={},f=u[h]=n?o.getPixelForDecimal(.5):o.getPixelForValue(i[h]),g=u[c]=n?a.getBasePixel():a.getPixelForValue(i[c]);u.skip=isNaN(f)||isNaN(g),l&&(u.options=r||this.resolveDataElementOptions(d,e.active?"active":s),n&&(u.options.radius=0)),this.updateElement(e,d,u,s)}}resolveDataElementOptions(t,e){const i=this.getParsed(t);let s=super.resolveDataElementOptions(t,e);s.$shared&&(s=Object.assign({},s,{$shared:!1}));const n=s.radius;return"active"!==e&&(s.radius=0),s.radius+=l(i&&i._custom,n),s}},DoughnutController:$n,LineController:class extends js{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:i,data:s=[],_dataset:n}=e,o=this.chart._animationsDisabled;let{start:a,count:r}=pt(e,s,o);this._drawStart=a,this._drawCount=r,mt(e)&&(a=0,r=s.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!n._decimated,i.points=s;const l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!o,options:l},t),this.updateElements(s,a,r,t)}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),u=a.axis,f=r.axis,{spanGaps:g,segment:p}=this.options,m=N(g)?g:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||"none"===n,b=e+i,_=t.length;let y=e>0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i<e||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;a<e+i;a++){const e=t[a],i=this.resolveDataElementOptions(a,e.active?"active":s),r=n.getPointPositionForValue(a,this.getParsed(a).r),l=o?n.xCenter:r.x,h=o?n.yCenter:r.y,c={x:l,y:h,angle:r.angle,skip:isNaN(l)||isNaN(h),options:i};this.updateElement(e,a,c,s)}}},ScatterController:class extends js{static id="scatter";static defaults={datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1};static overrides={interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}};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);return{label:i[t]||"",value:"("+a+", "+r+")"}}update(t){const e=this._cachedMeta,{data:i=[]}=e,s=this.chart._animationsDisabled;let{start:n,count:o}=pt(e,i,s);if(this._drawStart=n,this._drawCount=o,mt(e)&&(n=0,o=i.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:n,_dataset:o}=e;n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;const a=this.resolveDatasetElementOptions(t);a.segment=this.options.segment,this.updateElement(n,void 0,{animated:!s,options:a},t)}else this.datasetElementType&&(delete e.dataset,this.datasetElementType=!1);this.updateElements(i,n,o,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement("line")),super.addElements()}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,c=this.resolveDataElementOptions(e,n),d=this.getSharedOptions(c),u=this.includeOptions(n,d),f=a.axis,g=r.axis,{spanGaps:p,segment:m}=this.options,x=N(p)?p:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||"none"===n;let _=e>0&&this.getParsed(e-1);for(let c=e;c<e+i;++c){const e=t[c],i=this.getParsed(c),p=b?e:{},y=s(i[g]),v=p[f]=a.getPixelForValue(i[f],c),M=p[g]=o||y?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,i,l):i[g],c);p.skip=isNaN(v)||isNaN(M)||y,p.stop=c>0&&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 J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(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}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){Kn(t,e,i,s,g,n);for(let e=0;e<o;++e)t.stroke();isNaN(r)||(g=a+(r%O||O))}f&&function(t,e,i){const{startAngle:s,pixelMargin:n,x:o,y:a,outerRadius:r,innerRadius:l}=e;let h=n/r;t.beginPath(),t.arc(o,a,r,s-h,i+h),l>n?(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,g),o||(Kn(t,e,i,s,g,n),t.stroke())}function Zn(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 Jn(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=n<a&&o<a||n>r&&o>r;return{count:s,start:l,loop:e.loop,ilen:h<l&&!c?s+h-l:h-l}}function to(t,e,i,s){const{points:n,options:o}=e,{count:a,start:r,loop:l,ilen:h}=Qn(n,i,s),c=function(t){return t.stepped?Fe:t.tension||"monotone"===t.cubicInterpolationMode?Ve:Jn}(o);let d,u,f,{move:g=!0,reverse:p}=s||{};for(d=0;d<=h;++d)u=n[(r+(p?h-d:d))%a],u.skip||(g?(t.moveTo(u.x,u.y),g=!1):c(t,f,u,p,o.stepped),f=u);return l&&(u=n[(r+(p?h:0))%a],c(t,f,u,p,o.stepped)),!!l}function eo(t,e,i,s){const n=e.points,{count:o,start:a,ilen:r}=Qn(n,i,s),{move:l=!0,reverse:h}=s||{};let c,d,u,f,g,p,m=0,x=0;const b=t=>(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?(i<f?f=i:i>g&&(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()),Zn(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)Zn(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<h;++l){const{start:h,end:c}=o[l],d=n[h],u=n[c];if(d===u){a.push(d);continue}const f=r(d,u,Math.abs((s-d[e])/(u[e]-d[e])),i.stepped);f[e]=t[e],a.push(f)}return 1===a.length?a[0]:a}pathSegment(t,e,i){return io(this)(t,this,e,i)}path(t,e,i){const s=this.segments,n=io(this);let o=this._loop;e=e||0,i=i||this.points.length-e;for(const a of s)o&=n(t,this,a,{start:e,end:e+i-1});return!!o}draw(t,e,i,s){const n=this.options||{};(this.points||[]).length&&n.borderWidth&&(t.save(),no(t,this,i,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function ao(t,e,i,s){const n=t.options,{[i]:o}=t.getProps([i],s);return Math.abs(e-o)<n.radius+n.hitRadius}function ro(t,e){const{x:i,y:s,base:n,width:o,height:a}=t.getProps(["x","y","base","width","height"],e);let r,l,h,c,d;return t.horizontal?(d=a/2,r=Math.min(i,n),l=Math.max(i,n),h=s-d,c=s+d):(d=o/2,r=i-d,l=i+d,h=Math.min(s,n),c=Math.max(s,n)),{left:r,top:h,right:l,bottom:c}}function lo(t,e,i,s){return t?0:J(e,i,s)}function ho(t){const e=ro(t),i=e.right-e.left,s=e.bottom-e.top,n=function(t,e,i){const s=t.options.borderWidth,n=t.borderSkipped,o=Mi(s);return{t:lo(n.top,o.top,0,i),r:lo(n.right,o.right,0,e),b:lo(n.bottom,o.bottom,0,i),l:lo(n.left,o.left,0,e)}}(t,i/2,s/2),a=function(t,e,i){const{enableBorderRadius:s}=t.getProps(["enableBorderRadius"]),n=t.options.borderRadius,a=wi(n),r=Math.min(e,i),l=t.borderSkipped,h=s||o(n);return{topLeft:lo(!h||l.top||l.left,a.topLeft,0,r),topRight:lo(!h||l.top||l.right,a.topRight,0,r),bottomLeft:lo(!h||l.bottom||l.left,a.bottomLeft,0,r),bottomRight:lo(!h||l.bottom||l.right,a.bottomRight,0,r)}}(t,i/2,s/2);return{outer:{x:e.left,y:e.top,w:i,h:s,radius:a},inner:{x:e.left+n.l,y:e.top+n.t,w:i-n.l-n.r,h:s-n.t-n.b,radius:{topLeft:Math.max(0,a.topLeft-Math.max(n.t,n.l)),topRight:Math.max(0,a.topRight-Math.max(n.t,n.r)),bottomLeft:Math.max(0,a.bottomLeft-Math.max(n.b,n.l)),bottomRight:Math.max(0,a.bottomRight-Math.max(n.b,n.r))}}}}function co(t,e,i,s){const n=null===e,o=null===i,a=t&&!(n&&o)&&ro(t,s);return a&&(n||tt(e,a.left,a.right))&&(o||tt(i,a.top,a.bottom))}function uo(t,e){t.rect(e.x,e.y,e.w,e.h)}function fo(t,e,i={}){const s=t.x!==i.x?-e:0,n=t.y!==i.y?-e:0,o=(t.x+t.w!==i.x+i.w?e:0)-s,a=(t.y+t.h!==i.y+i.h?e:0)-n;return{x:t.x+s,y:t.y+n,w:t.w+o,h:t.h+a,radius:t.radius}}var go=Object.freeze({__proto__:null,ArcElement:class extends $s{static id="arc";static defaults={borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0};static defaultRoutes={backgroundColor:"backgroundColor"};static descriptors={_scriptable:!0,_indexable:t=>"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=Z(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<o;++e)t.fill();isNaN(r)||(l=a+(r%O||O))}Kn(t,e,i,s,l,n),t.fill()}(t,this,r,n,o),Gn(t,this,r,n,o),t.restore()}},BarElement:class extends $s{static id="bar";static defaults={borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:e,options:{borderColor:i,backgroundColor:s}}=this,{inner:n,outer:o}=ho(this),a=(r=o.radius).topLeft||r.topRight||r.bottomLeft||r.bottomRight?He:uo;var r;t.save(),o.w===n.w&&o.h===n.h||(t.beginPath(),a(t,fo(o,e,n)),t.clip(),a(t,fo(n,-e,o)),t.fillStyle=i,t.fill("evenodd")),t.beginPath(),a(t,fo(n,e)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,e,i){return co(this,t,e,i)}inXRange(t,e){return co(this,t,null,e)}inYRange(t,e){return co(this,null,t,e)}getCenterPoint(t){const{x:e,y:i,base:s,horizontal:n}=this.getProps(["x","y","base","horizontal"],t);return{x:n?(e+s)/2:e,y:n?i:(i+s)/2}}getRange(t){return"x"===t?this.width/2:this.height/2}},LineElement:oo,PointElement:class extends $s{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.options,{x:n,y:o}=this.getProps(["x","y"],i);return Math.pow(t-n,2)+Math.pow(e-o,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(t,e){return ao(this,t,"x",e)}inYRange(t,e){return ao(this,t,"y",e)}getCenterPoint(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}size(t){let e=(t=t||this.options||{}).radius||0;e=Math.max(e,e&&t.hoverRadius||0);return 2*(e+(e&&t.borderWidth||0))}draw(t,e){const i=this.options;this.skip||i.radius<.1||!Re(this,e,this.size(i)/2)||(t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.fillStyle=i.backgroundColor,Le(t,i,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}});function po(t,e,i,s){const n=t.indexOf(e);if(-1===n)return((t,e,i,s)=>("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&&t<e.length?e[t]:t}function xo(t,e,{horizontal:i,minRotation:s}){const n=$(s),o=(i?Math.sin(n):Math.cos(n))||.001,a=.75*e*(""+t).length;return Math.min(e/o,a)}class bo extends tn{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return s(t)||("number"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds();let{min:s,max:n}=this;const o=t=>s=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}),M<a&&D++,V(Math.round((M+D*S)*v)/v,a,xo(a,y,t))&&D++):M<a&&D++);D<k;++D){const t=Math.round((M+D*S)*v)/v;if(b&&t>r)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<i;)s.push({value:f,major:Mo(f),significand:u}),u>=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}:t<s||t>n?{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;u<a;u++){const a=r.setContext(t.getPointLabelContext(u));o[u]=a.padding;const f=t.getPointPosition(u,t.drawingArea+o[u],l),g=Si(a.font),p=(h=t.ctx,c=g,d=n(d=t._pointLabels[u])?d:[d],{w:Oe(h,c.string,d),h:d.length*c.lineHeight});s[u]=p;const m=G(t.getIndexAngle(u)+l),x=Math.round(Y(m));Oo(i,e,m,Do(x,f.x,p.w,0,180),Do(x,f.y,p.h,90,270))}var h,c,d;t.setCenterPoint(e.l-i.l,i.r-e.r,e.t-i.t,i.b-e.b),t._pointLabelItems=function(t,e,i){const s=[],n=t._pointLabels.length,o=t.options,{centerPointLabels:a,display:r}=o.pointLabels,l={extra:Po(o)/2,additionalAngle:a?C/n:0};let h;for(let o=0;o<n;o++){l.padding=i[o],l.size=e[o];const n=Ao(t,o,l);s.push(n),"auto"===r&&(n.visible=To(n,h),n.visible&&(h=n))}return s}(t,s,o)}function Oo(t,e,i,s,n){const o=Math.abs(Math.sin(i)),a=Math.abs(Math.cos(i));let r=0,l=0;s.start<e.l?(r=(e.l-s.start)/o,t.l=Math.min(t.l,e.l-r)):s.end>e.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.start<e.t?(l=(e.t-n.start)/a,t.t=Math.min(t.t,e.t-l)):n.end>e.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;o<s;o++)i=t.getPointPosition(o,e),n.lineTo(i.x,i.y)}}class Ro extends bo{static id="radialLinear";static defaults={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ae.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,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<e.length){const i=e[t];return function(t,e,i){return Ci(t,{label:i,index:e,type:"pointLabel"})}(this.getContext(),t,i)}}getPointPosition(t,e,i=0){const s=this.getIndexAngle(t)-E+i;return{x:Math.cos(s)*e+this.xCenter,y:Math.sin(s)*e+this.yCenter,angle:s}}getPointPositionForValue(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:e,top:i,right:s,bottom:n}=this._pointLabelItems[t];return{left:e,top:i,right:s,bottom:n}}drawBackground(){const{backgroundColor:t,grid:{circular:e}}=this.options;if(t){const i=this.ctx;i.save(),i.beginPath(),Eo(this,this.getDistanceFromCenterForValue(this._endValue),e,this._pointLabels.length),i.closePath(),i.fillStyle=t,i.fill(),i.restore()}}drawGrid(){const t=this.ctx,e=this.options,{angleLines:i,grid:s,border:n}=e,o=this._pointLabels.length;let a,r,l;if(e.pointLabels.display&&function(t,e){const{ctx:i,options:{pointLabels:s}}=t;for(let n=e-1;n>=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<n-1;++o){const t=Io[zo[o]],n=t.steps?t.steps:Number.MAX_SAFE_INTEGER;if(t.common&&Math.ceil((i-e)/(n*t.size))<=s)return zo[o]}return zo[n-1]}function Wo(t,e,i){if(i){if(i.length){const{lo:s,hi:n}=et(i,e);t[i[s]>=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<o;++a)r=e[a],n[r]=a,s.push({value:r,major:!1});return 0!==o&&i?function(t,e,i,s){const n=t._adapter,o=+n.startOf(e[0].value,s),a=e[e.length-1].value;let r,l;for(r=o;r<=a;r=+n.add(r,1,s))l=i[r],l>=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<i;++e)if(Io[zo[e]].common)return zo[e]}(this._unit):void 0,this.initOffsets(s),t.reverse&&o.reverse(),No(this,o,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map((t=>+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=J(s,0,o),n=J(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<i;d=+t.add(d,a,o),u++)Wo(c,d,g);return d!==i&&"ticks"!==s.bounds&&1!==u||Wo(c,d,g),Object.keys(c).sort(Fo).map((t=>+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;e<i;++e)s=t[e],s.label=this._tickFormatFunction(s.value,e,t)}getDecimalForValue(t){return null===t?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const e=this._offsets,i=this.getDecimalForValue(t);return this.getPixelForDecimal((e.start+i)*e.factor)}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return this.min+i*(this.max-this.min)}_getLabelSize(t){const e=this.options.ticks,i=this.ctx.measureText(t).width,s=$(this.isHorizontal()?e.maxRotation:e.minRotation),n=Math.cos(s),o=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:i*n+a*o,h:i*o+a*n}}_getLabelCapacity(t){const e=this.options.time,i=e.displayFormats,s=i[e.unit]||i.millisecond,n=this._tickFormatFunction(t,0,No(this,[t],this._majorUnit),s),o=this._getLabelSize(n),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?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<e;++t)i=i.concat(s[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(i)}getLabelTimestamps(){const t=this._cache.labels||[];let e,i;if(t.length)return t;const s=this.getLabels();for(e=0,i=s.length;e<i;++e)t.push(Vo(this,s[e]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return lt(t.sort(Fo))}}function jo(t,e,i){let s,n,o,a,r=0,l=t.length-1;i?(e>=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:J(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<a;++o)l=t[o],l>=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;o<a;++o)h=s[o+1],r=s[o-1],l=s[o],Math.round((h+r)/2)!==l&&n.push({time:l,pos:o/(a-1)});return n}_generate(){const t=this.min,e=this.max;let i=super.getDataTimestamps();return i.includes(t)&&i.length||i.splice(0,0,t),i.includes(e)&&1!==i.length||i.push(e),i.sort(((t,e)=>t-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 Zo={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 Jo(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=>{Jo(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=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(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 Jo(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;c<o-2;c++){let s,n=0,o=0;const h=Math.floor((c+1)*r)+1+e,m=Math.min(Math.floor((c+2)*r)+1,i)+e,x=m-h;for(s=h;s<m;s++)n+=t[s].x,o+=t[s].y;n/=x,o/=x;const b=Math.floor(c*r)+1+e,_=Math.min(Math.floor((c+1)*r)+1,i)+e,{x:y,y:v}=t[p];for(u=f=-1,s=b;s<_;s++)f=.5*Math.abs((y-n)*(t[s].y-v)-(y-t[s].x)*(o-v)),f>u&&(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;o<e+i;++o){a=t[o],r=(a.x-_)/y*n,l=a.y;const e=0|r;if(e===h)l<f?(f=l,c=o):l>g&&(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<i.length;n++){const o=i[n],{first:a,last:r,point:l}=ha(o,e,"x");if(!(!l||a&&r))if(a)s.unshift(l);else if(t.push(l),!r)break}t.push(...s)}function ha(t,e,i){const s=t.interpolate(e,i);if(!s)return{};const n=s[i],o=t.segments,a=t.points;let r=!1,l=!1;for(let t=0;t<o.length;t++){const e=o[t],s=a[e.start][i],h=a[e.end][i];if(tt(n,s,h)){r=n===s,l=n===h;break}}return{first:r,last:l,point:s}}class ca{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){const{x:s,y:n,radius:o}=this;return e=e||{start:0,end:O},t.arc(s,n,o,e.end,e.start,!0),!i.bounds}interpolate(t){const{x:e,y:i,radius:s}=this,n=t.angle;return{x:e+Math.cos(n)*s,y:i+Math.sin(n)*s,angle:n}}}function da(t){const{chart:e,fill:i,line:s}=t;if(a(i))return function(t,e){const i=t.getDatasetMeta(e),s=i&&t.isDatasetVisible(e);return s?i.dataset:null}(e,i);if("stack"===i)return function(t){const{scale:e,index:i,line:s}=t,n=[],o=s.segments,a=s.points,r=function(t,e){const i=[],s=t.getMatchingVisibleMetas("line");for(let t=0;t<s.length;t++){const n=s[t];if(n.index===e)break;n.hidden||i.unshift(n.dataset)}return i}(e,i);r.push(na({x:null,y:e.bottom},s));for(let t=0;t<o.length;t++){const e=o[t];for(let t=e.start;t<=e.end;t++)la(n,a[t],r)}return new oo({points:n,options:{}})}(t);if("shape"===i)return!0;const n=function(t){const e=t.scale||{};if(e.getPointPositionForValue)return function(t){const{scale:e,fill:i}=t,s=e.options,n=e.getLabels().length,a=s.reverse?e.max:e.min,r=function(t,e,i){let s;return s="start"===t?i:"end"===t?e.options.reverse?e.min:e.max:o(t)?t.value:e.getBaseValue(),s}(i,e,a),l=[];if(s.grid.circular){const t=e.getPointPositionForValue(0,a);return new ca({x:t.x,y:t.y,radius:e.getDistanceFromCenterForValue(r)})}for(let t=0;t<n;++t)l.push(e.getPointPositionForValue(t,r));return l}(t);return function(t){const{scale:e={},fill:i}=t,s=function(t,e){let i=null;return"start"===t?i=e.bottom:"end"===t?i=e.top:o(t)?i=e.getPixelForValue(t.value):e.getBasePixel&&(i=e.getBasePixel()),i}(i,e);if(a(s)){const t=e.isHorizontal();return{x:t?s:null,y:t?null:s}}return null}(t)}(t);return n instanceof ca?n:na(n,s)}function ua(t,e,i){const s=da(e),{chart:n,index:o,line:a,scale:r,axis:l}=e,h=a.options,c=h.fill,d=h.backgroundColor,{above:u=d,below:f=d}=c||{},g=n.getDatasetMeta(o),p=Ni(n,g);s&&a.points.length&&(Ie(t,i),function(t,e){const{line:i,target:s,above:n,below:o,area:a,scale:r,clip:l}=e,h=i._loop?"angle":e.axis;t.save(),"x"===h&&o!==n&&(fa(t,s,a.top),ga(t,{line:i,target:s,color:n,scale:r,property:h,clip:l}),t.restore(),t.save(),fa(t,s,a.bottom));ga(t,{line:i,target:s,color:o,scale:r,property:h,clip:l}),t.restore()}(t,{line:a,target:s,above:u,below:f,area:i,scale:r,axis:l,clip:p}),ze(t))}function fa(t,e,i){const{segments:s,points:n}=e;let o=!0,a=!1;t.beginPath();for(const r of s){const{start:s,end:l}=r,h=n[s],c=n[ia(s,l,n)];o?(t.moveTo(h.x,h.y),o=!1):(t.lineTo(h.x,i),t.lineTo(h.x,h.y)),a=!!e.pathSegment(t,r,{move:a}),a?t.closePath():t.lineTo(c.x,i)}t.lineTo(e.first().x,i),t.closePath(),t.clip()}function ga(t,e){const{line:i,target:s,property:n,color:o,scale:a,clip:r}=e,l=function(t,e,i){const s=t.segments,n=t.points,o=e.points,a=[];for(const t of s){let{start:s,end:r}=t;r=ia(s,r,n);const l=ea(i,n[s],n[r],t.loop);if(!e.segments){a.push({source:t,target:l,start:n[s],end:n[r]});continue}const h=Ii(e,l);for(const e of h){const s=ea(i,o[e.start],o[e.end],e.loop),r=Ri(t,n,s);for(const t of r)a.push({source:t,target:e,start:{[i]:sa(l,s,"start",Math.max)},end:{[i]:sa(l,s,"end",Math.min)}})}}return a}(i,s,n);for(const{source:e,target:h,start:c,end:d}of l){const{style:{backgroundColor:l=o}={}}=e,u=!0!==s;t.save(),t.fillStyle=l,pa(t,a,r,u&&ea(n,c,d)),t.beginPath();const f=!!i.pathSegment(t,e);let g;if(u){f?t.closePath():ma(t,s,d,n);const e=!!s.pathSegment(t,h,{move:f,reverse:!0});g=f&&e,g||ma(t,s,c,n)}t.closePath(),t.fill(g?"evenodd":"nonzero"),t.restore()}}function pa(t,e,i,s){const n=e.chart.chartArea,{property:o,start:a,end:r}=s||{};if("x"===o||"y"===o){let e,s,l,h;"x"===o?(e=a,s=n.top,l=r,h=n.bottom):(e=n.left,s=a,l=n.right,h=r),t.beginPath(),i&&(e=Math.max(e,i.left),l=Math.min(l,i.right),s=Math.max(s,i.top),h=Math.min(h,i.bottom)),t.rect(e,s,l-e,h-s),t.clip()}}function ma(t,e,i,s){const n=e.interpolate(i,s);n&&t.lineTo(n.x,n.y)}var xa={id:"filler",afterDatasetsUpdate(t,e,i){const s=(t.data.datasets||[]).length,n=[];let o,a,r,l;for(a=0;a<s;++a)o=t.getDatasetMeta(a),r=o.dataset,l=null,r&&r.options&&r instanceof oo&&(l={visible:t.isDatasetVisible(a),index:a,fill:ra(r,a,s),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:r}),o.$filler=l,n.push(l);for(a=0;a<s;++a)l=n[a],l&&!1!==l.fill&&(l.fill=aa(n,a,i.propagate))},beforeDraw(t,e,i){const s="beforeDraw"===i.drawTime,n=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let e=n.length-1;e>=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 ba=(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 _a 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}=ba(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=ya(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}=ba(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+=ya(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;i<n.length;++i)if(s=n[i],tt(t,s.left,s.left+s.width)&&tt(e,s.top,s.top+s.height))return this.legendItems[i];return null}handleEvent(t){const e=this.options;if(!function(t,e){if(("mousemove"===t||"mouseout"===t)&&(e.onHover||e.onLeave))return!0;if(e.onClick&&("click"===t||"mouseup"===t))return!0;return!1}(t.type,e))return;const i=this._getLegendItemAt(t.x,t.y);if("mousemove"===t.type||"mouseout"===t.type){const o=this._hoveredItem,a=(n=i,null!==(s=o)&&null!==n&&s.datasetIndex===n.datasetIndex&&s.index===n.index);o&&!a&&d(e.onLeave,[t,o,this],this),this._hoveredItem=i,i&&!a&&d(e.onHover,[t,i,this],this)}else i&&d(e.onClick,[t,i,this],this);var s,n}}function ya(t,e){return e*(t.text?t.text.length:0)}var va={id:"legend",_element:_a,start(t,e,i){const s=t.legend=new _a({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s)},stop(t){ls.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,i){const s=t.legend;ls.configure(t,s,i),s.options=i},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,i){const s=e.datasetIndex,n=i.chart;n.isDatasetVisible(s)?(n.hide(s),e.hidden=!0):(n.show(s),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.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 Ma 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 wa={id:"title",_element:Ma,start(t,e,i){!function(t,e){const i=new Ma({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 ka=new WeakMap;var Sa={id:"subtitle",start(t,e,i){const s=new Ma({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),ka.set(t,s)},stop(t){ls.removeBox(t,ka.get(t)),ka.delete(t)},beforeUpdate(t,e,i){const s=ka.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 Pa={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;e<i;++e){const i=t[e].element;if(i&&i.hasValue()){const t=i.tooltipPosition();s.add(t.x),n+=t.y,++o}}if(0===o||0===s.size)return!1;return{x:[...s].reduce(((t,e)=>t+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<s;++i){const s=t[i].element;if(s&&s.hasValue()){const t=q(e,s.getCenterPoint());t<r&&(r=t,n=s)}}if(n){const t=n.tooltipPosition();o=t.x,a=t.y}return{x:o,y:a}}};function Da(t,e){return e&&(n(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Ca(t){return("string"==typeof t||t instanceof String)&&t.indexOf("\n")>-1?t.split("\n"):t}function Oa(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 Aa(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 Ta(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 La(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return i<s/2?"top":i>t.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Ta(t,e,i,s),yAlign:s}}function Ea(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:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ra(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 Ia(t){return Da([],Ca(t))}function za(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Fa={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<s)return i[e.dataIndex]}return""},afterTitle:e,beforeBody:e,beforeLabel:e,label(t){if(this&&this.options&&"dataset"===this.options.mode)return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const i=t.formattedValue;return s(i)||(e+=i),e},labelColor(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:e.borderColor,backgroundColor:e.backgroundColor,borderWidth:e.borderWidth,borderDash:e.borderDash,borderDashOffset:e.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:e.pointStyle,rotation:e.rotation}},afterLabel:e,afterBody:e,beforeFooter:e,footer:e,afterFooter:e};function Va(t,e,i,s){const n=t[e].call(i,s);return void 0===n?Fa[e].call(i,s):n}class Ba extends $s{static positioners=Pa;constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,i=this.options.setContext(this.getContext()),s=i.enabled&&e.options.animation&&i.animations,n=new Ts(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(n)),n}getContext(){return this.$context||(this.$context=(t=this.chart.getContext(),e=this,i=this._tooltipItems,Ci(t,{tooltip:e,tooltipItems:i,type:"tooltip"})));var t,e,i}getTitle(t,e){const{callbacks:i}=e,s=Va(i,"beforeTitle",this,t),n=Va(i,"title",this,t),o=Va(i,"afterTitle",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(o)),a}getBeforeBody(t,e){return Ia(Va(e.callbacks,"beforeBody",this,t))}getBody(t,e){const{callbacks:i}=e,s=[];return u(t,(t=>{const e={before:[],lines:[],after:[]},n=za(i,t);Da(e.before,Ca(Va(n,"beforeLabel",this,t))),Da(e.lines,Va(n,"label",this,t)),Da(e.after,Ca(Va(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ia(Va(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Va(i,"beforeFooter",this,t),n=Va(i,"footer",this,t),o=Va(i,"afterFooter",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(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;a<r;++a)l.push(Oa(this.chart,e[a]));return t.filter&&(l=l.filter(((e,s,n)=>t.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=za(t.callbacks,e);s.push(Va(i,"labelColor",this,e)),n.push(Va(i,"labelPointStyle",this,e)),o.push(Va(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=Pa[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=Aa(this,i),a=Object.assign({},t,e),r=La(this.chart,i,a),l=Ea(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=Ra(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;r<n;++r)e.fillText(s[r],l.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+a,r+1===n&&(t.y+=i.titleMarginBottom-a)}}_drawColorBox(t,e,i,s,n){const a=this.labelColors[i],r=this.labelPointStyles[i],{boxHeight:l,boxWidth:h}=n,c=Si(n.bodyFont),d=Ra(this,"left",n),u=s.x(d),f=l<c.lineHeight?(c.lineHeight-l)/2:0,g=e.y+f;if(n.usePointStyle){const e={radius:Math.min(h,l)/2,pointStyle:r.pointStyle,rotation:r.rotation,borderWidth:1},i=s.leftForLtr(u,h)+h/2,o=g+l/2;t.strokeStyle=n.multiKeyBackground,t.fillStyle=n.multiKeyBackground,Le(t,e,i,o),t.strokeStyle=a.borderColor,t.fillStyle=a.backgroundColor,Le(t,e,i,o)}else{t.lineWidth=o(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,t.strokeStyle=a.borderColor,t.setLineDash(a.borderDash||[]),t.lineDashOffset=a.borderDashOffset||0;const e=s.leftForLtr(u,h),i=s.leftForLtr(s.xPlus(u,1),h-2),r=wi(a.borderRadius);Object.values(r).some((t=>0!==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=Ra(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;y<M;++y){for(x=s[y],b=this.labelTextColors[y],e.fillStyle=b,u(x.before,p),_=x.lines,a&&_.length&&(this._drawColorBox(e,t,y,g,i),d=Math.max(c.lineHeight,r)),v=0,w=_.length;v<w;++v)p(_[v]),d=c.lineHeight;u(x.after,p)}f=0,d=c.lineHeight,u(this.afterBody,p),t.y-=n}drawFooter(t,e,i){const s=this.footer,n=s.length;let o,a;if(n){const r=Oi(i.rtl,this.x,this.width);for(t.x=Ra(this,i.footerAlign,i),t.y+=i.footerMarginTop,e.textAlign=r.textAlign(i.footerAlign),e.textBaseline="middle",o=Si(i.footerFont),e.fillStyle=i.footerColor,e.font=o.string,a=0;a<n;++a)e.fillText(s[a],r.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+i.footerSpacing}}drawBackground(t,e,i,s){const{xAlign:n,yAlign:o}=this,{x:a,y:r}=t,{width:l,height:h}=i,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(s.cornerRadius);e.fillStyle=s.backgroundColor,e.strokeStyle=s.borderColor,e.lineWidth=s.borderWidth,e.beginPath(),e.moveTo(a+c,r),"top"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+l-d,r),e.quadraticCurveTo(a+l,r,a+l,r+d),"center"===o&&"right"===n&&this.drawCaret(t,e,i,s),e.lineTo(a+l,r+h-f),e.quadraticCurveTo(a+l,r+h,a+l-f,r+h),"bottom"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+u,r+h),e.quadraticCurveTo(a,r+h,a,r+h-u),"center"===o&&"left"===n&&this.drawCaret(t,e,i,s),e.lineTo(a,r+c),e.quadraticCurveTo(a,r,a+c,r),e.closePath(),e.fill(),s.borderWidth>0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Pa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Aa(this,t),a=Object.assign({},i,this._size),r=La(e,t,a),l=Ea(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=Pa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Wa={id:"tooltip",_element:Ba,positioners:Pa,afterInit(t,e,i){i&&(t.tooltip=new Ba({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:Fa},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.js.map
diff --git a/frontend/debug-export.html b/frontend/src/debug-export.html
similarity index 96%
rename from frontend/debug-export.html
rename to frontend/src/debug-export.html
index f681e50..985327a 100644
--- a/frontend/debug-export.html
+++ b/frontend/src/debug-export.html
@@ -106,12 +106,14 @@
</div>
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n Configuration -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<script>
let warranties = [];
diff --git a/frontend/favicon.ico b/frontend/src/favicon.ico
similarity index 100%
rename from frontend/favicon.ico
rename to frontend/src/favicon.ico
diff --git a/frontend/src/file-utils.js b/frontend/src/file-utils.js
new file mode 100644
index 0000000..fcaa07f
--- /dev/null
+++ b/frontend/src/file-utils.js
@@ -0,0 +1,126 @@
+/**
+ * Utility functions for secure file handling
+ */
+
+/**
+ * Converts a file path to a secure API endpoint path
+ * @param {string} path - The file path to convert
+ * @returns {string} The secure API endpoint path
+ */
+function secureFilePath(path) {
+ if (!path) return '';
+
+ if (path.startsWith('uploads/')) {
+ return '/api/secure-file/' + path.substring(8);
+ }
+
+ if (path.startsWith('/uploads/')) {
+ return '/api/secure-file/' + path.substring(9);
+ }
+
+ return path;
+}
+
+/**
+ * Opens a file in a new tab with proper authentication
+ * @param {string} path - The file path to open
+ */
+function openSecureFile(path) {
+ if (!path) return;
+
+ const securePath = secureFilePath(path);
+ console.log('Opening file:', securePath);
+
+ // Try to get the token from different sources
+ const token = localStorage.getItem('auth_token');
+
+ if (!token) {
+ console.error('No authentication token available');
+ alert('You must be logged in to access files');
+ return;
+ }
+
+ // Create a link with target="_blank" and click it programmatically
+ const link = document.createElement('a');
+ link.href = securePath;
+ link.target = '_blank';
+
+ // Add a click event listener to inject the token
+ link.addEventListener('click', function(e) {
+ // Prevent the default navigation
+ e.preventDefault();
+
+ // Make a fetch request with the Authorization header
+ fetch(securePath, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP error! Status: ${response.status}`);
+ }
+ return response.blob();
+ })
+ .then(blob => {
+ // Create a URL for the blob and open it in a new window
+ const url = URL.createObjectURL(blob);
+ window.open(url, '_blank');
+ })
+ .catch(error => {
+ console.error('Error opening file:', error);
+ alert('Error opening file. Please try again or check if you are logged in.');
+ });
+ });
+
+ // Trigger the click event
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+}
+
+/**
+ * Downloads a file using the secure file endpoint
+ * @param {string} path - The file path to download
+ * @param {string} filename - The name to save the file as
+ */
+function downloadSecureFile(path, filename) {
+ if (!path) return;
+
+ const securePath = secureFilePath(path);
+ const token = localStorage.getItem('auth_token');
+
+ if (!token) {
+ console.error('No authentication token available');
+ alert('You must be logged in to download files');
+ return;
+ }
+
+ fetch(securePath, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP error! Status: ${response.status}`);
+ }
+ return response.blob();
+ })
+ .then(blob => {
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+ a.download = filename || path.split('/').pop();
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ })
+ .catch(error => {
+ console.error('Error downloading file:', error);
+ alert('Error downloading file. Please try again or check if you are logged in.');
+ });
+}
\ No newline at end of file
diff --git a/frontend/src/footer-content.js b/frontend/src/footer-content.js
new file mode 100644
index 0000000..362d6ef
--- /dev/null
+++ b/frontend/src/footer-content.js
@@ -0,0 +1,131 @@
+/**
+ * Footer Content Manager - Universal
+ * Manages the "Powered by" footer content across all pages
+ * Easy to customize footer text, links, and branding from one place
+ */
+
+(function() {
+ 'use strict';
+
+ // === FOOTER CONFIGURATION ===
+ // Edit these values to change footer content across all pages
+ const FOOTER_CONFIG = {
+ // Main footer text
+ text: 'Powered by',
+
+ // Link configuration
+ link: {
+ text: 'Warracker',
+ url: 'https://warracker.com',
+ target: '_blank',
+ rel: 'noopener noreferrer'
+ },
+
+ // Optional: Additional links or text
+ // Uncomment and customize as needed
+ /*
+ additionalContent: [
+ { type: 'text', content: ' | ' },
+ { type: 'link', text: 'Privacy Policy', url: '/privacy.html' },
+ { type: 'text', content: ' | ' },
+ { type: 'link', text: 'Terms of Service', url: '/terms.html' }
+ ]
+ */
+ };
+
+ // === FOOTER CONTENT GENERATION ===
+ function generateFooterContent() {
+ let footerHTML = `${FOOTER_CONFIG.text} `;
+
+ // Add main link
+ footerHTML += `<a href="${FOOTER_CONFIG.link.url}" target="${FOOTER_CONFIG.link.target}" rel="${FOOTER_CONFIG.link.rel}" id="warrackerFooterLink">${FOOTER_CONFIG.link.text}</a>`;
+
+ // Add additional content if configured
+ if (FOOTER_CONFIG.additionalContent) {
+ FOOTER_CONFIG.additionalContent.forEach(item => {
+ if (item.type === 'text') {
+ footerHTML += item.content;
+ } else if (item.type === 'link') {
+ const target = item.target || '_self';
+ const rel = item.rel || '';
+ footerHTML += `<a href="${item.url}" target="${target}" rel="${rel}">${item.text}</a>`;
+ }
+ });
+ }
+
+ return footerHTML;
+ }
+
+ // === FOOTER INITIALIZATION ===
+ function initFooterContent() {
+ const footer = document.getElementById('warrackerFooter');
+
+ if (!footer) {
+ console.warn('Footer element with ID "warrackerFooter" not found');
+ return;
+ }
+
+ // Generate and inject footer content
+ const footerContent = generateFooterContent();
+ footer.innerHTML = `<p>${footerContent}</p>`;
+
+ console.log('Footer content initialized successfully');
+ }
+
+ // === DYNAMIC FOOTER CREATION ===
+ // If no footer exists, create one
+ function createFooterIfMissing() {
+ let footer = document.getElementById('warrackerFooter');
+
+ if (!footer) {
+ footer = document.createElement('footer');
+ footer.className = 'warracker-footer';
+ footer.id = 'warrackerFooter';
+
+ // Insert before closing body tag
+ document.body.appendChild(footer);
+ console.log('Footer element created dynamically');
+ }
+
+ return footer;
+ }
+
+ // === PUBLIC API ===
+ // Expose functions for manual updates if needed
+ window.FooterContent = {
+ // Update footer content dynamically
+ update: function(newConfig) {
+ Object.assign(FOOTER_CONFIG, newConfig);
+ initFooterContent();
+ },
+
+ // Get current configuration
+ getConfig: function() {
+ return { ...FOOTER_CONFIG };
+ },
+
+ // Reinitialize footer
+ reinit: function() {
+ initFooterContent();
+ }
+ };
+
+ // === AUTO-INITIALIZATION ===
+ function init() {
+ // Ensure footer element exists
+ createFooterIfMissing();
+
+ // Initialize footer content
+ initFooterContent();
+ }
+
+ // Initialize when DOM is ready
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ // DOM is already loaded
+ init();
+ }
+
+ console.log('Footer Content Manager loaded');
+})();
\ No newline at end of file
diff --git a/frontend/src/footer-fix.js b/frontend/src/footer-fix.js
new file mode 100644
index 0000000..0fcbaaa
--- /dev/null
+++ b/frontend/src/footer-fix.js
@@ -0,0 +1,97 @@
+/**
+ * Footer Width Fix - Universal
+ * Ensures the Warracker footer spans full width across all pages
+ * Handles both light and dark themes automatically
+ */
+
+(function() {
+ 'use strict';
+
+ // Apply footer styles based on theme
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+
+ if (!footer) return; // Exit if footer doesn't exist on this page
+
+ // Detect dark mode
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' ||
+ document.documentElement.classList.contains('dark-mode') ||
+ document.body.classList.contains('dark-mode');
+
+ if (isDarkMode) {
+ // Dark mode styles without viewport-width hacks (prevents horizontal scrollbar)
+ footer.style.cssText = `
+ width: 100% !important;
+ margin-top: 50px !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ padding: 20px !important;
+ text-align: center !important;
+ border-top: 1px solid #444 !important;
+ background-color: #2d2d2d !important;
+ color: #e0e0e0 !important;
+ font-size: 0.9rem !important;
+ position: relative !important;
+ box-sizing: border-box !important;
+ `;
+ if (link) {
+ link.style.cssText = 'color: #4dabf7 !important; text-decoration: none !important; font-weight: 500 !important;';
+ }
+ } else {
+ // Light mode styles without viewport-width hacks (prevents horizontal scrollbar)
+ footer.style.cssText = `
+ width: 100% !important;
+ margin-top: 50px !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ padding: 20px !important;
+ text-align: center !important;
+ border-top: 1px solid #e0e0e0 !important;
+ background-color: #ffffff !important;
+ color: #333333 !important;
+ font-size: 0.9rem !important;
+ position: relative !important;
+ box-sizing: border-box !important;
+ `;
+ if (link) {
+ link.style.cssText = 'color: #3498db !important; text-decoration: none !important; font-weight: 500 !important;';
+ }
+ }
+ }
+
+ // Initialize footer styles when DOM is ready
+ function initFooterFix() {
+ applyFooterStyles();
+
+ // Watch for theme changes on document.documentElement
+ const observer = new MutationObserver(applyFooterStyles);
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme', 'class']
+ });
+
+ // Also watch body for theme changes (fallback)
+ observer.observe(document.body, {
+ attributes: true,
+ attributeFilter: ['class']
+ });
+
+ // Listen for custom theme change events if they exist
+ document.addEventListener('themeChanged', applyFooterStyles);
+ window.addEventListener('themeChanged', applyFooterStyles);
+ }
+
+ // Auto-initialize when DOM is loaded
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initFooterFix);
+ } else {
+ // DOM is already loaded
+ initFooterFix();
+ }
+
+ // Expose function globally in case manual calls are needed
+ window.applyFooterFix = applyFooterStyles;
+
+ console.log('Footer Fix loaded - Footer will span full width on all pages');
+})();
\ No newline at end of file
diff --git a/frontend/header-fix.css b/frontend/src/header-fix.css
similarity index 100%
rename from frontend/header-fix.css
rename to frontend/src/header-fix.css
diff --git a/frontend/img/favicon-16x16.png b/frontend/src/img/favicon-16x16.png
similarity index 100%
rename from frontend/img/favicon-16x16.png
rename to frontend/src/img/favicon-16x16.png
diff --git a/frontend/img/favicon-32x32.png b/frontend/src/img/favicon-32x32.png
similarity index 100%
rename from frontend/img/favicon-32x32.png
rename to frontend/src/img/favicon-32x32.png
diff --git a/frontend/img/favicon-512x512.png b/frontend/src/img/favicon-512x512.png
similarity index 100%
rename from frontend/img/favicon-512x512.png
rename to frontend/src/img/favicon-512x512.png
diff --git a/frontend/index.html b/frontend/src/index.html
similarity index 97%
rename from frontend/index.html
rename to frontend/src/index.html
index 1d70404..cf80354 100644
--- a/frontend/index.html
+++ b/frontend/src/index.html
@@ -2,45 +2,56 @@
<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
+ <script src="/auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js?v=20250119001"></script>
+
<!-- File utilities script for secure file handling -->
- <script src="file-utils.js?v=20250119001"></script>
+ <script src="/file-utils.js?v=20250119001"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Warracker - Warranty Tracker</title>
<!-- Add standard favicon.ico link -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<!-- Replace the old favicon link -->
<!-- <link rel="icon" type="image/png" href="img/favicon.png"> -->
<!-- Add new favicon links -->
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/store.js"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
+ <script type="module" src="/js/components/warrantyCard.js"></script>
+ <script type="module" src="/js/components/tag.js"></script>
+ <script type="module" src="/js/components/editModal.js"></script>
+ <script type="module" src="/js/components/modals.js"></script>
+ <script type="module" src="/js/components/claims.js"></script>
+ <script type="module" src="/js/components/notes.js"></script>
+ <script type="module" src="/js/components/paperless.js"></script>
+ <script type="module" src="/js/components/ui.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
+
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n Configuration -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Immediate authentication check script -->
<script>
@@ -95,7 +106,7 @@
</script>
<!-- Registration status check script -->
- <script src="registration-status.js?v=20250119001"></script>
+
</head>
<body>
<!-- Header -->
@@ -1325,8 +1336,8 @@
<div class="loading-spinner"></div>
</div>
- <script src="auth.js?v=20250119001"></script>
- <script src="script.js?v=20250119002"></script>
+
+ <script src="/script.js?v=20250119002" defer></script>
<script>
// Lightweight UI logic for Filter/Sort popovers (no change to core logic)
document.addEventListener('DOMContentLoaded', function () {
@@ -1635,10 +1646,10 @@
</script>
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
@@ -1684,5 +1695,23 @@
});
</script>
+<!-- Templates (do not affect layout) -->
+<template id="warranty-card-template">
+ <div class="warranty-card">
+ <div class="product-name-header">
+ <h3 class="warranty-title"></h3>
+ <div class="warranty-actions">
+ <button class="action-btn edit-btn" title="Edit"><i class="fas fa-edit"></i></button>
+ <button class="action-btn delete-btn" title="Delete"><i class="fas fa-trash"></i></button>
+ </div>
+ </div>
+ <div class="warranty-content">
+ <div class="warranty-info"></div>
+ </div>
+ <div class="warranty-status-row"><span></span></div>
+ </div>
+</template>
</body>
</html>
+
+</html>
diff --git a/frontend/src/js/components/claims.js b/frontend/src/js/components/claims.js
new file mode 100644
index 0000000..22b2d46
--- /dev/null
+++ b/frontend/src/js/components/claims.js
@@ -0,0 +1,186 @@
+function el(tag, className, text) {
+ const e = document.createElement(tag);
+ if (className) e.className = className;
+ if (text !== undefined && text !== null) e.textContent = text;
+ return e;
+}
+
+export function renderWarrantyInfo(container, warranty, formatDateFn) {
+ if (!container || !warranty) return;
+ container.textContent = '';
+ const card = el('div', 'warranty-info-card');
+ const title = el('h4', null, warranty.product_name || 'Unnamed Product');
+ const details = el('div', 'warranty-details');
+
+ const vendor = el('span');
+ const vendorIcon = el('i', 'fas fa-building');
+ vendor.appendChild(vendorIcon);
+ vendor.appendChild(document.createTextNode(' ' + (warranty.vendor || 'Unknown Vendor')));
+
+ const exp = el('span');
+ const calIcon = el('i', 'fas fa-calendar');
+ const expText = (typeof formatDateFn === 'function')
+ ? formatDateFn(warranty.expiration_date ? new Date(warranty.expiration_date) : null)
+ : (warranty.expiration_date || '');
+ exp.appendChild(calIcon);
+ exp.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('warranties.expires')) || 'Expires') + ': ' + expText));
+
+ const statusVal = warranty.status || 'unknown';
+ const status = el('span', `warranty-status status-${statusVal}`);
+ status.textContent = warranty.statusText || 'Unknown Status';
+
+ details.appendChild(vendor);
+ details.appendChild(exp);
+ details.appendChild(status);
+
+ card.appendChild(title);
+ card.appendChild(details);
+ container.appendChild(card);
+}
+
+function createClaimItem(claim, canEdit, formatDateFn) {
+ const item = el('div', 'claim-item');
+ item.dataset.claimId = String(claim.id);
+
+ const header = el('div', 'claim-header');
+ const info = el('div', 'claim-info');
+ const title = el('div', 'claim-title');
+ const strong = el('strong', null, claim.claim_number ? String(claim.claim_number) : `Claim #${claim.id}`);
+ title.appendChild(strong);
+
+ const statusClass = `claim-status-${String(claim.status || '').toLowerCase().replace(' ', '-')}`;
+ const badge = el('span', `claim-status-badge ${statusClass}`, claim.status || '');
+ title.appendChild(document.createTextNode(' '));
+ title.appendChild(badge);
+
+ const dateRow = el('div', 'claim-date');
+ const calIcon = el('i', 'fas fa-calendar');
+ dateRow.appendChild(calIcon);
+ const dateText = (typeof formatDateFn === 'function') ? formatDateFn(claim.claim_date ? new Date(claim.claim_date) : null) : (claim.claim_date || '');
+ dateRow.appendChild(document.createTextNode(' ' + dateText));
+
+ if (claim.resolution_date && String(claim.resolution_date).trim()) {
+ const resSpan = el('span');
+ resSpan.style.marginLeft = '10px';
+ const check = el('i', 'fas fa-check-circle');
+ resSpan.appendChild(check);
+ const resText = (typeof formatDateFn === 'function') ? formatDateFn(new Date(claim.resolution_date)) : claim.resolution_date;
+ resSpan.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('claims.resolved')) || 'Resolved') + ': ' + resText));
+ dateRow.appendChild(resSpan);
+ }
+
+ info.appendChild(title);
+ info.appendChild(dateRow);
+
+ const actions = el('div', 'claim-actions');
+ if (canEdit) {
+ const editBtn = el('button', 'btn btn-sm btn-secondary edit-claim-btn');
+ editBtn.dataset.claimId = String(claim.id);
+ const editIcon = el('i', 'fas fa-edit');
+ editBtn.appendChild(editIcon);
+ editBtn.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('actions.edit')) || 'Edit')));
+ const delBtn = el('button', 'btn btn-sm btn-danger delete-claim-btn');
+ delBtn.dataset.claimId = String(claim.id);
+ const delIcon = el('i', 'fas fa-trash');
+ delBtn.appendChild(delIcon);
+ delBtn.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('actions.delete')) || 'Delete')));
+ actions.appendChild(editBtn);
+ actions.appendChild(delBtn);
+ } else {
+ const ro = el('span', 'claim-readonly-indicator');
+ ro.style.color = 'var(--medium-gray)';
+ ro.style.fontSize = '0.9em';
+ const eye = el('i', 'fas fa-eye');
+ ro.appendChild(eye);
+ ro.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('actions.view_only')) || 'View Only')));
+ actions.appendChild(ro);
+ }
+
+ header.appendChild(info);
+ header.appendChild(actions);
+ item.appendChild(header);
+
+ if (claim.description) {
+ const desc = el('div', 'claim-description');
+ desc.textContent = claim.description;
+ item.appendChild(desc);
+ }
+ if (claim.resolution) {
+ const res = el('div', 'claim-resolution');
+ const strong = el('strong', null, ((window.i18next && window.i18next.t('claims.resolution')) || 'Resolution') + ': ');
+ res.appendChild(strong);
+ res.appendChild(document.createTextNode(claim.resolution));
+ item.appendChild(res);
+ }
+
+ return item;
+}
+
+export function renderClaimsList(container, claims = [], canEdit = false, formatDateFn) {
+ if (!container) return;
+ container.textContent = '';
+
+ if (!Array.isArray(claims) || claims.length === 0) {
+ const wrapper = el('div', 'no-claims-message');
+ wrapper.style.textAlign = 'center';
+ wrapper.style.padding = '40px';
+ const icon = el('i', 'fas fa-clipboard-list');
+ icon.style.fontSize = '3rem';
+ icon.style.color = 'var(--medium-gray)';
+ icon.style.marginBottom = '1rem';
+ const h4 = el('h4', null, (window.i18next && window.i18next.t('claims.no_claims_yet')) || 'No Claims Yet');
+ h4.style.color = 'var(--text-color)';
+ h4.style.marginBottom = '0.5rem';
+ const msg = canEdit ? ((window.i18next && window.i18next.t('claims.no_claims_message')) || 'Click "Add New Claim" to get started') : 'No claims have been filed for this warranty';
+ const p = el('p', null, msg);
+ p.style.color = 'var(--dark-gray)';
+ p.style.marginBottom = '0';
+ wrapper.appendChild(icon);
+ wrapper.appendChild(h4);
+ wrapper.appendChild(p);
+ container.appendChild(wrapper);
+ return;
+ }
+
+ claims.forEach(claim => {
+ container.appendChild(createClaimItem(claim, canEdit, formatDateFn));
+ });
+}
+
+export function renderClaimsLoading(container) {
+ if (!container) return;
+ container.textContent = '';
+ const wrap = el('div', 'loading-message');
+ wrap.style.textAlign = 'center';
+ wrap.style.padding = '20px';
+ const spinner = el('i', 'fas fa-spinner fa-spin');
+ wrap.appendChild(spinner);
+ wrap.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('claims.loading')) || 'Loading claims...')));
+ container.appendChild(wrap);
+}
+
+export function renderClaimsError(container, text) {
+ if (!container) return;
+ container.textContent = '';
+ const wrap = el('div', 'error-message');
+ wrap.style.textAlign = 'center';
+ wrap.style.padding = '20px';
+ wrap.style.color = 'var(--danger-color)';
+ const warn = el('i', 'fas fa-exclamation-triangle');
+ wrap.appendChild(warn);
+ wrap.appendChild(document.createTextNode(' ' + (text || 'Failed to load claims')));
+ container.appendChild(wrap);
+}
+
+// Global exposure
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.claims = {
+ renderWarrantyInfo,
+ renderClaimsList,
+ renderClaimsLoading,
+ renderClaimsError,
+ };
+}
+
+
diff --git a/frontend/src/js/components/editModal.js b/frontend/src/js/components/editModal.js
new file mode 100644
index 0000000..eff0d44
--- /dev/null
+++ b/frontend/src/js/components/editModal.js
@@ -0,0 +1,251 @@
+// Edit modal helper components (DOM-based, no innerHTML templates)
+
+function createElement(tag, className, text) {
+ const el = document.createElement(tag);
+ if (className) el.className = className;
+ if (text !== undefined && text !== null) el.textContent = text;
+ return el;
+}
+
+export function renderSerialNumbers(container, serialNumbers = [], i18n = window.i18next) {
+ if (!container) return;
+ while (container.firstChild) container.removeChild(container.firstChild);
+
+ const makeRow = (value = '', isFirst = false) => {
+ const row = createElement('div', 'serial-number-input');
+
+ const input = createElement('input', 'form-control');
+ input.type = 'text';
+ input.name = 'serial_numbers[]';
+ input.placeholder = i18n ? i18n.t('warranties.enter_serial_number') : 'Enter serial number';
+ input.value = value;
+ row.appendChild(input);
+
+ if (isFirst) {
+ const addBtn = createElement('button', 'btn btn-sm btn-primary add-serial-number');
+ addBtn.type = 'button';
+ // Use icon element for consistency
+ const icon = createElement('i', 'fas fa-plus');
+ addBtn.appendChild(icon);
+ addBtn.appendChild(document.createTextNode(' ' + (i18n ? i18n.t('warranties.add_serial_number') : 'Add Serial Number')));
+ row.appendChild(addBtn);
+ } else {
+ const removeBtn = createElement('button', 'btn btn-sm btn-danger remove-serial-number');
+ removeBtn.type = 'button';
+ const icon = createElement('i', 'fas fa-minus');
+ removeBtn.appendChild(icon);
+ removeBtn.appendChild(document.createTextNode(' ' + (i18n ? i18n.t('actions.delete') : 'Delete')));
+ removeBtn.addEventListener('click', () => {
+ row.remove();
+ });
+ row.appendChild(removeBtn);
+ }
+
+ return row;
+ };
+
+ if (!Array.isArray(serialNumbers) || serialNumbers.length === 0) {
+ container.appendChild(makeRow('', true));
+ } else {
+ container.appendChild(makeRow(serialNumbers[0] || '', true));
+ for (let i = 1; i < serialNumbers.length; i++) {
+ container.appendChild(makeRow(serialNumbers[i] || '', false));
+ }
+ }
+}
+
+function createCloudIcon() {
+ const cloud = createElement('i', 'fas fa-cloud');
+ cloud.style.color = '#4dabf7';
+ cloud.style.marginLeft = '4px';
+ cloud.style.fontSize = '0.8em';
+ cloud.title = 'Stored in Paperless-ngx';
+ return cloud;
+}
+
+function setElementChildren(el, children) {
+ if (!el) return;
+ while (el.firstChild) el.removeChild(el.firstChild);
+ children.forEach(child => el.appendChild(child));
+}
+
+export function renderCurrentInvoice(element, deleteBtn, warranty, i18n = window.i18next) {
+ if (!element) return;
+ const hasLocal = warranty.invoice_path && warranty.invoice_path !== 'null';
+ const hasPaperless = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
+
+ if (hasLocal) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_invoice') : 'Current invoice') + ': ';
+ const label = document.createTextNode(labelText);
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openSecureFile) window.openSecureFile(warranty.invoice_path);
+ });
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else if (hasPaperless) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_invoice') : 'Current invoice') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openPaperlessDocument) window.openPaperlessDocument(warranty.paperless_invoice_id, { user_id: warranty.user_id, id: warranty.id });
+ });
+ const cloud = createCloudIcon();
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, cloud, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else {
+ setElementChildren(element, [createElement('span', null, i18n ? i18n.t('warranties.no_invoice_uploaded') : 'No invoice uploaded')]);
+ if (deleteBtn) deleteBtn.style.display = 'none';
+ }
+}
+
+export function renderCurrentManual(element, deleteBtn, warranty, i18n = window.i18next) {
+ if (!element) return;
+ const hasLocal = warranty.manual_path && warranty.manual_path !== 'null';
+ const hasPaperless = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;
+
+ if (hasLocal) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_manual') : 'Current manual') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openSecureFile) window.openSecureFile(warranty.manual_path);
+ });
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else if (hasPaperless) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_manual') : 'Current manual') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openPaperlessDocument) window.openPaperlessDocument(warranty.paperless_manual_id, { user_id: warranty.user_id, id: warranty.id });
+ });
+ const cloud = createCloudIcon();
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, cloud, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else {
+ setElementChildren(element, [createElement('span', null, i18n ? i18n.t('warranties.no_manual_uploaded') : 'No manual uploaded')]);
+ if (deleteBtn) deleteBtn.style.display = 'none';
+ }
+}
+
+export function renderCurrentPhoto(element, deleteBtn, warranty, i18n = window.i18next) {
+ if (!element) return;
+ const hasLocal = warranty.product_photo_path && warranty.product_photo_path !== 'null';
+ const hasPaperless = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;
+
+ if (hasLocal) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_photo') : 'Current photo') + ': ';
+ const img = createElement('img', 'secure-image');
+ img.setAttribute('data-secure-src', `/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}`);
+ img.alt = 'Current Photo';
+ img.style.maxWidth = '100px';
+ img.style.maxHeight = '100px';
+ img.style.objectFit = 'cover';
+ img.style.borderRadius = '8px';
+ img.style.marginLeft = '10px';
+ img.style.border = '2px solid var(--border-color)';
+ img.onerror = () => { img.style.display = 'none'; };
+ const br = document.createElement('br');
+ const small = createElement('small', null, `(${i18n ? i18n.t('warranties.upload_new_photo_replace') : 'Upload a new photo to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), img, br, small]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else if (hasPaperless) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_photo') : 'Current photo') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openPaperlessDocument) window.openPaperlessDocument(warranty.paperless_photo_id, { user_id: warranty.user_id, id: warranty.id });
+ });
+ const cloud = createCloudIcon();
+ const br = document.createElement('br');
+ const small = createElement('small', null, `(${i18n ? i18n.t('warranties.upload_new_photo_replace') : 'Upload a new photo to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, cloud, br, small]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else {
+ setElementChildren(element, [createElement('span', null, i18n ? i18n.t('warranties.no_photo_uploaded') : 'No photo uploaded')]);
+ if (deleteBtn) deleteBtn.style.display = 'none';
+ }
+}
+
+export function renderCurrentOther(element, deleteBtn, warranty, i18n = window.i18next) {
+ if (!element) return;
+ const hasLocal = warranty.other_document_path && warranty.other_document_path !== 'null';
+ const hasPaperless = warranty.paperless_other_id && warranty.paperless_other_id !== null;
+
+ if (hasLocal) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_other_document') : 'Current files') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openSecureFile) window.openSecureFile(warranty.other_document_path);
+ });
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else if (hasPaperless) {
+ const span = createElement('span', 'text-success');
+ const icon = createElement('i', 'fas fa-check-circle');
+ const labelText = (i18n ? i18n.t('warranties.current_other_document') : 'Current files') + ': ';
+ const a = createElement('a', 'view-document-link', (i18n ? i18n.t('actions.view') : 'View'));
+ a.href = '#';
+ a.addEventListener('click', (e) => {
+ e.preventDefault();
+ if (window.openPaperlessDocument) window.openPaperlessDocument(warranty.paperless_other_id, { user_id: warranty.user_id, id: warranty.id });
+ });
+ const cloud = createCloudIcon();
+ const suffix = createElement('span', null, ` (${i18n ? i18n.t('warranties.upload_new_file_replace') : 'Upload a new file to replace'})`);
+ setElementChildren(span, [icon, document.createTextNode(' '), document.createTextNode(labelText), a, cloud, suffix]);
+ setElementChildren(element, [span]);
+ if (deleteBtn) deleteBtn.style.display = '';
+ } else {
+ setElementChildren(element, [createElement('span', null, i18n ? i18n.t('warranties.no_other_document_uploaded') : 'No files uploaded')]);
+ if (deleteBtn) deleteBtn.style.display = 'none';
+ }
+}
+
+// Expose globally
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.editModal = {
+ renderSerialNumbers,
+ renderCurrentInvoice,
+ renderCurrentManual,
+ renderCurrentPhoto,
+ renderCurrentOther,
+ };
+}
+
+
diff --git a/frontend/src/js/components/modals.js b/frontend/src/js/components/modals.js
new file mode 100644
index 0000000..ca315a5
--- /dev/null
+++ b/frontend/src/js/components/modals.js
@@ -0,0 +1,44 @@
+// Lightweight modal utilities and wrappers
+
+export function showModalById(modalId) {
+ const modal = document.getElementById(modalId);
+ if (modal) {
+ modal.classList.add('active');
+ }
+}
+
+export function hideModalById(modalId) {
+ const modal = document.getElementById(modalId);
+ if (modal) {
+ modal.classList.remove('active');
+ }
+}
+
+export function setText(selector, text) {
+ const el = document.querySelector(selector);
+ if (el) el.textContent = text || '';
+}
+
+export function openDeleteModal(productName) {
+ setText('#deleteProductName', productName || '');
+ showModalById('deleteModal');
+}
+
+export function openArchiveModal(productName) {
+ setText('#archiveProductName', productName || '');
+ showModalById('archiveModal');
+}
+
+// Non-module exposure
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.modals = {
+ showModalById,
+ hideModalById,
+ setText,
+ openDeleteModal,
+ openArchiveModal,
+ };
+}
+
+
diff --git a/frontend/src/js/components/notes.js b/frontend/src/js/components/notes.js
new file mode 100644
index 0000000..653d5ff
--- /dev/null
+++ b/frontend/src/js/components/notes.js
@@ -0,0 +1,55 @@
+function el(tag, className, text) {
+ const e = document.createElement(tag);
+ if (className) e.className = className;
+ if (text !== undefined && text !== null) e.textContent = text;
+ return e;
+}
+
+export function ensureNotesModal() {
+ if (document.getElementById('notesModal')) return;
+ const backdrop = el('div', 'modal-backdrop');
+ backdrop.id = 'notesModal';
+
+ const modal = el('div', 'modal');
+ modal.style.maxWidth = '500px';
+
+ const header = el('div', 'modal-header');
+ const title = el('h3', 'modal-title', (window.i18next && window.i18next.t('warranties.notes')) || 'Warranty Notes');
+ const closeBtn = el('button', 'close-btn');
+ closeBtn.id = 'closeNotesModal';
+ closeBtn.textContent = '×';
+ header.appendChild(title);
+ header.appendChild(closeBtn);
+
+ const body = el('div', 'modal-body');
+ const content = el('div'); content.id = 'notesModalContent'; content.style.whiteSpace = 'pre-line';
+ const textarea = el('textarea'); textarea.id = 'notesModalTextarea'; textarea.style.display = 'none'; textarea.style.width = '100%'; textarea.style.minHeight = '100px';
+ body.appendChild(content);
+ body.appendChild(textarea);
+
+ const footer = el('div', 'modal-footer'); footer.id = 'notesModalFooter';
+ const editBtn = el('button', 'btn btn-secondary', (window.i18next && window.i18next.t('actions.edit')) || 'Edit Notes'); editBtn.id = 'editNotesBtn';
+ const editWarrantyBtn = el('button', 'btn btn-info', (window.i18next && window.i18next.t('warranties.edit_warranty')) || 'Edit Warranty'); editWarrantyBtn.id = 'editWarrantyBtn';
+ const saveBtn = el('button', 'btn btn-primary', (window.i18next && window.i18next.t('actions.save')) || 'Save'); saveBtn.id = 'saveNotesBtn'; saveBtn.style.display = 'none';
+ const cancelBtn = el('button', 'btn btn-danger', (window.i18next && window.i18next.t('actions.cancel')) || 'Cancel'); cancelBtn.id = 'cancelEditNotesBtn'; cancelBtn.style.display = 'none';
+ footer.appendChild(editBtn);
+ footer.appendChild(editWarrantyBtn);
+ footer.appendChild(saveBtn);
+ footer.appendChild(cancelBtn);
+
+ modal.appendChild(header);
+ modal.appendChild(body);
+ modal.appendChild(footer);
+ backdrop.appendChild(modal);
+ document.body.appendChild(backdrop);
+
+ closeBtn.addEventListener('click', () => backdrop.classList.remove('active'));
+}
+
+// Global exposure
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.notes = { ensureNotesModal };
+}
+
+
diff --git a/frontend/src/js/components/paperless.js b/frontend/src/js/components/paperless.js
new file mode 100644
index 0000000..7272e65
--- /dev/null
+++ b/frontend/src/js/components/paperless.js
@@ -0,0 +1,100 @@
+function el(tag, className, text) {
+ const e = document.createElement(tag);
+ if (className) e.className = className;
+ if (text !== undefined && text !== null) e.textContent = text;
+ return e;
+}
+
+export function renderLoading(container) {
+ if (!container) return;
+ container.textContent = '';
+ const wrap = el('div', 'loading-message');
+ wrap.style.textAlign = 'center';
+ wrap.style.padding = '40px';
+ const spinner = el('i', 'fas fa-spinner fa-spin');
+ wrap.appendChild(spinner);
+ wrap.appendChild(document.createTextNode(' ' + ((window.i18next && window.i18next.t('paperless.loading_documents')) || 'Loading documents...')));
+ container.appendChild(wrap);
+}
+
+export function renderError(container, message) {
+ if (!container) return;
+ container.textContent = '';
+ const wrap = el('div', 'no-documents-message');
+ const icon = el('i', 'fas fa-exclamation-triangle');
+ const h4 = el('h4', null, (window.i18next && window.i18next.t('errors.error')) || 'Error');
+ const p = el('p', null, message || ((window.i18next && window.i18next.t('paperless.failed_to_load')) || 'Failed to load documents'));
+ wrap.appendChild(icon);
+ wrap.appendChild(h4);
+ wrap.appendChild(p);
+ container.appendChild(wrap);
+}
+
+function createDocItem(doc) {
+ const item = el('div', 'paperless-document-item');
+ item.dataset.id = String(doc.id);
+ item.addEventListener('click', () => {
+ if (window.selectPaperlessDocument) window.selectPaperlessDocument(doc.id);
+ });
+
+ const title = el('div', 'document-title', doc.title || '');
+ const meta = el('div', 'document-meta');
+ const createdDate = doc.created ? new Date(doc.created).toLocaleDateString() : '';
+ const fileType = doc.mime_type || 'Unknown';
+ const tags = Array.isArray(doc.tags) ? doc.tags : [];
+
+ const dateSpan = el('span');
+ dateSpan.appendChild(el('i', 'fas fa-calendar'));
+ dateSpan.appendChild(document.createTextNode(' ' + createdDate));
+ const typeSpan = el('span');
+ typeSpan.appendChild(el('i', 'fas fa-file'));
+ typeSpan.appendChild(document.createTextNode(' ' + fileType));
+ meta.appendChild(dateSpan);
+ meta.appendChild(typeSpan);
+ if (doc.correspondent) {
+ const corr = el('span');
+ corr.appendChild(el('i', 'fas fa-user'));
+ corr.appendChild(document.createTextNode(' ' + doc.correspondent));
+ meta.appendChild(corr);
+ }
+
+ item.appendChild(title);
+ item.appendChild(meta);
+
+ if (tags.length > 0) {
+ const tagsWrap = el('div', 'document-tags');
+ tags.forEach(t => {
+ const badge = el('span', 'document-tag', String(t));
+ tagsWrap.appendChild(badge);
+ });
+ item.appendChild(tagsWrap);
+ }
+
+ return item;
+}
+
+export function renderDocumentsList(container, documents = []) {
+ if (!container) return;
+ container.textContent = '';
+ if (!Array.isArray(documents) || documents.length === 0) {
+ const wrap = el('div', 'no-documents-message');
+ wrap.appendChild(el('i', 'fas fa-file-alt'));
+ wrap.appendChild(el('h4', null, (window.i18next && window.i18next.t('paperless.no_documents_found')) || 'No documents found'));
+ wrap.appendChild(el('p', null, (window.i18next && window.i18next.t('paperless.try_adjusting_filters')) || 'Try adjusting your search terms or filters.'));
+ container.appendChild(wrap);
+ return;
+ }
+ documents.forEach(doc => container.appendChild(createDocItem(doc)));
+}
+
+// Global exposure
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.paperless = {
+ renderLoading,
+ renderError,
+ renderDocumentsList,
+ };
+}
+
+
diff --git a/frontend/src/js/components/tag.js b/frontend/src/js/components/tag.js
new file mode 100644
index 0000000..e14bd5b
--- /dev/null
+++ b/frontend/src/js/components/tag.js
@@ -0,0 +1,42 @@
+export function createTag(name, color) {
+ const tagEl = document.createElement('span');
+ tagEl.className = 'tag';
+ if (color) {
+ tagEl.style.backgroundColor = color;
+ try {
+ const contrast = (window.getContrastColor ? window.getContrastColor(color) : null);
+ if (contrast) tagEl.style.color = contrast;
+ } catch (e) {
+ // fallback silently
+ }
+ }
+ tagEl.textContent = name || '';
+ return tagEl;
+}
+
+export function appendTags(cardElement, tags = []) {
+ if (!cardElement || !Array.isArray(tags) || tags.length === 0) return;
+ const tagsRow = document.createElement('div');
+ tagsRow.className = 'tags-row';
+ tags.forEach(tag => {
+ const el = createTag(tag?.name, tag?.color);
+ tagsRow.appendChild(el);
+ });
+
+ // Prefer to insert after document links row if present, else append at end of card
+ const docRow = cardElement.querySelector('.document-links-row');
+ if (docRow) {
+ docRow.insertAdjacentElement('afterend', tagsRow);
+ } else {
+ cardElement.appendChild(tagsRow);
+ }
+}
+
+// Expose globally for non-module consumers
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.createTag = createTag;
+ window.components.appendTags = appendTags;
+}
+
+
diff --git a/frontend/src/js/components/ui.js b/frontend/src/js/components/ui.js
new file mode 100644
index 0000000..38f083c
--- /dev/null
+++ b/frontend/src/js/components/ui.js
@@ -0,0 +1,27 @@
+function el(tag, className, text) {
+ const e = document.createElement(tag);
+ if (className) e.className = className;
+ if (text !== undefined && text !== null) e.textContent = text;
+ return e;
+}
+
+export function renderEmptyState(container, message) {
+ if (!container) return;
+ container.textContent = '';
+ const wrap = el('div', 'empty-state');
+ const icon = el('i', 'fas fa-box-open');
+ const h3 = el('h3', null, (window.t ? window.t('messages.no_warranties_found') : 'No warranties found'));
+ const p = el('p', null, message || (window.t ? window.t('messages.no_warranties_found_add_first') : 'No warranties yet. Add your first warranty to get started.'));
+ wrap.appendChild(icon);
+ wrap.appendChild(h3);
+ wrap.appendChild(p);
+ container.appendChild(wrap);
+}
+
+// Global expose
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.ui = { renderEmptyState };
+}
+
+
diff --git a/frontend/src/js/components/warrantyCard.js b/frontend/src/js/components/warrantyCard.js
new file mode 100644
index 0000000..2fa37b3
--- /dev/null
+++ b/frontend/src/js/components/warrantyCard.js
@@ -0,0 +1,53 @@
+const template = document.getElementById('warranty-card-template');
+
+export function createWarrantyCard(warranty, options = {}) {
+ const { eventHandlers = {}, actionsHtml = '', contentHtml = '', statusText = '', statusClass = '', rootModifierClass = '' } = options;
+ if (!template) {
+ const fallback = document.createElement('div');
+ fallback.className = 'warranty-card';
+ fallback.textContent = warranty?.product_name || 'Warranty';
+ return fallback;
+ }
+
+ const card = template.content.cloneNode(true).firstElementChild;
+ if (rootModifierClass) {
+ card.className = `warranty-card ${rootModifierClass}`;
+ }
+
+ const title = card.querySelector('.warranty-title');
+ if (title) {
+ const name = warranty?.product_name || 'Unnamed Product';
+ title.textContent = name;
+ title.title = name;
+ }
+
+ const actions = card.querySelector('.warranty-actions');
+ if (actions && actionsHtml) actions.innerHTML = actionsHtml;
+
+ const info = card.querySelector('.warranty-info');
+ if (info && contentHtml) info.innerHTML = contentHtml;
+
+ const statusRow = card.querySelector('.warranty-status-row');
+ if (statusRow) {
+ const span = statusRow.querySelector('span');
+ if (span && statusText) span.textContent = statusText;
+ if (statusClass) statusRow.className = `warranty-status-row status-${statusClass}`;
+ }
+
+ const deleteBtn = card.querySelector('.delete-btn');
+ if (deleteBtn && eventHandlers.onDelete) {
+ deleteBtn.addEventListener('click', () => eventHandlers.onDelete(warranty.id, warranty.product_name));
+ }
+ const editBtn = card.querySelector('.edit-btn');
+ if (editBtn && eventHandlers.onEdit) {
+ editBtn.addEventListener('click', () => eventHandlers.onEdit(warranty));
+ }
+
+ return card;
+}
+
+// Non-module exposure
+if (typeof window !== 'undefined') {
+ window.components = window.components || {};
+ window.components.createWarrantyCard = createWarrantyCard;
+}
diff --git a/frontend/src/js/i18n-debug.js b/frontend/src/js/i18n-debug.js
new file mode 100644
index 0000000..d3684af
--- /dev/null
+++ b/frontend/src/js/i18n-debug.js
@@ -0,0 +1,36 @@
+// Debug script to test i18next CDN loading
+console.log('=== i18next Debug Script ===');
+
+// Check if CDN scripts are loaded
+setTimeout(() => {
+ console.log('Checking i18next libraries:');
+ console.log('- i18next:', typeof i18next !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+ console.log('- i18nextHttpBackend:', typeof i18nextHttpBackend !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+ console.log('- i18nextBrowserLanguageDetector:', typeof i18nextBrowserLanguageDetector !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+
+ // Test basic fetch to translation file
+ fetch('/locales/en/translation.json')
+ .then(response => {
+ console.log('Translation file fetch status:', response.status);
+ return response.json();
+ })
+ .then(data => {
+ console.log('Translation file loaded successfully, keys:', Object.keys(data).slice(0, 5));
+ })
+ .catch(error => {
+ console.error('Failed to load translation file:', error);
+ });
+
+ // Test API endpoint
+ fetch('/api/locales')
+ .then(response => {
+ console.log('Locales API status:', response.status);
+ return response.json();
+ })
+ .then(data => {
+ console.log('Locales API response:', data);
+ })
+ .catch(error => {
+ console.error('Failed to load locales API:', error);
+ });
+}, 2000); // Wait 2 seconds for CDN scripts to load
\ No newline at end of file
diff --git a/frontend/src/js/i18n.js b/frontend/src/js/i18n.js
new file mode 100644
index 0000000..f178ea3
--- /dev/null
+++ b/frontend/src/js/i18n.js
@@ -0,0 +1,469 @@
+/**
+ * i18next Configuration and Initialization
+ * Handles frontend localization with offline support
+ */
+
+// Global i18n object to make translation functions available
+window.i18n = {};
+
+// Supported languages
+const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar', 'ru', 'uk', 'zh_CN', 'zh_HK', 'ja', 'pt', 'ko', 'tr', 'pl', 'he'];
+const DEFAULT_LANGUAGE = 'en';
+const RTL_LANGUAGES = ['ar', 'fa', 'he']; // Arabic, Persian, and Hebrew are RTL languages
+
+/**
+ * Initialize i18next with configuration
+ */
+async function initializeI18n() {
+ console.log('Initializing i18next...');
+
+ // Debug: Check if required libraries are loaded
+ if (typeof i18next === 'undefined') {
+ console.error('i18next library not loaded');
+ return;
+ }
+
+ console.log('i18next library loaded successfully');
+
+ // Check optional libraries
+ const hasHttpBackend = typeof i18nextHttpBackend !== 'undefined';
+ const hasLanguageDetector = typeof i18nextBrowserLanguageDetector !== 'undefined';
+
+ console.log('Optional libraries:', {
+ httpBackend: hasHttpBackend,
+ languageDetector: hasLanguageDetector
+ });
+
+ try {
+ // Get current language from various sources
+ const savedLanguage = getCurrentLanguage();
+ console.log('Initial language detected:', savedLanguage);
+
+ // Load translations manually since HttpBackend might not be available
+ const translations = await loadTranslations(savedLanguage);
+
+ // Configure i18next with or without plugins
+ let i18nextInstance = i18next;
+
+ if (hasLanguageDetector) {
+ i18nextInstance = i18nextInstance.use(i18nextBrowserLanguageDetector);
+ }
+
+ await i18nextInstance.init({
+ fallbackLng: DEFAULT_LANGUAGE,
+ supportedLngs: SUPPORTED_LANGUAGES,
+ debug: false,
+
+ // Set initial language and resources
+ lng: savedLanguage,
+ resources: translations,
+
+ // Language detection configuration (only if detector is available)
+ ...(hasLanguageDetector && {
+ detection: {
+ order: ['cookie', 'localStorage', 'navigator', 'htmlTag'],
+ lookupCookie: 'lang',
+ lookupLocalStorage: 'preferred_language',
+ caches: ['cookie', 'localStorage'],
+ cookieOptions: {
+ path: '/',
+ maxAge: 365 * 24 * 60 * 60 // 1 year
+ }
+ }
+ }),
+
+ // Interpolation options
+ interpolation: {
+ escapeValue: false
+ }
+ });
+
+ // Store translation function globally
+ window.i18n.t = i18next.t.bind(i18next);
+ window.i18n.changeLanguage = changeLanguage;
+ window.i18n.getCurrentLanguage = getCurrentLanguage;
+ window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
+
+ // Initialize page translations
+ translatePage();
+
+ // Set initial page direction
+ updatePageDirection(i18next.language);
+
+ // Set up language change listener
+ i18next.on('languageChanged', (lng) => {
+ console.log('Language changed to:', lng);
+ translatePage();
+ updateLanguageAttribute(lng);
+ updatePageDirection(lng);
+ });
+
+ console.log('i18next initialized successfully with language:', i18next.language);
+
+ // Dispatch event to notify other scripts that i18n is ready
+ window.dispatchEvent(new CustomEvent('i18nReady', {
+ detail: {
+ language: i18next.language,
+ t: window.i18n.t
+ }
+ }));
+
+ } catch (error) {
+ console.error('Failed to initialize i18next:', error);
+ // Fallback to default language without i18next
+ window.i18n.t = (key) => key; // Return key as fallback
+ window.i18n.changeLanguage = () => {};
+ window.i18n.getCurrentLanguage = () => DEFAULT_LANGUAGE;
+ window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
+
+ // Still dispatch event so other scripts know i18n is "ready" (even with fallback)
+ window.dispatchEvent(new CustomEvent('i18nReady', {
+ detail: {
+ language: DEFAULT_LANGUAGE,
+ t: window.i18n.t,
+ fallback: true
+ }
+ }));
+ }
+}
+
+/**
+ * Load translations for a specific language
+ */
+async function loadTranslations(language) {
+ console.log(`loadTranslations called for language: ${language}`);
+ const translations = {};
+
+ try {
+ // Load primary language
+ const url = `/locales/${language}/translation.json?v=${Date.now()}`;
+ console.log(`Fetching translations from: ${url}`);
+ const response = await fetch(url);
+ console.log(`Fetch response status: ${response.status} for language: ${language}`);
+
+ if (response.ok) {
+ const data = await response.json();
+ translations[language] = { translation: data };
+ const keyCount = Object.keys(data).length;
+ console.log(`Successfully loaded ${keyCount} translation keys for ${language}:`, Object.keys(data).slice(0, 5));
+ } else {
+ console.warn(`Failed to load translations for ${language}, status: ${response.status}`);
+ console.warn(`Response text:`, await response.text().catch(() => 'Could not read response text'));
+ }
+ } catch (error) {
+ console.error(`Error loading translations for ${language}:`, error);
+ }
+
+ // Always load fallback language if different
+ if (language !== DEFAULT_LANGUAGE) {
+ try {
+ const fallbackUrl = `/locales/${DEFAULT_LANGUAGE}/translation.json?v=${Date.now()}`;
+ console.log(`Loading fallback language from: ${fallbackUrl}`);
+ const fallbackResponse = await fetch(fallbackUrl);
+ console.log(`Fallback fetch response status: ${fallbackResponse.status}`);
+
+ if (fallbackResponse.ok) {
+ const fallbackData = await fallbackResponse.json();
+ translations[DEFAULT_LANGUAGE] = { translation: fallbackData };
+ const fallbackKeyCount = Object.keys(fallbackData).length;
+ console.log(`Loaded ${fallbackKeyCount} fallback translation keys for ${DEFAULT_LANGUAGE}`);
+ }
+ } catch (error) {
+ console.error(`Error loading fallback translations:`, error);
+ }
+ }
+
+ console.log(`loadTranslations completed. Languages loaded: ${Object.keys(translations)}`);
+ return translations;
+}
+
+/**
+ * Get current language from storage or user preferences
+ */
+function getCurrentLanguage() {
+ // URL override (e.g., ?lang=tr)
+ try {
+ const params = new URLSearchParams(window.location.search);
+ const urlLang = params.get('lang');
+ if (urlLang && SUPPORTED_LANGUAGES.includes(urlLang)) {
+ setCookie('lang', urlLang, 365);
+ localStorage.setItem('preferred_language', urlLang);
+ return urlLang;
+ }
+ } catch (e) {
+ // Ignore URL parsing errors and continue
+ }
+ // Check cookie first
+ const cookieLang = getCookie('lang');
+ if (cookieLang && SUPPORTED_LANGUAGES.includes(cookieLang)) {
+ return cookieLang;
+ }
+
+ // Check localStorage
+ const storedLang = localStorage.getItem('preferred_language');
+ if (storedLang && SUPPORTED_LANGUAGES.includes(storedLang)) {
+ return storedLang;
+ }
+
+ // Check user preferences from API if authenticated
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ if (userInfo.preferred_language && SUPPORTED_LANGUAGES.includes(userInfo.preferred_language)) {
+ return userInfo.preferred_language;
+ }
+
+ // Fallback to browser language or default
+ const browserLang = navigator.language?.split('-')[0];
+ return SUPPORTED_LANGUAGES.includes(browserLang) ? browserLang : DEFAULT_LANGUAGE;
+}
+
+/**
+ * Change language and persist preference
+ */
+async function changeLanguage(language) {
+ console.log('changeLanguage called with:', language);
+
+ if (!SUPPORTED_LANGUAGES.includes(language)) {
+ console.warn('Unsupported language:', language);
+ return;
+ }
+
+ try {
+ console.log('Loading translations for language:', language);
+ // Load translations for the new language
+ const translations = await loadTranslations(language);
+ console.log('Translations loaded:', Object.keys(translations));
+
+ // Add new language resources to i18next
+ for (const [lng, resources] of Object.entries(translations)) {
+ console.log('Adding resource bundle for language:', lng);
+ i18next.addResourceBundle(lng, 'translation', resources.translation, true, true);
+ }
+
+ // Change language in i18next
+ console.log('Changing i18next language to:', language);
+ await i18next.changeLanguage(language);
+ console.log('i18next language changed successfully to:', i18next.language);
+
+ // Persist to cookie and localStorage
+ setCookie('lang', language, 365);
+ localStorage.setItem('preferred_language', language);
+ console.log('Language preference saved to cookie and localStorage:', language);
+
+ // Update user preference in backend if authenticated
+ if (localStorage.getItem('auth_token')) {
+ try {
+ await saveLanguagePreference(language);
+ console.log('Language preference saved to backend');
+ } catch (error) {
+ console.warn('Failed to save language preference to backend:', error);
+ }
+ }
+
+ // Dispatch event for other components
+ window.dispatchEvent(new CustomEvent('languageChanged', { detail: { language } }));
+ console.log('languageChanged event dispatched for:', language);
+
+ } catch (error) {
+ console.error('Failed to change language:', error);
+ throw error; // Re-throw to let calling code handle it
+ }
+}
+
+/**
+ * Save language preference to backend
+ */
+async function saveLanguagePreference(language) {
+ const token = localStorage.getItem('auth_token');
+ if (!token) return;
+
+ const response = await fetch('/api/auth/user/language-preference', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ preferred_language: language })
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to save language preference');
+ }
+}
+
+/**
+ * Translate all elements on the current page
+ */
+function translatePage() {
+ if (!window.i18n.t) {
+ console.warn('Translation function not available, skipping translation');
+ return;
+ }
+
+ console.log('Starting page translation...');
+ let translatedCount = 0;
+
+ // Update dynamic titles that are set by JavaScript
+ updateDynamicTitles();
+
+ // Translate elements with data-i18n attribute
+ document.querySelectorAll('[data-i18n]').forEach(element => {
+ const raw = element.getAttribute('data-i18n');
+ let handled = false;
+
+ // Support syntax like [placeholder]warranties.search_placeholder
+ const attrMatch = raw && raw.match(/^\s*\[(\w+)\]\s*(.+)$/);
+ if (attrMatch) {
+ const attrName = attrMatch[1];
+ const key = attrMatch[2];
+ const translation = window.i18n.t(key);
+ if (translation && translation !== key) {
+ element.setAttribute(attrName, translation);
+ translatedCount++;
+ handled = true;
+ }
+ }
+
+ if (!handled) {
+ const key = raw;
+ const translation = window.i18n.t(key);
+ if (translation && translation !== key) {
+ if (element.tagName === 'INPUT' && (element.type === 'text' || element.type === 'email' || element.type === 'password')) {
+ element.placeholder = translation;
+ } else if (element.hasAttribute('title')) {
+ element.title = translation;
+ } else {
+ element.textContent = translation;
+ }
+ translatedCount++;
+ } else {
+ console.warn(`No translation found for key: ${key}`);
+ }
+ }
+ });
+
+ // Translate elements with data-i18n-html attribute (allows HTML content)
+ document.querySelectorAll('[data-i18n-html]').forEach(element => {
+ const key = element.getAttribute('data-i18n-html');
+ const translation = window.i18n.t(key);
+ element.innerHTML = translation;
+ });
+
+ // Translate elements with data-i18n-title attribute
+ document.querySelectorAll('[data-i18n-title]').forEach(element => {
+ const key = element.getAttribute('data-i18n-title');
+ const translation = window.i18n.t(key);
+ element.title = translation;
+ });
+
+ // Translate elements with data-i18n-placeholder attribute
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
+ const key = element.getAttribute('data-i18n-placeholder');
+ const translation = window.i18n.t(key);
+ if (translation && translation !== key) {
+ element.placeholder = translation;
+ translatedCount++;
+ }
+ });
+
+ console.log(`Page translation completed. Translated ${translatedCount} elements.`);
+
+ // Re-process warranties to update status text and labels if warranties exist
+ if (typeof warranties !== 'undefined' && warranties && warranties.length > 0) {
+ console.log(`[i18n.js] Re-processing ${warranties.length} warranties after language change`);
+ // Re-process each warranty to update status text with new language
+ warranties = warranties.map(warranty => {
+ if (typeof processWarrantyData === 'function') {
+ return processWarrantyData(warranty);
+ }
+ return warranty;
+ });
+ // Re-render warranties with new translations
+ if (typeof applyFilters === 'function') {
+ applyFilters();
+ }
+ }
+}
+
+/**
+ * Update dynamic titles that are set by JavaScript
+ */
+function updateDynamicTitles() {
+ // Update warranties panel title on index.html
+ if (typeof updateWarrantiesPanelTitle === 'function' && typeof isGlobalView !== 'undefined') {
+ updateWarrantiesPanelTitle(isGlobalView);
+ }
+
+ // Update dashboard title on status.html
+ if (typeof updateDashboardTitle === 'function') {
+ updateDashboardTitle();
+ }
+
+ // Re-process warranty cards if they exist (for dynamic status text)
+ if (typeof processAllWarranties === 'function') {
+ processAllWarranties();
+ }
+}
+
+/**
+ * Update HTML lang attribute
+ */
+function updateLanguageAttribute(language) {
+ document.documentElement.lang = language;
+}
+
+/**
+ * Update page direction for RTL languages
+ */
+function updatePageDirection(language) {
+ const isRTL = RTL_LANGUAGES.includes(language);
+ const htmlElement = document.documentElement;
+ const bodyElement = document.body;
+
+ if (isRTL) {
+ htmlElement.dir = 'rtl';
+ htmlElement.setAttribute('data-rtl', 'true');
+ bodyElement.classList.add('rtl');
+ console.log(`Applied RTL direction for language: ${language}`);
+ } else {
+ htmlElement.dir = 'ltr';
+ htmlElement.removeAttribute('data-rtl');
+ bodyElement.classList.remove('rtl');
+ console.log(`Applied LTR direction for language: ${language}`);
+ }
+}
+
+/**
+ * Utility function to get cookie value
+ */
+function getCookie(name) {
+ const value = `; ${document.cookie}`;
+ const parts = value.split(`; ${name}=`);
+ if (parts.length === 2) return parts.pop().split(';').shift();
+ return null;
+}
+
+/**
+ * Utility function to set cookie
+ */
+function setCookie(name, value, days) {
+ const expires = new Date();
+ expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
+ document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
+}
+
+/**
+ * Add translation helper for dynamic content
+ */
+function t(key, options = {}) {
+ return window.i18n.t ? window.i18n.t(key, options) : key;
+}
+
+// Expose translation function globally
+window.t = t;
+
+// Initialize when DOM is ready
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initializeI18n);
+} else {
+ initializeI18n();
+}
diff --git a/frontend/src/js/lib/i18next.min.js b/frontend/src/js/lib/i18next.min.js
new file mode 100644
index 0000000..1978709
--- /dev/null
+++ b/frontend/src/js/lib/i18next.min.js
@@ -0,0 +1 @@
+!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).i18next=e()}(this,(function(){"use strict";const t={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console&&console[t]&&console[t].apply(console,e)}};class e{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.init(t,e)}init(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=s.prefix||"i18next:",this.logger=e||t,this.options=s,this.debug=s.debug}log(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"log","",!0)}warn(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"warn","",!0)}error(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"error","")}deprecate(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(t,e,s,i){return i&&!this.debug?null:("string"==typeof t[0]&&(t[0]=`${s}${this.prefix} ${t[0]}`),this.logger[e](t))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return(t=t||this.options).prefix=t.prefix||this.prefix,new e(this.logger,t)}}var s=new e;class i{constructor(){this.observers={}}on(t,e){return t.split(" ").forEach((t=>{this.observers[t]=this.observers[t]||[],this.observers[t].push(e)})),this}off(t,e){this.observers[t]&&(e?this.observers[t]=this.observers[t].filter((t=>t!==e)):delete this.observers[t])}emit(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];if(this.observers[t]){[].concat(this.observers[t]).forEach((t=>{t(...s)}))}if(this.observers["*"]){[].concat(this.observers["*"]).forEach((e=>{e.apply(e,[t,...s])}))}}}function n(){let t,e;const s=new Promise(((s,i)=>{t=s,e=i}));return s.resolve=t,s.reject=e,s}function o(t){return null==t?"":""+t}function r(t,e,s){function i(t){return t&&t.indexOf("###")>-1?t.replace(/###/g,"."):t}function n(){return!t||"string"==typeof t}const o="string"!=typeof e?[].concat(e):e.split(".");for(;o.length>1;){if(n())return{};const e=i(o.shift());!t[e]&&s&&(t[e]=new s),t=Object.prototype.hasOwnProperty.call(t,e)?t[e]:{}}return n()?{}:{obj:t,k:i(o.shift())}}function a(t,e,s){const{obj:i,k:n}=r(t,e,Object);i[n]=s}function l(t,e){const{obj:s,k:i}=r(t,e);if(s)return s[i]}function u(t,e,s){for(const i in e)"__proto__"!==i&&"constructor"!==i&&(i in t?"string"==typeof t[i]||t[i]instanceof String||"string"==typeof e[i]||e[i]instanceof String?s&&(t[i]=e[i]):u(t[i],e[i],s):t[i]=e[i]);return t}function h(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var c={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function p(t){return"string"==typeof t?t.replace(/[&<>"'\/]/g,(t=>c[t])):t}const g=[" ",",","?","!",";"];function d(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(!t)return;if(t[e])return t[e];const i=e.split(s);let n=t;for(let t=0;t<i.length;++t){if(!n)return;if("string"==typeof n[i[t]]&&t+1<i.length)return;if(void 0===n[i[t]]){let o=2,r=i.slice(t,t+o).join(s),a=n[r];for(;void 0===a&&i.length>t+o;)o++,r=i.slice(t,t+o).join(s),a=n[r];if(void 0===a)return;if(null===a)return null;if(e.endsWith(r)){if("string"==typeof a)return a;if(r&&"string"==typeof a[r])return a[r]}const l=i.slice(t+o).join(s);return l?d(a,l,s):void 0}n=n[i[t]]}return n}function f(t){return t&&t.indexOf("_")>0?t.replace("_","-"):t}class m extends i{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const e=this.options.ns.indexOf(t);e>-1&&this.options.ns.splice(e,1)}getResource(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const n=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,o=void 0!==i.ignoreJSONStructure?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let r=[t,e];s&&"string"!=typeof s&&(r=r.concat(s)),s&&"string"==typeof s&&(r=r.concat(n?s.split(n):s)),t.indexOf(".")>-1&&(r=t.split("."));const a=l(this.data,r);return a||!o||"string"!=typeof s?a:d(this.data&&this.data[t]&&this.data[t][e],s,n)}addResource(t,e,s,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1};const o=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator;let r=[t,e];s&&(r=r.concat(o?s.split(o):s)),t.indexOf(".")>-1&&(r=t.split("."),i=e,e=r[1]),this.addNamespaces(e),a(this.data,r,i),n.silent||this.emit("added",t,e,s,i)}addResources(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(const i in s)"string"!=typeof s[i]&&"[object Array]"!==Object.prototype.toString.apply(s[i])||this.addResource(t,e,i,s[i],{silent:!0});i.silent||this.emit("added",t,e,s)}addResourceBundle(t,e,s,i,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},r=[t,e];t.indexOf(".")>-1&&(r=t.split("."),i=s,s=e,e=r[1]),this.addNamespaces(e);let h=l(this.data,r)||{};i?u(h,s,n):h={...h,...s},a(this.data,r,h),o.silent||this.emit("added",t,e,s)}removeResourceBundle(t,e){this.hasResourceBundle(t,e)&&delete this.data[t][e],this.removeNamespaces(e),this.emit("removed",t,e)}hasResourceBundle(t,e){return void 0!==this.getResource(t,e)}getResourceBundle(t,e){return e||(e=this.options.defaultNS),"v1"===this.options.compatibilityAPI?{...this.getResource(t,e)}:this.getResource(t,e)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const e=this.getDataByLanguage(t);return!!(e&&Object.keys(e)||[]).find((t=>e[t]&&Object.keys(e[t]).length>0))}toJSON(){return this.data}}var y={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,i,n){return t.forEach((t=>{this.processors[t]&&(e=this.processors[t].process(e,s,i,n))})),e}};const v={};class b extends i{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;super(),i=t,n=this,["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"].forEach((t=>{i[t]&&(n[t]=i[t])})),this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=s.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==t)return!1;const s=this.resolve(t,e);return s&&void 0!==s.res}extractFromKey(t,e){let s=void 0!==e.nsSeparator?e.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");const i=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator;let n=e.ns||this.options.defaultNS||[];const o=s&&t.indexOf(s)>-1,r=!(this.options.userDefinedKeySeparator||e.keySeparator||this.options.userDefinedNsSeparator||e.nsSeparator||function(t,e,s){e=e||"",s=s||"";const i=g.filter((t=>e.indexOf(t)<0&&s.indexOf(t)<0));if(0===i.length)return!0;const n=new RegExp(`(${i.map((t=>"?"===t?"\\?":t)).join("|")})`);let o=!n.test(t);if(!o){const e=t.indexOf(s);e>0&&!n.test(t.substring(0,e))&&(o=!0)}return o}(t,s,i));if(o&&!r){const e=t.match(this.interpolator.nestingRegexp);if(e&&e.length>0)return{key:t,namespaces:n};const o=t.split(s);(s!==i||s===i&&this.options.ns.indexOf(o[0])>-1)&&(n=o.shift()),t=o.join(i)}return"string"==typeof n&&(n=[n]),{key:t,namespaces:n}}translate(t,e,s){if("object"!=typeof e&&this.options.overloadTranslationOptionHandler&&(e=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof e&&(e={...e}),e||(e={}),null==t)return"";Array.isArray(t)||(t=[String(t)]);const i=void 0!==e.returnDetails?e.returnDetails:this.options.returnDetails,n=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator,{key:o,namespaces:r}=this.extractFromKey(t[t.length-1],e),a=r[r.length-1],l=e.lng||this.language,u=e.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l&&"cimode"===l.toLowerCase()){if(u){const t=e.nsSeparator||this.options.nsSeparator;return i?{res:`${a}${t}${o}`,usedKey:o,exactUsedKey:o,usedLng:l,usedNS:a,usedParams:this.getUsedParamsDetails(e)}:`${a}${t}${o}`}return i?{res:o,usedKey:o,exactUsedKey:o,usedLng:l,usedNS:a,usedParams:this.getUsedParamsDetails(e)}:o}const h=this.resolve(t,e);let c=h&&h.res;const p=h&&h.usedKey||o,g=h&&h.exactUsedKey||o,d=Object.prototype.toString.apply(c),f=void 0!==e.joinArrays?e.joinArrays:this.options.joinArrays,m=!this.i18nFormat||this.i18nFormat.handleAsObject;if(m&&c&&("string"!=typeof c&&"boolean"!=typeof c&&"number"!=typeof c)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(d)<0&&("string"!=typeof f||"[object Array]"!==d)){if(!e.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const t=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,c,{...e,ns:r}):`key '${o} (${this.language})' returned an object instead of string.`;return i?(h.res=t,h.usedParams=this.getUsedParamsDetails(e),h):t}if(n){const t="[object Array]"===d,s=t?[]:{},i=t?g:p;for(const t in c)if(Object.prototype.hasOwnProperty.call(c,t)){const o=`${i}${n}${t}`;s[t]=this.translate(o,{...e,joinArrays:!1,ns:r}),s[t]===o&&(s[t]=c[t])}c=s}}else if(m&&"string"==typeof f&&"[object Array]"===d)c=c.join(f),c&&(c=this.extendTranslation(c,t,e,s));else{let i=!1,r=!1;const u=void 0!==e.count&&"string"!=typeof e.count,p=b.hasDefaultValue(e),g=u?this.pluralResolver.getSuffix(l,e.count,e):"",d=e.ordinal&&u?this.pluralResolver.getSuffix(l,e.count,{ordinal:!1}):"",f=e[`defaultValue${g}`]||e[`defaultValue${d}`]||e.defaultValue;!this.isValidLookup(c)&&p&&(i=!0,c=f),this.isValidLookup(c)||(r=!0,c=o);const m=(e.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&r?void 0:c,y=p&&f!==c&&this.options.updateMissing;if(r||i||y){if(this.logger.log(y?"updateKey":"missingKey",l,a,o,y?f:c),n){const t=this.resolve(o,{...e,keySeparator:!1});t&&t.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let t=[];const s=this.languageUtils.getFallbackCodes(this.options.fallbackLng,e.lng||this.language);if("fallback"===this.options.saveMissingTo&&s&&s[0])for(let e=0;e<s.length;e++)t.push(s[e]);else"all"===this.options.saveMissingTo?t=this.languageUtils.toResolveHierarchy(e.lng||this.language):t.push(e.lng||this.language);const i=(t,s,i)=>{const n=p&&i!==c?i:m;this.options.missingKeyHandler?this.options.missingKeyHandler(t,a,s,n,y,e):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(t,a,s,n,y,e),this.emit("missingKey",t,a,s,c)};this.options.saveMissing&&(this.options.saveMissingPlurals&&u?t.forEach((t=>{this.pluralResolver.getSuffixes(t,e).forEach((s=>{i([t],o+s,e[`defaultValue${s}`]||f)}))})):i(t,o,f))}c=this.extendTranslation(c,t,e,h,s),r&&c===o&&this.options.appendNamespaceToMissingKey&&(c=`${a}:${o}`),(r||i)&&this.options.parseMissingKeyHandler&&(c="v1"!==this.options.compatibilityAPI?this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${a}:${o}`:o,i?c:void 0):this.options.parseMissingKeyHandler(c))}return i?(h.res=c,h.usedParams=this.getUsedParamsDetails(e),h):c}extendTranslation(t,e,s,i,n){var o=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const r="string"==typeof t&&(s&&s.interpolation&&void 0!==s.interpolation.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let a;if(r){const e=t.match(this.interpolator.nestingRegexp);a=e&&e.length}let l=s.replace&&"string"!=typeof s.replace?s.replace:s;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),t=this.interpolator.interpolate(t,l,s.lng||this.language,s),r){const e=t.match(this.interpolator.nestingRegexp);a<(e&&e.length)&&(s.nest=!1)}!s.lng&&"v1"!==this.options.compatibilityAPI&&i&&i.res&&(s.lng=i.usedLng),!1!==s.nest&&(t=this.interpolator.nest(t,(function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return n&&n[0]===i[0]&&!s.context?(o.logger.warn(`It seems you are nesting recursively key: ${i[0]} in key: ${e[0]}`),null):o.translate(...i,e)}),s)),s.interpolation&&this.interpolator.reset()}const r=s.postProcess||this.options.postProcess,a="string"==typeof r?[r]:r;return null!=t&&a&&a.length&&!1!==s.applyPostProcessor&&(t=y.handle(a,t,e,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),t}resolve(t){let e,s,i,n,o,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof t&&(t=[t]),t.forEach((t=>{if(this.isValidLookup(e))return;const a=this.extractFromKey(t,r),l=a.key;s=l;let u=a.namespaces;this.options.fallbackNS&&(u=u.concat(this.options.fallbackNS));const h=void 0!==r.count&&"string"!=typeof r.count,c=h&&!r.ordinal&&0===r.count&&this.pluralResolver.shouldUseIntlApi(),p=void 0!==r.context&&("string"==typeof r.context||"number"==typeof r.context)&&""!==r.context,g=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);u.forEach((t=>{this.isValidLookup(e)||(o=t,!v[`${g[0]}-${t}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(o)&&(v[`${g[0]}-${t}`]=!0,this.logger.warn(`key "${s}" for languages "${g.join(", ")}" won't get resolved as namespace "${o}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach((s=>{if(this.isValidLookup(e))return;n=s;const o=[l];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(o,l,s,t,r);else{let t;h&&(t=this.pluralResolver.getSuffix(s,r.count,r));const e=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(o.push(l+t),r.ordinal&&0===t.indexOf(i)&&o.push(l+t.replace(i,this.options.pluralSeparator)),c&&o.push(l+e)),p){const s=`${l}${this.options.contextSeparator}${r.context}`;o.push(s),h&&(o.push(s+t),r.ordinal&&0===t.indexOf(i)&&o.push(s+t.replace(i,this.options.pluralSeparator)),c&&o.push(s+e))}}let a;for(;a=o.pop();)this.isValidLookup(e)||(i=a,e=this.getResource(s,t,a,r))})))}))})),{res:e,usedKey:s,exactUsedKey:i,usedLng:n,usedNS:o}}isValidLookup(t){return!(void 0===t||!this.options.returnNull&&null===t||!this.options.returnEmptyString&&""===t)}getResource(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,e,s,i):this.resourceStore.getResource(t,e,s,i)}getUsedParamsDetails(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=t.replace&&"string"!=typeof t.replace;let i=s?t.replace:t;if(s&&void 0!==t.count&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!s){i={...i};for(const t of e)delete i[t]}return i}static hasDefaultValue(t){const e="defaultValue";for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&e===s.substring(0,12)&&void 0!==t[s])return!0;return!1}}function x(t){return t.charAt(0).toUpperCase()+t.slice(1)}class S{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=s.create("languageUtils")}getScriptPartFromCode(t){if(!(t=f(t))||t.indexOf("-")<0)return null;const e=t.split("-");return 2===e.length?null:(e.pop(),"x"===e[e.length-1].toLowerCase()?null:this.formatLanguageCode(e.join("-")))}getLanguagePartFromCode(t){if(!(t=f(t))||t.indexOf("-")<0)return t;const e=t.split("-");return this.formatLanguageCode(e[0])}formatLanguageCode(t){if("string"==typeof t&&t.indexOf("-")>-1){const e=["hans","hant","latn","cyrl","cans","mong","arab"];let s=t.split("-");return this.options.lowerCaseLng?s=s.map((t=>t.toLowerCase())):2===s.length?(s[0]=s[0].toLowerCase(),s[1]=s[1].toUpperCase(),e.indexOf(s[1].toLowerCase())>-1&&(s[1]=x(s[1].toLowerCase()))):3===s.length&&(s[0]=s[0].toLowerCase(),2===s[1].length&&(s[1]=s[1].toUpperCase()),"sgn"!==s[0]&&2===s[2].length&&(s[2]=s[2].toUpperCase()),e.indexOf(s[1].toLowerCase())>-1&&(s[1]=x(s[1].toLowerCase())),e.indexOf(s[2].toLowerCase())>-1&&(s[2]=x(s[2].toLowerCase()))),s.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let e;return t.forEach((t=>{if(e)return;const s=this.formatLanguageCode(t);this.options.supportedLngs&&!this.isSupportedCode(s)||(e=s)})),!e&&this.options.supportedLngs&&t.forEach((t=>{if(e)return;const s=this.getLanguagePartFromCode(t);if(this.isSupportedCode(s))return e=s;e=this.options.supportedLngs.find((t=>t===s?t:t.indexOf("-")<0&&s.indexOf("-")<0?void 0:0===t.indexOf(s)?t:void 0))})),e||(e=this.getFallbackCodes(this.options.fallbackLng)[0]),e}getFallbackCodes(t,e){if(!t)return[];if("function"==typeof t&&(t=t(e)),"string"==typeof t&&(t=[t]),"[object Array]"===Object.prototype.toString.apply(t))return t;if(!e)return t.default||[];let s=t[e];return s||(s=t[this.getScriptPartFromCode(e)]),s||(s=t[this.formatLanguageCode(e)]),s||(s=t[this.getLanguagePartFromCode(e)]),s||(s=t.default),s||[]}toResolveHierarchy(t,e){const s=this.getFallbackCodes(e||this.options.fallbackLng||[],t),i=[],n=t=>{t&&(this.isSupportedCode(t)?i.push(t):this.logger.warn(`rejecting language code not found in supportedLngs: ${t}`))};return"string"==typeof t&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?("languageOnly"!==this.options.load&&n(this.formatLanguageCode(t)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&n(this.getScriptPartFromCode(t)),"currentOnly"!==this.options.load&&n(this.getLanguagePartFromCode(t))):"string"==typeof t&&n(this.formatLanguageCode(t)),s.forEach((t=>{i.indexOf(t)<0&&n(this.formatLanguageCode(t))})),i}}let k=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],L={1:function(t){return Number(t>1)},2:function(t){return Number(1!=t)},3:function(t){return 0},4:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},5:function(t){return Number(0==t?0:1==t?1:2==t?2:t%100>=3&&t%100<=10?3:t%100>=11?4:5)},6:function(t){return Number(1==t?0:t>=2&&t<=4?1:2)},7:function(t){return Number(1==t?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},8:function(t){return Number(1==t?0:2==t?1:8!=t&&11!=t?2:3)},9:function(t){return Number(t>=2)},10:function(t){return Number(1==t?0:2==t?1:t<7?2:t<11?3:4)},11:function(t){return Number(1==t||11==t?0:2==t||12==t?1:t>2&&t<20?2:3)},12:function(t){return Number(t%10!=1||t%100==11)},13:function(t){return Number(0!==t)},14:function(t){return Number(1==t?0:2==t?1:3==t?2:3)},15:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&(t%100<10||t%100>=20)?1:2)},16:function(t){return Number(t%10==1&&t%100!=11?0:0!==t?1:2)},17:function(t){return Number(1==t||t%10==1&&t%100!=11?0:1)},18:function(t){return Number(0==t?0:1==t?1:2)},19:function(t){return Number(1==t?0:0==t||t%100>1&&t%100<11?1:t%100>10&&t%100<20?2:3)},20:function(t){return Number(1==t?0:0==t||t%100>0&&t%100<20?1:2)},21:function(t){return Number(t%100==1?1:t%100==2?2:t%100==3||t%100==4?3:0)},22:function(t){return Number(1==t?0:2==t?1:(t<0||t>10)&&t%10==0?2:3)}};const O=["v1","v2","v3"],w=["v4"],N={zero:0,one:1,two:2,few:3,many:4,other:5};class R{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.languageUtils=t,this.options=e,this.logger=s.create("pluralResolver"),this.options.compatibilityJSON&&!w.includes(this.options.compatibilityJSON)||"undefined"!=typeof Intl&&Intl.PluralRules||(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=function(){const t={};return k.forEach((e=>{e.lngs.forEach((s=>{t[s]={numbers:e.nr,plurals:L[e.fc]}}))})),t}()}addRule(t,e){this.rules[t]=e}getRule(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(f(t),{type:e.ordinal?"ordinal":"cardinal"})}catch(t){return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getRule(t,e);return this.shouldUseIntlApi()?s&&s.resolvedOptions().pluralCategories.length>1:s&&s.numbers.length>1}getPluralFormsOfKey(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.getSuffixes(t,s).map((t=>`${e}${t}`))}getSuffixes(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getRule(t,e);return s?this.shouldUseIntlApi()?s.resolvedOptions().pluralCategories.sort(((t,e)=>N[t]-N[e])).map((t=>`${this.options.prepend}${e.ordinal?`ordinal${this.options.prepend}`:""}${t}`)):s.numbers.map((s=>this.getSuffix(t,s,e))):[]}getSuffix(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=this.getRule(t,s);return i?this.shouldUseIntlApi()?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${i.select(e)}`:this.getSuffixRetroCompatible(i,e):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,e){const s=t.noAbs?t.plurals(e):t.plurals(Math.abs(e));let i=t.numbers[s];this.options.simplifyPluralSuffix&&2===t.numbers.length&&1===t.numbers[0]&&(2===i?i="plural":1===i&&(i=""));const n=()=>this.options.prepend&&i.toString()?this.options.prepend+i.toString():i.toString();return"v1"===this.options.compatibilityJSON?1===i?"":"number"==typeof i?`_plural_${i.toString()}`:n():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===t.numbers.length&&1===t.numbers[0]?n():this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString()}shouldUseIntlApi(){return!O.includes(this.options.compatibilityJSON)}}function $(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:".",n=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],o=function(t,e,s){const i=l(t,s);return void 0!==i?i:l(e,s)}(t,e,s);return!o&&n&&"string"==typeof s&&(o=d(t,s,i),void 0===o&&(o=d(e,s,i))),o}class P{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.logger=s.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(t=>t),this.init(t)}init(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const e=t.interpolation;this.escape=void 0!==e.escape?e.escape:p,this.escapeValue=void 0===e.escapeValue||e.escapeValue,this.useRawValueToEscape=void 0!==e.useRawValueToEscape&&e.useRawValueToEscape,this.prefix=e.prefix?h(e.prefix):e.prefixEscaped||"{{",this.suffix=e.suffix?h(e.suffix):e.suffixEscaped||"}}",this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||",",this.unescapePrefix=e.unescapeSuffix?"":e.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":e.unescapeSuffix||"",this.nestingPrefix=e.nestingPrefix?h(e.nestingPrefix):e.nestingPrefixEscaped||h("$t("),this.nestingSuffix=e.nestingSuffix?h(e.nestingSuffix):e.nestingSuffixEscaped||h(")"),this.nestingOptionsSeparator=e.nestingOptionsSeparator?e.nestingOptionsSeparator:e.nestingOptionsSeparator||",",this.maxReplaces=e.maxReplaces?e.maxReplaces:1e3,this.alwaysFormat=void 0!==e.alwaysFormat&&e.alwaysFormat,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=`${this.prefix}(.+?)${this.suffix}`;this.regexp=new RegExp(t,"g");const e=`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;this.regexpUnescape=new RegExp(e,"g");const s=`${this.nestingPrefix}(.+?)${this.nestingSuffix}`;this.nestingRegexp=new RegExp(s,"g")}interpolate(t,e,s,i){let n,r,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(t){return t.replace(/\$/g,"$$$$")}const h=t=>{if(t.indexOf(this.formatSeparator)<0){const n=$(e,l,t,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(n,void 0,s,{...i,...e,interpolationkey:t}):n}const n=t.split(this.formatSeparator),o=n.shift().trim(),r=n.join(this.formatSeparator).trim();return this.format($(e,l,o,this.options.keySeparator,this.options.ignoreJSONStructure),r,s,{...i,...e,interpolationkey:o})};this.resetRegExp();const c=i&&i.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i&&i.interpolation&&void 0!==i.interpolation.skipOnVariables?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:t=>u(t)},{regex:this.regexp,safeValue:t=>this.escapeValue?u(this.escape(t)):u(t)}].forEach((e=>{for(a=0;n=e.regex.exec(t);){const s=n[1].trim();if(r=h(s),void 0===r)if("function"==typeof c){const e=c(t,n,i);r="string"==typeof e?e:""}else if(i&&Object.prototype.hasOwnProperty.call(i,s))r="";else{if(p){r=n[0];continue}this.logger.warn(`missed to pass in variable ${s} for interpolating ${t}`),r=""}else"string"==typeof r||this.useRawValueToEscape||(r=o(r));const l=e.safeValue(r);if(t=t.replace(n[0],l),p?(e.regex.lastIndex+=r.length,e.regex.lastIndex-=n[0].length):e.regex.lastIndex=0,a++,a>=this.maxReplaces)break}})),t}nest(t,e){let s,i,n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};function a(t,e){const s=this.nestingOptionsSeparator;if(t.indexOf(s)<0)return t;const i=t.split(new RegExp(`${s}[ ]*{`));let o=`{${i[1]}`;t=i[0],o=this.interpolate(o,n);const r=o.match(/'/g),a=o.match(/"/g);(r&&r.length%2==0&&!a||a.length%2!=0)&&(o=o.replace(/'/g,'"'));try{n=JSON.parse(o),e&&(n={...e,...n})}catch(e){return this.logger.warn(`failed parsing options string in nesting for key ${t}`,e),`${t}${s}${o}`}return delete n.defaultValue,t}for(;s=this.nestingRegexp.exec(t);){let l=[];n={...r},n=n.replace&&"string"!=typeof n.replace?n.replace:n,n.applyPostProcessor=!1,delete n.defaultValue;let u=!1;if(-1!==s[0].indexOf(this.formatSeparator)&&!/{.*}/.test(s[1])){const t=s[1].split(this.formatSeparator).map((t=>t.trim()));s[1]=t.shift(),l=t,u=!0}if(i=e(a.call(this,s[1].trim(),n),n),i&&s[0]===t&&"string"!=typeof i)return i;"string"!=typeof i&&(i=o(i)),i||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),i=""),u&&(i=l.reduce(((t,e)=>this.format(t,e,r.lng,{...r,interpolationkey:s[1].trim()})),i.trim())),t=t.replace(s[0],i),this.regexp.lastIndex=0}return t}}function C(t){const e={};return function(s,i,n){const o=i+JSON.stringify(n);let r=e[o];return r||(r=t(f(i),n),e[o]=r),r(s)}}class j{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.logger=s.create("formatter"),this.options=t,this.formats={number:C(((t,e)=>{const s=new Intl.NumberFormat(t,{...e});return t=>s.format(t)})),currency:C(((t,e)=>{const s=new Intl.NumberFormat(t,{...e,style:"currency"});return t=>s.format(t)})),datetime:C(((t,e)=>{const s=new Intl.DateTimeFormat(t,{...e});return t=>s.format(t)})),relativetime:C(((t,e)=>{const s=new Intl.RelativeTimeFormat(t,{...e});return t=>s.format(t,e.range||"day")})),list:C(((t,e)=>{const s=new Intl.ListFormat(t,{...e});return t=>s.format(t)}))},this.init(t)}init(t){const e=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||","}add(t,e){this.formats[t.toLowerCase().trim()]=e}addCached(t,e){this.formats[t.toLowerCase().trim()]=C(e)}format(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e.split(this.formatSeparator).reduce(((t,e)=>{const{formatName:n,formatOptions:o}=function(t){let e=t.toLowerCase().trim();const s={};if(t.indexOf("(")>-1){const i=t.split("(");e=i[0].toLowerCase().trim();const n=i[1].substring(0,i[1].length-1);"currency"===e&&n.indexOf(":")<0?s.currency||(s.currency=n.trim()):"relativetime"===e&&n.indexOf(":")<0?s.range||(s.range=n.trim()):n.split(";").forEach((t=>{if(!t)return;const[e,...i]=t.split(":"),n=i.join(":").trim().replace(/^'+|'+$/g,"");s[e.trim()]||(s[e.trim()]=n),"false"===n&&(s[e.trim()]=!1),"true"===n&&(s[e.trim()]=!0),isNaN(n)||(s[e.trim()]=parseInt(n,10))}))}return{formatName:e,formatOptions:s}}(e);if(this.formats[n]){let e=t;try{const r=i&&i.formatParams&&i.formatParams[i.interpolationkey]||{},a=r.locale||r.lng||i.locale||i.lng||s;e=this.formats[n](t,a,{...o,...i,...r})}catch(t){this.logger.warn(t)}return e}return this.logger.warn(`there was no format function for ${n}`),t}),t)}}class E extends i{constructor(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};super(),this.backend=t,this.store=e,this.services=i,this.languageUtils=i.languageUtils,this.options=n,this.logger=s.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=n.maxParallelReads||10,this.readingCalls=0,this.maxRetries=n.maxRetries>=0?n.maxRetries:5,this.retryTimeout=n.retryTimeout>=1?n.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(i,n.backend,n)}queueLoad(t,e,s,i){const n={},o={},r={},a={};return t.forEach((t=>{let i=!0;e.forEach((e=>{const r=`${t}|${e}`;!s.reload&&this.store.hasResourceBundle(t,e)?this.state[r]=2:this.state[r]<0||(1===this.state[r]?void 0===o[r]&&(o[r]=!0):(this.state[r]=1,i=!1,void 0===o[r]&&(o[r]=!0),void 0===n[r]&&(n[r]=!0),void 0===a[e]&&(a[e]=!0)))})),i||(r[t]=!0)})),(Object.keys(n).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(n),pending:Object.keys(o),toLoadLanguages:Object.keys(r),toLoadNamespaces:Object.keys(a)}}loaded(t,e,s){const i=t.split("|"),n=i[0],o=i[1];e&&this.emit("failedLoading",n,o,e),s&&this.store.addResourceBundle(n,o,s),this.state[t]=e?-1:2;const a={};this.queue.forEach((s=>{!function(t,e,s,i){const{obj:n,k:o}=r(t,e,Object);n[o]=n[o]||[],i&&(n[o]=n[o].concat(s)),i||n[o].push(s)}(s.loaded,[n],o),function(t,e){void 0!==t.pending[e]&&(delete t.pending[e],t.pendingCount--)}(s,t),e&&s.errors.push(e),0!==s.pendingCount||s.done||(Object.keys(s.loaded).forEach((t=>{a[t]||(a[t]={});const e=s.loaded[t];e.length&&e.forEach((e=>{void 0===a[t][e]&&(a[t][e]=!0)}))})),s.done=!0,s.errors.length?s.callback(s.errors):s.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((t=>!t.done))}read(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.retryTimeout,o=arguments.length>5?arguments[5]:void 0;if(!t.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:t,ns:e,fcName:s,tried:i,wait:n,callback:o});this.readingCalls++;const r=(r,a)=>{if(this.readingCalls--,this.waitingReads.length>0){const t=this.waitingReads.shift();this.read(t.lng,t.ns,t.fcName,t.tried,t.wait,t.callback)}r&&a&&i<this.maxRetries?setTimeout((()=>{this.read.call(this,t,e,s,i+1,2*n,o)}),n):o(r,a)},a=this.backend[s].bind(this.backend);if(2!==a.length)return a(t,e,r);try{const s=a(t,e);s&&"function"==typeof s.then?s.then((t=>r(null,t))).catch(r):r(null,s)}catch(t){r(t)}}prepareLoading(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();"string"==typeof t&&(t=this.languageUtils.toResolveHierarchy(t)),"string"==typeof e&&(e=[e]);const n=this.queueLoad(t,e,s,i);if(!n.toLoad.length)return n.pending.length||i(),null;n.toLoad.forEach((t=>{this.loadOne(t)}))}load(t,e,s){this.prepareLoading(t,e,{},s)}reload(t,e,s){this.prepareLoading(t,e,{reload:!0},s)}loadOne(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const s=t.split("|"),i=s[0],n=s[1];this.read(i,n,"read",void 0,void 0,((s,o)=>{s&&this.logger.warn(`${e}loading namespace ${n} for language ${i} failed`,s),!s&&o&&this.logger.log(`${e}loaded namespace ${n} for language ${i}`,o),this.loaded(t,s,o)}))}saveMissing(t,e,s,i,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(e))this.logger.warn(`did not save key "${s}" as the namespace "${e}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");else if(null!=s&&""!==s){if(this.backend&&this.backend.create){const a={...o,isUpdate:n},l=this.backend.create.bind(this.backend);if(l.length<6)try{let n;n=5===l.length?l(t,e,s,i,a):l(t,e,s,i),n&&"function"==typeof n.then?n.then((t=>r(null,t))).catch(r):r(null,n)}catch(t){r(t)}else l(t,e,s,i,r,a)}t&&t[0]&&this.store.addResource(t[0],e,s,i)}}}function F(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){let e={};if("object"==typeof t[1]&&(e=t[1]),"string"==typeof t[1]&&(e.defaultValue=t[1]),"string"==typeof t[2]&&(e.tDescription=t[2]),"object"==typeof t[2]||"object"==typeof t[3]){const s=t[3]||t[2];Object.keys(s).forEach((t=>{e[t]=s[t]}))}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function I(t){return"string"==typeof t.ns&&(t.ns=[t.ns]),"string"==typeof t.fallbackLng&&(t.fallbackLng=[t.fallbackLng]),"string"==typeof t.fallbackNS&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&t.supportedLngs.indexOf("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t}function D(){}class V extends i{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;var i;if(super(),this.options=I(t),this.services={},this.logger=s,this.modules={external:[]},i=this,Object.getOwnPropertyNames(Object.getPrototypeOf(i)).forEach((t=>{"function"==typeof i[t]&&(i[t]=i[t].bind(i))})),e&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,e),this;setTimeout((()=>{this.init(t,e)}),0)}}init(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;"function"==typeof e&&(i=e,e={}),!e.defaultNS&&!1!==e.defaultNS&&e.ns&&("string"==typeof e.ns?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const o=F();function r(t){return t?"function"==typeof t?new t:t:null}if(this.options={...o,...this.options,...I(e)},"v1"!==this.options.compatibilityAPI&&(this.options.interpolation={...o.interpolation,...this.options.interpolation}),void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator),!this.options.isClone){let e;this.modules.logger?s.init(r(this.modules.logger),this.options):s.init(null,this.options),this.modules.formatter?e=this.modules.formatter:"undefined"!=typeof Intl&&(e=j);const i=new S(this.options);this.store=new m(this.options.resources,this.options);const n=this.services;n.logger=s,n.resourceStore=this.store,n.languageUtils=i,n.pluralResolver=new R(i,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),!e||this.options.interpolation.format&&this.options.interpolation.format!==o.interpolation.format||(n.formatter=r(e),n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new P(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new E(r(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on("*",(function(e){for(var s=arguments.length,i=new Array(s>1?s-1:0),n=1;n<s;n++)i[n-1]=arguments[n];t.emit(e,...i)})),this.modules.languageDetector&&(n.languageDetector=r(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=r(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new b(this.services,this.options),this.translator.on("*",(function(e){for(var s=arguments.length,i=new Array(s>1?s-1:0),n=1;n<s;n++)i[n-1]=arguments[n];t.emit(e,...i)})),this.modules.external.forEach((t=>{t.init&&t.init(this)}))}if(this.format=this.options.interpolation.format,i||(i=D),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const t=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);t.length>0&&"dev"!==t[0]&&(this.options.lng=t[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((e=>{this[e]=function(){return t.store[e](...arguments)}}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((e=>{this[e]=function(){return t.store[e](...arguments),t}}));const a=n(),l=()=>{const t=(t,e)=>{this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(e),i(t,e)};if(this.languages&&"v1"!==this.options.compatibilityAPI&&!this.isInitialized)return t(null,this.t.bind(this));this.changeLanguage(this.options.lng,t)};return this.options.resources||!this.options.initImmediate?l():setTimeout(l,0),a}loadResources(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:D;const s="string"==typeof t?t:this.language;if("function"==typeof t&&(e=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&"cimode"===s.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return e();const t=[],i=e=>{if(!e)return;if("cimode"===e)return;this.services.languageUtils.toResolveHierarchy(e).forEach((e=>{"cimode"!==e&&t.indexOf(e)<0&&t.push(e)}))};if(s)i(s);else{this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((t=>i(t)))}this.options.preload&&this.options.preload.forEach((t=>i(t))),this.services.backendConnector.load(t,this.options.ns,(t=>{t||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),e(t)}))}else e(null)}reloadResources(t,e,s){const i=n();return t||(t=this.languages),e||(e=this.options.ns),s||(s=D),this.services.backendConnector.reload(t,e,(t=>{i.resolve(),s(t)})),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===t.type&&(this.modules.backend=t),("logger"===t.type||t.log&&t.warn&&t.error)&&(this.modules.logger=t),"languageDetector"===t.type&&(this.modules.languageDetector=t),"i18nFormat"===t.type&&(this.modules.i18nFormat=t),"postProcessor"===t.type&&y.addPostProcessor(t),"formatter"===t.type&&(this.modules.formatter=t),"3rdParty"===t.type&&this.modules.external.push(t),this}setResolvedLanguage(t){if(t&&this.languages&&!(["cimode","dev"].indexOf(t)>-1))for(let t=0;t<this.languages.length;t++){const e=this.languages[t];if(!(["cimode","dev"].indexOf(e)>-1)&&this.store.hasLanguageSomeTranslations(e)){this.resolvedLanguage=e;break}}}changeLanguage(t,e){var s=this;this.isLanguageChangingTo=t;const i=n();this.emit("languageChanging",t);const o=t=>{this.language=t,this.languages=this.services.languageUtils.toResolveHierarchy(t),this.resolvedLanguage=void 0,this.setResolvedLanguage(t)},r=(t,n)=>{n?(o(n),this.translator.changeLanguage(n),this.isLanguageChangingTo=void 0,this.emit("languageChanged",n),this.logger.log("languageChanged",n)):this.isLanguageChangingTo=void 0,i.resolve((function(){return s.t(...arguments)})),e&&e(t,(function(){return s.t(...arguments)}))},a=e=>{t||e||!this.services.languageDetector||(e=[]);const s="string"==typeof e?e:this.services.languageUtils.getBestMatchFromCodes(e);s&&(this.language||o(s),this.translator.language||this.translator.changeLanguage(s),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(s)),this.loadResources(s,(t=>{r(t,s)}))};return t||!this.services.languageDetector||this.services.languageDetector.async?!t&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t):a(this.services.languageDetector.detect()),i}getFixedT(t,e,s){var i=this;const n=function(t,e){let o;if("object"!=typeof e){for(var r=arguments.length,a=new Array(r>2?r-2:0),l=2;l<r;l++)a[l-2]=arguments[l];o=i.options.overloadTranslationOptionHandler([t,e].concat(a))}else o={...e};o.lng=o.lng||n.lng,o.lngs=o.lngs||n.lngs,o.ns=o.ns||n.ns,o.keyPrefix=o.keyPrefix||s||n.keyPrefix;const u=i.options.keySeparator||".";let h;return h=o.keyPrefix&&Array.isArray(t)?t.map((t=>`${o.keyPrefix}${u}${t}`)):o.keyPrefix?`${o.keyPrefix}${u}${t}`:t,i.t(h,o)};return"string"==typeof t?n.lng=t:n.lngs=t,n.ns=e,n.keyPrefix=s,n}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const s=e.lng||this.resolvedLanguage||this.languages[0],i=!!this.options&&this.options.fallbackLng,n=this.languages[this.languages.length-1];if("cimode"===s.toLowerCase())return!0;const o=(t,e)=>{const s=this.services.backendConnector.state[`${t}|${e}`];return-1===s||2===s};if(e.precheck){const t=e.precheck(this,o);if(void 0!==t)return t}return!!this.hasResourceBundle(s,t)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!o(s,t)||i&&!o(n,t)))}loadNamespaces(t,e){const s=n();return this.options.ns?("string"==typeof t&&(t=[t]),t.forEach((t=>{this.options.ns.indexOf(t)<0&&this.options.ns.push(t)})),this.loadResources((t=>{s.resolve(),e&&e(t)})),s):(e&&e(),Promise.resolve())}loadLanguages(t,e){const s=n();"string"==typeof t&&(t=[t]);const i=this.options.preload||[],o=t.filter((t=>i.indexOf(t)<0));return o.length?(this.options.preload=i.concat(o),this.loadResources((t=>{s.resolve(),e&&e(t)})),s):(e&&e(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const e=this.services&&this.services.languageUtils||new S(F());return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(e.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){return new V(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}cloneInstance(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:D;const s=t.forkResourceStore;s&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},n=new V(i);void 0===t.debug&&void 0===t.prefix||(n.logger=n.logger.clone(t));return["store","services","language"].forEach((t=>{n[t]=this[t]})),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},s&&(n.store=new m(this.store.data,i),n.services.resourceStore=n.store),n.translator=new b(n.services,i),n.translator.on("*",(function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];n.emit(t,...s)})),n.init(i,e),n.translator.options=i,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const T=V.createInstance();return T.createInstance=V.createInstance,T}));
diff --git a/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js b/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js
new file mode 100644
index 0000000..f4530ae
--- /dev/null
+++ b/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js
@@ -0,0 +1 @@
+!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e="undefined"!=typeof globalThis?globalThis:e||self).i18nextBrowserLanguageDetector=o()}(this,(function(){"use strict";function e(e,o){if(!(e instanceof o))throw new TypeError("Cannot call a class as a function")}function o(e){return o="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},o(e)}function t(e){var t=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!==o(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===o(t)?t:String(t)}function n(e,o){for(var n=0;n<o.length;n++){var i=o[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,t(i.key),i)}}var i=[],r=i.forEach,a=i.slice;function u(e){return r.call(a.call(arguments,1),(function(o){if(o)for(var t in o)void 0===e[t]&&(e[t]=o[t])})),e}var s=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,c=function(e,o,t){var n=t||{};n.path=n.path||"/";var i=encodeURIComponent(o),r="".concat(e,"=").concat(i);if(n.maxAge>0){var a=n.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");r+="; Max-Age=".concat(Math.floor(a))}if(n.domain){if(!s.test(n.domain))throw new TypeError("option domain is invalid");r+="; Domain=".concat(n.domain)}if(n.path){if(!s.test(n.path))throw new TypeError("option path is invalid");r+="; Path=".concat(n.path)}if(n.expires){if("function"!=typeof n.expires.toUTCString)throw new TypeError("option expires is invalid");r+="; Expires=".concat(n.expires.toUTCString())}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite)switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r},l=function(e,o,t,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+60*t*1e3)),n&&(i.domain=n),document.cookie=c(e,encodeURIComponent(o),i)},f=function(e){for(var o="".concat(e,"="),t=document.cookie.split(";"),n=0;n<t.length;n++){for(var i=t[n];" "===i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(o))return i.substring(o.length,i.length)}return null},d={name:"cookie",lookup:function(e){var o;if(e.lookupCookie&&"undefined"!=typeof document){var t=f(e.lookupCookie);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupCookie&&"undefined"!=typeof document&&l(o.lookupCookie,e,o.cookieMinutes,o.cookieDomain,o.cookieOptions)}},g={name:"querystring",lookup:function(e){var o;if("undefined"!=typeof window){var t=window.location.search;!window.location.search&&window.location.hash&&window.location.hash.indexOf("?")>-1&&(t=window.location.hash.substring(window.location.hash.indexOf("?")));for(var n=t.substring(1).split("&"),i=0;i<n.length;i++){var r=n[i].indexOf("=");if(r>0)n[i].substring(0,r)===e.lookupQuerystring&&(o=n[i].substring(r+1))}}return o}},p=null,h=function(){if(null!==p)return p;try{p="undefined"!==window&&null!==window.localStorage;var e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch(e){p=!1}return p},m={name:"localStorage",lookup:function(e){var o;if(e.lookupLocalStorage&&h()){var t=window.localStorage.getItem(e.lookupLocalStorage);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupLocalStorage&&h()&&window.localStorage.setItem(o.lookupLocalStorage,e)}},v=null,w=function(){if(null!==v)return v;try{v="undefined"!==window&&null!==window.sessionStorage;var e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch(e){v=!1}return v},y={name:"sessionStorage",lookup:function(e){var o;if(e.lookupSessionStorage&&w()){var t=window.sessionStorage.getItem(e.lookupSessionStorage);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupSessionStorage&&w()&&window.sessionStorage.setItem(o.lookupSessionStorage,e)}},S={name:"navigator",lookup:function(e){var o=[];if("undefined"!=typeof navigator){if(navigator.languages)for(var t=0;t<navigator.languages.length;t++)o.push(navigator.languages[t]);navigator.userLanguage&&o.push(navigator.userLanguage),navigator.language&&o.push(navigator.language)}return o.length>0?o:void 0}},k={name:"htmlTag",lookup:function(e){var o,t=e.htmlTag||("undefined"!=typeof document?document.documentElement:null);return t&&"function"==typeof t.getAttribute&&(o=t.getAttribute("lang")),o}},b={name:"path",lookup:function(e){var o;if("undefined"!=typeof window){var t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(t instanceof Array)if("number"==typeof e.lookupFromPathIndex){if("string"!=typeof t[e.lookupFromPathIndex])return;o=t[e.lookupFromPathIndex].replace("/","")}else o=t[0].replace("/","")}return o}},x={name:"subdomain",lookup:function(e){var o="number"==typeof e.lookupFromSubdomainIndex?e.lookupFromSubdomainIndex+1:1,t="undefined"!=typeof window&&window.location&&window.location.hostname&&window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(t)return t[o]}};var L=function(){function o(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,o),this.type="languageDetector",this.detectors={},this.init(t,n)}var t,i,r;return t=o,i=[{key:"init",value:function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=e||{languageUtils:{}},this.options=u(o,this.options||{},{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:function(e){return e}}),"string"==typeof this.options.convertDetectedLanguage&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=function(e){return e.replace("-","_")}),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=t,this.addDetector(d),this.addDetector(g),this.addDetector(m),this.addDetector(y),this.addDetector(S),this.addDetector(k),this.addDetector(b),this.addDetector(x)}},{key:"addDetector",value:function(e){this.detectors[e.name]=e}},{key:"detect",value:function(e){var o=this;e||(e=this.options.order);var t=[];return e.forEach((function(e){if(o.detectors[e]){var n=o.detectors[e].lookup(o.options);n&&"string"==typeof n&&(n=[n]),n&&(t=t.concat(n))}})),t=t.map((function(e){return o.options.convertDetectedLanguage(e)})),this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}},{key:"cacheUserLanguage",value:function(e,o){var t=this;o||(o=this.options.caches),o&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||o.forEach((function(o){t.detectors[o]&&t.detectors[o].cacheUserLanguage(e,t.options)})))}}],i&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),o}();return L.type="languageDetector",L}));
diff --git a/frontend/src/js/lib/i18nextHttpBackend.min.js b/frontend/src/js/lib/i18nextHttpBackend.min.js
new file mode 100644
index 0000000..7f1f20e
--- /dev/null
+++ b/frontend/src/js/lib/i18nextHttpBackend.min.js
@@ -0,0 +1 @@
+!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).i18nextHttpBackend=e()}(function(){return function o(r,i,s){function a(t,e){if(!i[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}n=i[t]={exports:{}},r[t][0].call(n.exports,function(e){return a(r[t][1][e]||e)},n,n.exports,o,r,i,s)}return i[t].exports}for(var u="function"==typeof require&&require,e=0;e<s.length;e++)a(s[e]);return a}({1:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var a=e("./utils.js"),r=(e=e("./request.js"))&&e.__esModule?e:{default:e};function i(e){return(i="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})(e)}function o(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function s(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?o(Object(n),!0).forEach(function(e){c(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function u(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,f(o.key),o)}}function c(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e){e=((e,t)=>{if("object"!=i(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return("string"===t?String:Number)(e);if("object"!=i(n=n.call(e,t||"default")))return n;throw new TypeError("@@toPrimitive must return a primitive value.")})(e,"string");return"symbol"==i(e)?e:e+""}e=function e(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},r=this,i=e;if(!(r instanceof i))throw new TypeError("Cannot call a class as a function");this.services=t,this.options=n,this.allOptions=o,this.type="backend",this.init(t,n,o)},(d=[{key:"init",value:function(e){var t=this,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};this.services=e,this.options=s(s(s({},{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(e){return JSON.parse(e)},stringify:JSON.stringify,parsePayload:function(e,t,n){return c({},t,n||"")},parseLoadPayload:function(e,t){},request:r.default,reloadInterval:"undefined"==typeof window&&36e5,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}),this.options||{}),n),this.allOptions=o,this.services&&this.options.reloadInterval&&"object"===i(e=setInterval(function(){return t.reload()},this.options.reloadInterval))&&"function"==typeof e.unref&&e.unref()}},{key:"readMulti",value:function(e,t,n){this._readAny(e,e,t,t,n)}},{key:"read",value:function(e,t,n){this._readAny([e],e,[t],t,n)}},{key:"_readAny",value:function(t,n,o,r,i){var s=this,e=this.options.loadPath;"function"==typeof this.options.loadPath&&(e=this.options.loadPath(t,o)),(e=(0,a.makePromise)(e)).then(function(e){if(!e)return i(null,{});e=s.services.interpolator.interpolate(e,{lng:t.join("+"),ns:o.join("+")});s.loadUrl(e,i,n,r)})}},{key:"loadUrl",value:function(i,s,a,u){var c=this,e=this.options.parseLoadPayload("string"==typeof a?[a]:a,"string"==typeof u?[u]:u);this.options.request(this.options,i,e,function(e,t){if(t&&(500<=t.status&&t.status<600||!t.status))return s("failed loading "+i+"; status code: "+t.status,!0);if(t&&400<=t.status&&t.status<500)return s("failed loading "+i+"; status code: "+t.status,!1);if(!t&&e&&e.message){var n=e.message.toLowerCase();if(["failed","fetch","network","load"].find(function(e){return-1<n.indexOf(e)}))return s("failed loading "+i+": "+e.message,!0)}if(e)return s(e,!1);var o,r;try{o="string"==typeof t.data?c.options.parse(t.data,a,u):t.data}catch(e){r="failed parsing "+i+" to json"}if(r)return s(r,!1);s(null,o)})}},{key:"create",value:function(n,o,e,t,r){var i,s,a,u,c=this;this.options.addPath&&("string"==typeof n&&(n=[n]),i=this.options.parsePayload(o,e,t),s=0,a=[],u=[],n.forEach(function(e){var t=c.options.addPath,t=("function"==typeof c.options.addPath&&(t=c.options.addPath(e,o)),c.services.interpolator.interpolate(t,{lng:e,ns:o}));c.options.request(c.options,t,i,function(e,t){s+=1,a.push(e),u.push(t),s===n.length&&"function"==typeof r&&r(a,u)})}))}},{key:"reload",value:function(){var t,e,n=this,o=this.services,r=o.backendConnector,i=o.languageUtils,s=o.logger,o=r.language;o&&"cimode"===o.toLowerCase()||(t=[],(e=function(e){i.toResolveHierarchy(e).forEach(function(e){t.indexOf(e)<0&&t.push(e)})})(o),this.allOptions.preload&&this.allOptions.preload.forEach(e),t.forEach(function(o){n.allOptions.ns.forEach(function(n){r.read(o,n,"read",null,null,function(e,t){e&&s.warn("loading namespace ".concat(n," for language ").concat(o," failed"),e),!e&&t&&s.log("loaded namespace ".concat(n," for language ").concat(o),t),r.loaded("".concat(o,"|").concat(n),e,t)})})}))}}])&&u(e.prototype,d),l&&u(e,l),Object.defineProperty(e,"prototype",{writable:!1});var l,d=e;d.type="backend",n.default=d;t.exports=n.default},{"./request.js":2,"./utils.js":3}],2:[function(e,n,o){!function(S){!function(){Object.defineProperty(o,"__esModule",{value:!0}),o.default=void 0;var h=e("./utils.js");function t(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function b(o){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?t(Object(r),!0).forEach(function(e){var t,n;t=o,n=r[e=e],(e=(e=>(e=((e,t)=>{if("object"!=v(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return("string"===t?String:Number)(e);if("object"!=v(n=n.call(e,t||"default")))return n;throw new TypeError("@@toPrimitive must return a primitive value.")})(e,"string"),"symbol"==v(e)?e:e+""))(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(r)):t(Object(r)).forEach(function(e){Object.defineProperty(o,e,Object.getOwnPropertyDescriptor(r,e))})}return o}function v(e){return(v="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})(e)}var m,g,O="function"==typeof fetch?fetch:void 0;if(void 0!==S&&S.fetch?O=S.fetch:"undefined"!=typeof window&&window.fetch&&(O=window.fetch),(0,h.hasXMLHttpRequest)()&&(void 0!==S&&S.XMLHttpRequest?m=S.XMLHttpRequest:"undefined"!=typeof window&&window.XMLHttpRequest&&(m=window.XMLHttpRequest)),"function"==typeof ActiveXObject&&(void 0!==S&&S.ActiveXObject?g=S.ActiveXObject:"undefined"!=typeof window&&window.ActiveXObject&&(g=window.ActiveXObject)),!(O="function"!=typeof O?void 0:O)&&!m&&!g)try{O=e("cross-fetch")}catch(e){}var w=function(e,t){if(t&&"object"===v(t)){var n,o="";for(n in t)o+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t[n]);if(!o)return e;e=e+(-1!==e.indexOf("?")?"&":"?")+o.slice(1)}return e},j=function(e,t,n,o){function r(t){if(!t.ok)return n(t.statusText||"Error",{status:t.status});t.text().then(function(e){n(null,{status:t.status,data:e})}).catch(n)}if(o){o=o(e,t);if(o instanceof Promise)return void o.then(r).catch(n)}("function"==typeof fetch?fetch:O)(e,t).then(r).catch(n)},P=!1;o.default=function(e,t,n,o){if("function"==typeof n&&(o=n,n=void 0),o=o||function(){},O&&0!==t.indexOf("file:")){var r=e,i=t,s=n,a=o,u=(r.queryStringParams&&(i=w(i,r.queryStringParams)),b({},"function"==typeof r.customHeaders?r.customHeaders():r.customHeaders)),c=("undefined"==typeof window&&void 0!==S&&void 0!==S.process&&S.process.versions&&S.process.versions.node&&(u["User-Agent"]="i18next-http-backend (node/".concat(S.process.version,"; ").concat(S.process.platform," ").concat(S.process.arch,")")),s&&(u["Content-Type"]="application/json"),"function"==typeof r.requestOptions?r.requestOptions(s):r.requestOptions),f=b({method:s?"POST":"GET",body:s?r.stringify(s):void 0,headers:u},P?{}:c),s="function"==typeof r.alternateFetch&&1<=r.alternateFetch.length?r.alternateFetch:void 0;try{j(i,f,a,s)}catch(e){if(!c||0===Object.keys(c).length||!e.message||e.message.indexOf("not implemented")<0)return a(e);try{Object.keys(c).forEach(function(e){delete f[e]}),j(i,f,a,s),P=!0}catch(e){a(e)}}}else if((0,h.hasXMLHttpRequest)()||"function"==typeof ActiveXObject){var u=e,r=t,c=n,l=o;c&&"object"===v(c)&&(c=w("",c).slice(1)),u.queryStringParams&&(r=w(r,u.queryStringParams));try{var d=m?new m:new g("MSXML2.XMLHTTP.3.0"),p=(d.open(c?"POST":"GET",r,1),u.crossDomain||d.setRequestHeader("X-Requested-With","XMLHttpRequest"),d.withCredentials=!!u.withCredentials,c&&d.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),d.overrideMimeType&&d.overrideMimeType("application/json"),u.customHeaders);if(p="function"==typeof p?p():p)for(var y in p)d.setRequestHeader(y,p[y]);d.onreadystatechange=function(){3<d.readyState&&l(400<=d.status?d.statusText:null,{status:d.status,data:d.responseText})},d.send(c)}catch(e){console&&console.log(e)}}else o(new Error("No fetch and no xhr implementation found!"))};n.exports=o.default}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./utils.js":3,"cross-fetch":4}],3:[function(e,t,n){function o(e){return(o="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})(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.defaults=function(n){return r.call(i.call(arguments,1),function(e){if(e)for(var t in e)void 0===n[t]&&(n[t]=e[t])}),n},n.hasXMLHttpRequest=function(){return"function"==typeof XMLHttpRequest||"object"===("undefined"==typeof XMLHttpRequest?"undefined":o(XMLHttpRequest))},n.makePromise=function(e){if((e=>e&&"function"==typeof e.then)(e))return e;return Promise.resolve(e)};var n=[],r=n.forEach,i=n.slice},{}],4:[function(e,t,n){},{}]},{},[1])(1)});
\ No newline at end of file
diff --git a/frontend/src/js/services/apiService.js b/frontend/src/js/services/apiService.js
new file mode 100644
index 0000000..178706f
--- /dev/null
+++ b/frontend/src/js/services/apiService.js
@@ -0,0 +1,96 @@
+import authService from '/js/services/authService.js';
+
+async function baseRequest(path, options = {}) {
+ const headers = new Headers(options.headers || {});
+ const token = authService.getToken();
+ if (token && !headers.has('Authorization')) {
+ headers.set('Authorization', `Bearer ${token}`);
+ }
+ const opts = { ...options, headers };
+ const response = await fetch(path, opts);
+ if (!response.ok) {
+ const message = await safeErrorMessage(response);
+ throw new Error(message || `Request failed: ${response.status}`);
+ }
+ return response;
+}
+
+async function safeErrorMessage(response) {
+ try {
+ const data = await response.clone().json();
+ return data?.message || data?.error || null;
+ } catch {
+ try {
+ return await response.clone().text();
+ } catch {
+ return null;
+ }
+ }
+}
+
+export async function getWarranties(query = '') {
+ const res = await baseRequest(`/api/warranties${query ? `?${query}` : ''}`);
+ return res.json();
+}
+
+export async function updateWarranty(id, formData) {
+ const res = await baseRequest(`/api/warranties/${id}`, { method: 'PUT', body: formData });
+ return res.json();
+}
+
+export async function deleteWarranty(id) {
+ await baseRequest(`/api/warranties/${id}`, { method: 'DELETE' });
+ return true;
+}
+
+export async function getStatistics() {
+ const res = await baseRequest('/api/statistics');
+ return res.json();
+}
+
+export async function savePreferences(prefs) {
+ const res = await baseRequest('/api/auth/preferences', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(prefs),
+ });
+ return res.json();
+}
+
+// Backwards-compatible helper available to non-module scripts
+if (typeof window !== 'undefined') {
+ // Non-intrusive fetch shim: adds Authorization for /api calls when missing
+ const originalFetch = window.fetch.bind(window);
+ window.fetch = async (input, init = {}) => {
+ try {
+ const url = typeof input === 'string' ? input : (input && input.url) || '';
+ if (url.startsWith('/api')) {
+ const headers = new Headers((init && init.headers) || {});
+ if (!headers.has('Authorization')) {
+ const token = authService.getToken();
+ if (token) headers.set('Authorization', `Bearer ${token}`);
+ }
+ return originalFetch(input, { ...init, headers });
+ }
+ } catch {}
+ return originalFetch(input, init);
+ };
+
+ window.api = {
+ getWarranties,
+ updateWarranty,
+ deleteWarranty,
+ getStatistics,
+ savePreferences,
+ };
+}
+
+export default {
+ getWarranties,
+ updateWarranty,
+ deleteWarranty,
+ getStatistics,
+ savePreferences,
+};
+
+
diff --git a/frontend/src/js/services/authService.js b/frontend/src/js/services/authService.js
new file mode 100644
index 0000000..4aed282
--- /dev/null
+++ b/frontend/src/js/services/authService.js
@@ -0,0 +1,306 @@
+// Centralized Authentication Service
+// Provides a single source of truth for auth state and UI updates.
+
+const authService = (() => {
+ let cachedToken = null;
+ let cachedUser = null;
+ const logoutCallbacks = [];
+
+ function readStateFromStorage() {
+ cachedToken = localStorage.getItem('auth_token');
+ const userInfoString = localStorage.getItem('user_info');
+ cachedUser = null;
+ if (userInfoString) {
+ try {
+ cachedUser = JSON.parse(userInfoString);
+ } catch {
+ localStorage.removeItem('user_info');
+ cachedUser = null;
+ }
+ }
+ }
+
+ function isAuthenticated() {
+ return !!(cachedToken && cachedUser && cachedUser.id);
+ }
+
+ function getToken() {
+ if (!cachedToken) cachedToken = localStorage.getItem('auth_token');
+ return cachedToken;
+ }
+
+ function getCurrentUser() {
+ if (!cachedUser) {
+ const userInfoString = localStorage.getItem('user_info');
+ if (userInfoString) {
+ try {
+ cachedUser = JSON.parse(userInfoString);
+ } catch {
+ cachedUser = null;
+ }
+ }
+ }
+ return cachedUser;
+ }
+
+ function clearAuthData() {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ cachedToken = null;
+ cachedUser = null;
+ logoutCallbacks.forEach((cb) => {
+ try { cb(); } catch {}
+ });
+ }
+
+ function onLogout(callback) {
+ if (typeof callback === 'function') logoutCallbacks.push(callback);
+ }
+
+ function dispatchAuthStateEvent(isAuthed, user) {
+ setTimeout(() => {
+ window.dispatchEvent(new CustomEvent('authStateReady', { detail: { isAuthenticated: isAuthed, user } }));
+ }, 0);
+ }
+
+ function updateHeaderUI(isAuthed, user) {
+ const authContainer = document.getElementById('authContainer');
+ const userMenu = document.getElementById('userMenu');
+ const userDisplayName = document.getElementById('userDisplayName');
+ const userNameMenu = document.getElementById('userName');
+ const userEmailMenu = document.getElementById('userEmail');
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+
+ const loginButtons = document.querySelectorAll('a[href="/login.html"], a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="/register.html"], a[href="register.html"], .register-btn, .auth-btn.register-btn');
+ const genericAuthButtonsContainers = document.querySelectorAll('.auth-buttons');
+
+ if (isAuthed && user) {
+ if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden'; }
+ if (userMenu) { userMenu.style.display = 'block'; userMenu.style.visibility = 'visible'; }
+ if (userDisplayName) userDisplayName.textContent = user.first_name || user.username || 'User';
+ if (userNameMenu) userNameMenu.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';
+ if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;
+ loginButtons.forEach((b) => { b.style.display = 'none'; b.style.visibility = 'hidden'; });
+ registerButtons.forEach((b) => { b.style.display = 'none'; b.style.visibility = 'hidden'; });
+ genericAuthButtonsContainers.forEach((c) => { if (c.id !== 'authContainer') { c.style.display = 'none'; c.style.visibility = 'hidden'; } });
+ if (logoutMenuItem) logoutMenuItem.style.display = 'flex';
+ } else {
+ if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }
+ if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }
+ if (userDisplayName) userDisplayName.textContent = 'User';
+ if (userNameMenu) userNameMenu.textContent = 'User Name';
+ if (userEmailMenu) userEmailMenu.textContent = '';
+ loginButtons.forEach((b) => { b.style.display = 'inline-block'; b.style.visibility = 'visible'; });
+ registerButtons.forEach((b) => { b.style.display = 'inline-block'; b.style.visibility = 'visible'; });
+ genericAuthButtonsContainers.forEach((c) => { if (c.id !== 'authContainer') { c.style.display = 'flex'; c.style.visibility = 'visible'; } });
+ if (logoutMenuItem) logoutMenuItem.style.display = 'none';
+ }
+ }
+
+ function immediateCssToggle() {
+ // Fast, CSS-based hide/show to prevent flicker before scripts finish
+ const styleId = 'auth-ui-style';
+ let style = document.getElementById(styleId);
+ if (!style) {
+ style = document.createElement('style');
+ style.id = styleId;
+ document.head.appendChild(style);
+ }
+ const hasToken = !!localStorage.getItem('auth_token');
+ style.textContent = hasToken
+ ? `#authContainer, .auth-buttons, a[href="login.html"], a[href="/login.html"], a[href="register.html"], a[href="/register.html"], .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn { display: none !important; visibility: hidden !important; } #userMenu, .user-menu { display: block !important; visibility: visible !important; }`
+ : `#authContainer, .auth-buttons { display: flex !important; visibility: visible !important; } a[href="login.html"], a[href="/login.html"], a[href="register.html"], a[href="/register.html"], .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn { display: inline-block !important; visibility: visible !important; } #userMenu, .user-menu { display: none !important; visibility: hidden !important; }`;
+ }
+
+ async function validateTokenAndLoadUser() {
+ if (!cachedToken) return;
+ try {
+ const res = await fetch('/api/auth/validate-token', { headers: { Authorization: `Bearer ${cachedToken}` } });
+ if (!res.ok) throw new Error('Token validation failed');
+ const data = await res.json();
+ if (data && data.valid && data.user) {
+ cachedUser = data.user;
+ localStorage.setItem('user_info', JSON.stringify(cachedUser));
+ } else {
+ clearAuthData();
+ }
+ } catch {
+ clearAuthData();
+ }
+ }
+
+ async function initAuth() {
+ readStateFromStorage();
+ immediateCssToggle();
+ await validateTokenAndLoadUser();
+ updateHeaderUI(isAuthenticated(), cachedUser);
+ dispatchAuthStateEvent(isAuthenticated(), cachedUser);
+
+ // Keep dropdown handlers consistent
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+ if (logoutMenuItem) {
+ const clone = logoutMenuItem.cloneNode(true);
+ logoutMenuItem.parentNode.replaceChild(clone, logoutMenuItem);
+ clone.addEventListener('click', () => logout());
+ }
+
+ // User menu toggle (replicates legacy behavior from auth.js)
+ const userMenuBtnOriginal = document.getElementById('userMenuBtn');
+ const userMenuDropdown = document.getElementById('userMenuDropdown');
+ if (userMenuBtnOriginal && userMenuDropdown) {
+ const userMenuBtn = userMenuBtnOriginal.cloneNode(true);
+ userMenuBtnOriginal.parentNode.replaceChild(userMenuBtn, userMenuBtnOriginal);
+ userMenuBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ userMenuDropdown.classList.toggle('active');
+ });
+ }
+
+ // Settings gear menu toggle if present
+ const settingsBtnOriginal = document.getElementById('settingsBtn');
+ const settingsMenu = document.getElementById('settingsMenu');
+ if (settingsBtnOriginal && settingsMenu) {
+ const settingsBtn = settingsBtnOriginal.cloneNode(true);
+ settingsBtnOriginal.parentNode.replaceChild(settingsBtn, settingsBtnOriginal);
+ settingsBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ });
+ }
+
+ // Global click to close any open dropdowns (add once)
+ if (!window._authServiceGlobalClickListenerAdded) {
+ document.addEventListener('click', (e) => {
+ const dd = document.getElementById('userMenuDropdown');
+ const btn = document.getElementById('userMenuBtn');
+ if (dd && btn && dd.classList.contains('active') && !dd.contains(e.target) && !btn.contains(e.target)) {
+ dd.classList.remove('active');
+ }
+ const sm = document.getElementById('settingsMenu');
+ const sb = document.getElementById('settingsBtn');
+ if (sm && sb && sm.classList.contains('active') && !sm.contains(e.target) && !sb.contains(e.target)) {
+ sm.classList.remove('active');
+ }
+ });
+ window._authServiceGlobalClickListenerAdded = true;
+ }
+
+ // Storage changes from other tabs
+ window.addEventListener('storage', (e) => {
+ if (e.key === 'auth_token' || e.key === 'user_info') {
+ readStateFromStorage();
+ updateHeaderUI(isAuthenticated(), cachedUser);
+ dispatchAuthStateEvent(isAuthenticated(), cachedUser);
+ }
+ });
+
+ // Optionally hide registration links if registration disabled and user logged out
+ if (!getToken()) {
+ const hideRegistrationUI = () => {
+ const forceHide = (el) => {
+ if (!el) return;
+ // Strong hide to defeat CSS !important rules
+ el.style.setProperty('display', 'none', 'important');
+ el.style.setProperty('visibility', 'hidden', 'important');
+ el.setAttribute('hidden', 'true');
+ el.setAttribute('aria-hidden', 'true');
+ };
+
+ const selectors = [
+ '.register-btn', '.auth-btn.register-btn',
+ 'a[href="register.html"]', 'a[href="./register.html"]', 'a[href="/register.html"]',
+ 'a[data-i18n="auth.create_account"]'
+ ];
+ selectors.forEach((sel) => document.querySelectorAll(sel).forEach(forceHide));
+
+ const authLinks = document.querySelector('.auth-links');
+ if (authLinks) {
+ authLinks.querySelectorAll('a').forEach((a) => {
+ const text = (a.textContent || '').trim().toLowerCase();
+ if (text === 'create account' || a.getAttribute('href')?.includes('register.html') || a.dataset?.i18n === 'auth.create_account') {
+ forceHide(a);
+ }
+ });
+ }
+ };
+
+ try {
+ const res = await fetch('/api/auth/registration-status');
+ if (res.ok) {
+ const data = await res.json();
+ if (!data.enabled) {
+ hideRegistrationUI();
+ // Keep it hidden even if i18n or other scripts mutate DOM later
+ if (!window._authServiceRegObserver) {
+ const observer = new MutationObserver(() => hideRegistrationUI());
+ observer.observe(document.body, { childList: true, subtree: true });
+ window._authServiceRegObserver = observer;
+ }
+ }
+ }
+ } catch {}
+ }
+ }
+
+ async function login(username, password) {
+ const res = await fetch('/api/auth/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username, password }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data?.message || 'Login failed');
+ localStorage.setItem('auth_token', data.token);
+ localStorage.setItem('user_info', JSON.stringify(data.user));
+ readStateFromStorage();
+ updateHeaderUI(true, data.user);
+ dispatchAuthStateEvent(true, data.user);
+ return data;
+ }
+
+ async function logout() {
+ const tokenForApi = getToken();
+ clearAuthData();
+ updateHeaderUI(false, null);
+ dispatchAuthStateEvent(false, null);
+ try {
+ if (tokenForApi) {
+ await fetch('/api/auth/logout', { method: 'POST', headers: { Authorization: `Bearer ${tokenForApi}` } });
+ }
+ } catch {}
+ if (window.location.pathname !== '/login.html') {
+ window.location.href = 'login.html';
+ }
+ }
+
+ return {
+ initAuth,
+ login,
+ logout,
+ getToken,
+ getCurrentUser,
+ isAuthenticated,
+ clearAuthData,
+ onLogout,
+ };
+})();
+
+// Backwards compatibility for existing scripts
+window.auth = {
+ isAuthenticated: () => authService.isAuthenticated(),
+ getCurrentUser: () => authService.getCurrentUser(),
+ getToken: () => authService.getToken(),
+ login: (u, p) => authService.login(u, p),
+ logout: () => authService.logout(),
+ onLogout: (cb) => authService.onLogout(cb),
+};
+
+// Auto-init on DOM ready
+document.addEventListener('DOMContentLoaded', () => {
+ authService.initAuth();
+});
+
+export default authService;
+
+
diff --git a/frontend/src/js/store.js b/frontend/src/js/store.js
new file mode 100644
index 0000000..1df4db9
--- /dev/null
+++ b/frontend/src/js/store.js
@@ -0,0 +1,47 @@
+// Private state object
+let state = {
+ warranties: [],
+ filters: { status: 'all', tag: 'all', search: '', sortBy: 'expiration', vendor: 'all', warranty_type: 'all' },
+ isLoading: false,
+ allTags: []
+};
+
+// Simple event dispatcher
+const dispatch = (eventName, detail) => window.dispatchEvent(new CustomEvent(eventName, { detail }));
+
+// Exported functions to interact with the state
+export const getWarranties = () => state.warranties;
+export const setWarranties = (newWarranties) => {
+ state.warranties = Array.isArray(newWarranties) ? newWarranties : [];
+ dispatch('state:warrantiesChanged', { warranties: state.warranties });
+};
+
+export const getFilters = () => state.filters;
+export const updateFilter = (key, value) => {
+ state.filters[key] = value;
+ dispatch('state:filtersChanged', { filters: state.filters });
+};
+
+export const setLoading = (isLoading) => {
+ state.isLoading = !!isLoading;
+ dispatch('state:loadingChanged', { isLoading: state.isLoading });
+};
+
+export const getAllTags = () => state.allTags;
+export const setAllTags = (tags) => {
+ state.allTags = Array.isArray(tags) ? tags : [];
+ dispatch('state:tagsChanged', { allTags: state.allTags });
+};
+
+// Non-module compatibility for existing scripts
+if (typeof window !== 'undefined') {
+ window.store = {
+ getWarranties,
+ setWarranties,
+ getFilters,
+ updateFilter,
+ setLoading,
+ getAllTags,
+ setAllTags,
+ };
+}
diff --git a/frontend/login.html b/frontend/src/login.html
similarity index 94%
rename from frontend/login.html
rename to frontend/src/login.html
index ea704fd..5750120 100644
--- a/frontend/login.html
+++ b/frontend/src/login.html
@@ -1,17 +1,19 @@
<!DOCTYPE html>
<html>
<head>
- <script src="auth-redirect.js?v=20250119001" data-protected="false"></script>
+ <script src="/auth-redirect.js?v=20250119001" data-protected="false"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="auth.login_title">Login - Warracker</title>
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script>
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<script>
// If user is authenticated and has a theme in user_info (from previous sessions), reflect it early
try {
@@ -22,11 +24,11 @@
} catch (_) {}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
- <script src="js/i18n.js?v=20250119001"></script>
- <script src="registration-status.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
+
</head>
<body class="login-page-body">
@@ -94,7 +96,7 @@
</div>
</div>
- <script src="auth.js?v=20250119001"></script>
+
<script>
document.addEventListener('DOMContentLoaded', function() {
// Check for OIDC errors in URL parameters and display them
diff --git a/frontend/manifest.json b/frontend/src/manifest.json
similarity index 100%
rename from frontend/manifest.json
rename to frontend/src/manifest.json
diff --git a/frontend/mobile-header.css b/frontend/src/mobile-header.css
similarity index 100%
rename from frontend/mobile-header.css
rename to frontend/src/mobile-header.css
diff --git a/frontend/src/mobile-menu.js b/frontend/src/mobile-menu.js
new file mode 100644
index 0000000..b080815
--- /dev/null
+++ b/frontend/src/mobile-menu.js
@@ -0,0 +1,146 @@
+(function() {
+ function buildMobileMenuContent(panel, header) {
+ if (!panel || !header) return;
+ if (panel.getAttribute('data-built') === 'true') return;
+ panel.innerHTML = '';
+
+ const createSection = (titleText) => {
+ const title = document.createElement('div');
+ title.className = 'section-title';
+ title.textContent = titleText;
+ panel.appendChild(title);
+ };
+
+ const appendLinks = (links) => {
+ if (!links || links.length === 0) return;
+ const list = document.createElement('div');
+ list.className = 'menu-list';
+ links.forEach(a => {
+ try {
+ const cloned = a.cloneNode(true);
+ if (cloned.id) cloned.id = '';
+ list.appendChild(cloned);
+ } catch (_) {}
+ });
+ panel.appendChild(list);
+ };
+
+ const isAuthenticated = !!(function(){ try { return localStorage.getItem('auth_token'); } catch(_) { return null; } })();
+ let displayName = '';
+ const headerDisplayNameEl = header.querySelector('#userDisplayName');
+ if (headerDisplayNameEl && headerDisplayNameEl.textContent) {
+ displayName = headerDisplayNameEl.textContent.trim();
+ }
+ if (!displayName) {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
+ if (userInfo) displayName = userInfo.first_name || userInfo.username || 'Account';
+ } catch(_) {}
+ }
+ if (!displayName) displayName = 'Account';
+
+ const navLinksContainer = header.querySelector('.nav-links');
+ const navAnchors = navLinksContainer ? Array.from(navLinksContainer.querySelectorAll('a')) : [];
+ if (navAnchors.length) {
+ createSection('Navigation');
+ appendLinks(navAnchors);
+ }
+
+ const authContainer = header.querySelector('#authContainer');
+ const authAnchors = (!isAuthenticated && authContainer) ? Array.from(authContainer.querySelectorAll('a')) : [];
+ if (!isAuthenticated && authAnchors.length) {
+ createSection('Account');
+ appendLinks(authAnchors);
+ }
+
+ const userDropdown = header.querySelector('#userMenuDropdown');
+ const userMenuAnchors = userDropdown ? Array.from(userDropdown.querySelectorAll('a')) : [];
+ if (userMenuAnchors.length) {
+ createSection(displayName || 'Menu');
+ appendLinks(userMenuAnchors);
+
+ const logoutSource = header.querySelector('#logoutMenuItem');
+ if (logoutSource) {
+ const logoutLink = document.createElement('a');
+ logoutLink.href = '#';
+ logoutLink.id = 'mobileLogoutLink';
+ logoutLink.innerHTML = '<i class="fas fa-sign-out-alt"></i> <span>Logout</span>';
+ logoutLink.addEventListener('click', async function(e) {
+ e.preventDefault();
+ try {
+ if (window.auth && typeof window.auth.logout === 'function') {
+ await window.auth.logout();
+ } else {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ window.location.href = 'login.html';
+ }
+ } catch (_) {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ window.location.href = 'login.html';
+ }
+ });
+ const list = document.createElement('div');
+ list.className = 'menu-list';
+ list.appendChild(logoutLink);
+ panel.appendChild(list);
+ }
+ }
+
+ panel.setAttribute('data-built', 'true');
+ }
+
+ function initializeMobileMenu() {
+ const header = document.querySelector('header');
+ if (!header) return;
+ const toggleBtn = header.querySelector('.mobile-menu-toggle');
+ const panel = document.getElementById('mobileMenuPanel');
+ const overlay = document.getElementById('mobileMenuOverlay');
+ if (!toggleBtn || !panel || !overlay) return;
+
+ if (toggleBtn.getAttribute('data-mm-bound') === '1') return;
+ toggleBtn.setAttribute('data-mm-bound', '1');
+
+ const openMenu = () => {
+ buildMobileMenuContent(panel, header);
+ panel.classList.add('is-open');
+ overlay.classList.add('is-open');
+ document.body.classList.add('mobile-menu-active');
+ };
+
+ const closeMenu = () => {
+ panel.classList.remove('is-open');
+ overlay.classList.remove('is-open');
+ document.body.classList.remove('mobile-menu-active');
+ };
+
+ toggleBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ const isOpen = panel.classList.contains('is-open');
+ if (isOpen) closeMenu(); else openMenu();
+ });
+
+ overlay.addEventListener('click', function() {
+ closeMenu();
+ });
+
+ panel.addEventListener('click', function(e) {
+ const link = e.target.closest('a');
+ if (link && link.href) {
+ closeMenu();
+ }
+ });
+
+ document.addEventListener('keydown', function(e) {
+ if (e.key === 'Escape' && panel.classList.contains('is-open')) {
+ closeMenu();
+ }
+ });
+ }
+
+ window.initializeMobileMenu = initializeMobileMenu;
+ document.addEventListener('DOMContentLoaded', initializeMobileMenu);
+})();
+
+
diff --git a/frontend/register.html b/frontend/src/register.html
similarity index 95%
rename from frontend/register.html
rename to frontend/src/register.html
index b67b39a..2dc83a6 100644
--- a/frontend/register.html
+++ b/frontend/src/register.html
@@ -2,34 +2,36 @@
<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js?v=20250119001" data-protected="false"></script>
+ <script src="/auth-redirect.js?v=20250119001" data-protected="false"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="auth.register">Register - Warracker</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n initialization script -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
- <script src="script.js?v=20250119001" defer></script>
+
+ <script src="/script.js?v=20250119001" defer></script>
<style>
.auth-container {
max-width: 500px;
@@ -237,7 +239,7 @@
</style>
<!-- Registration status check script -->
- <script src="registration-status.js?v=20250119001"></script>
+
<script>
// Additional handling for the register page
document.addEventListener('DOMContentLoaded', function() {
@@ -377,7 +379,7 @@
</div>
<!-- Script for authentication -->
- <script src="auth.js?v=20250119001"></script>
+
<script>
document.addEventListener('DOMContentLoaded', function() {
const registerForm = document.getElementById('registerForm');
@@ -619,10 +621,10 @@
</script>
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/reset-password-request.html b/frontend/src/reset-password-request.html
similarity index 89%
rename from frontend/reset-password-request.html
rename to frontend/src/reset-password-request.html
index 7ef017b..88879cc 100644
--- a/frontend/reset-password-request.html
+++ b/frontend/src/reset-password-request.html
@@ -5,28 +5,30 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="auth.reset_password_title">Warracker - Reset Password</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n initialization script -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
- <script src="script.js?v=20250119001" defer></script>
+
+ <script src="/script.js?v=20250119001" defer></script>
<style>
.auth-container {
max-width: 400px;
@@ -97,7 +99,7 @@
</style>
<!-- Registration status check script -->
- <script src="registration-status.js?v=20250119001"></script>
+
</head>
<body>
<!-- Header -->
@@ -259,13 +261,13 @@
document.addEventListener('DOMContentLoaded', initializeTheme);
</script>
- <script src="auth.js?v=20250119001"></script>
+
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/reset-password.html b/frontend/src/reset-password.html
similarity index 93%
rename from frontend/reset-password.html
rename to frontend/src/reset-password.html
index bd351c7..a4fc88c 100644
--- a/frontend/reset-password.html
+++ b/frontend/src/reset-password.html
@@ -5,28 +5,30 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="auth.set_new_password_title">Warracker - Set New Password</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n initialization script -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
- <script src="script.js?v=20250119001" defer></script>
+
+ <script src="/script.js?v=20250119001" defer></script>
<style>
.auth-container {
max-width: 400px;
@@ -154,7 +156,7 @@
</style>
<!-- Registration status check script -->
- <script src="registration-status.js?v=20250119001"></script>
+
</head>
<body>
<!-- Header -->
@@ -426,13 +428,13 @@
</script>
<!-- Scripts -->
- <script src="auth.js?v=20250119001"></script>
+
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/src/script.js b/frontend/src/script.js
new file mode 100644
index 0000000..f6f4b0b
--- /dev/null
+++ b/frontend/src/script.js
@@ -0,0 +1,9644 @@
+// ===== MOBILE HAMBURGER MENU (kept for other pages) =====
+(function() {
+ function buildMobileMenuContent(panel, header) {
+ if (!panel || !header) return;
+ // Build only once
+ if (panel.getAttribute('data-built') === 'true') return;
+ panel.innerHTML = '';
+
+ const createSection = (titleText) => {
+ const title = document.createElement('div');
+ title.className = 'section-title';
+ title.textContent = titleText;
+ panel.appendChild(title);
+ };
+
+ const appendLinks = (links) => {
+ if (!links || links.length === 0) return;
+ const list = document.createElement('div');
+ list.className = 'menu-list';
+ links.forEach(a => {
+ try {
+ const cloned = a.cloneNode(true);
+ // Remove ids to avoid duplicates
+ if (cloned.id) cloned.id = '';
+ list.appendChild(cloned);
+ } catch (e) {
+ // Skip problematic nodes
+ }
+ });
+ panel.appendChild(list);
+ };
+
+ // Resolve auth state and display name
+ const isAuthenticated = !!(function(){ try { return localStorage.getItem('auth_token'); } catch(_) { return null; } })();
+ let displayName = '';
+ const headerDisplayNameEl = header.querySelector('#userDisplayName');
+ if (headerDisplayNameEl && headerDisplayNameEl.textContent) {
+ displayName = headerDisplayNameEl.textContent.trim();
+ }
+ if (!displayName) {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
+ if (userInfo) displayName = userInfo.first_name || userInfo.username || 'Account';
+ } catch(_) {}
+ }
+ if (!displayName) displayName = 'Account';
+
+ // Nav links
+ const navLinksContainer = header.querySelector('.nav-links');
+ const navAnchors = navLinksContainer ? Array.from(navLinksContainer.querySelectorAll('a')) : [];
+ if (navAnchors.length) {
+ createSection('Navigation');
+ appendLinks(navAnchors);
+ }
+
+ // Auth buttons if present (only when NOT authenticated)
+ const authContainer = header.querySelector('#authContainer');
+ const authAnchors = (!isAuthenticated && authContainer) ? Array.from(authContainer.querySelectorAll('a')) : [];
+ if (!isAuthenticated && authAnchors.length) {
+ createSection('Account');
+ appendLinks(authAnchors);
+ }
+
+ // User menu dropdown items if present
+ const userDropdown = header.querySelector('#userMenuDropdown');
+ const userMenuAnchors = userDropdown ? Array.from(userDropdown.querySelectorAll('a')) : [];
+ if (userMenuAnchors.length) {
+ // Use username as section title when available
+ createSection(displayName || 'Menu');
+ appendLinks(userMenuAnchors);
+
+ // Add Logout if available
+ const logoutSource = header.querySelector('#logoutMenuItem');
+ if (logoutSource) {
+ const logoutLink = document.createElement('a');
+ logoutLink.href = '#';
+ logoutLink.id = 'mobileLogoutLink';
+ logoutLink.innerHTML = '<i class="fas fa-sign-out-alt"></i> <span>Logout</span>';
+ logoutLink.addEventListener('click', async function(e) {
+ e.preventDefault();
+ try {
+ if (window.auth && typeof window.auth.logout === 'function') {
+ await window.auth.logout();
+ } else {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ window.location.href = 'login.html';
+ }
+ } catch (_) {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ window.location.href = 'login.html';
+ }
+ });
+ const list = document.createElement('div');
+ list.className = 'menu-list';
+ list.appendChild(logoutLink);
+ panel.appendChild(list);
+ }
+ }
+
+ panel.setAttribute('data-built', 'true');
+ }
+
+ function initializeMobileMenu() {
+ const header = document.querySelector('header');
+ if (!header) return;
+ const toggleBtn = header.querySelector('.mobile-menu-toggle');
+ const panel = document.getElementById('mobileMenuPanel');
+ const overlay = document.getElementById('mobileMenuOverlay');
+ if (!toggleBtn || !panel || !overlay) return;
+
+ // Prevent double-binding
+ if (toggleBtn.getAttribute('data-mm-bound') === '1') return;
+ toggleBtn.setAttribute('data-mm-bound', '1');
+
+ const openMenu = () => {
+ buildMobileMenuContent(panel, header);
+ panel.classList.add('is-open');
+ overlay.classList.add('is-open');
+ document.body.classList.add('mobile-menu-active');
+ };
+
+ const closeMenu = () => {
+ panel.classList.remove('is-open');
+ overlay.classList.remove('is-open');
+ document.body.classList.remove('mobile-menu-active');
+ };
+
+ toggleBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ const isOpen = panel.classList.contains('is-open');
+ if (isOpen) closeMenu(); else openMenu();
+ });
+
+ overlay.addEventListener('click', function() {
+ closeMenu();
+ });
+
+ panel.addEventListener('click', function(e) {
+ const link = e.target.closest('a');
+ if (link && link.href) {
+ closeMenu();
+ }
+ });
+
+ document.addEventListener('keydown', function(e) {
+ if (e.key === 'Escape' && panel.classList.contains('is-open')) {
+ closeMenu();
+ }
+ });
+ }
+
+ // Expose and initialize
+ window.initializeMobileMenu = initializeMobileMenu;
+ document.addEventListener('DOMContentLoaded', initializeMobileMenu);
+})();
+console.log('[SCRIPT VERSION] 20250529-005 - Added CSS cache busting for consistent styling across domains');
+console.log('[DEBUG] script.js loaded and running');
+
+// alert('script.js loaded!'); // Remove alert after confirming script loads
+
+// Global variables
+// Central state wiring: local mirrors kept in sync with store
+let warranties = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];
+window.addEventListener('state:warrantiesChanged', (e) => {
+ warranties = e.detail.warranties || [];
+ if (typeof applyFilters === 'function') {
+ applyFilters();
+ }
+});
+let warrantiesLoaded = false; // Track if warranties have been loaded from API
+let lastLoadedArchived = false; // Track if the current warranties array came from archived endpoint
+let lastLoadedIncludesArchived = false; // Track if the current warranties list includes archived items
+let currentTabIndex = 0;
+let tabContents = []; // Initialize as empty array
+let editMode = false;
+let currentWarrantyId = null;
+let userPreferencePrefix = null; // <<< ADDED GLOBAL PREFIX VARIABLE
+let isGlobalView = false; // Track if admin is viewing all users' warranties
+let currentFilters = (window.store && window.store.getFilters && window.store.getFilters()) || {
+ status: 'all',
+ tag: 'all',
+ search: '',
+ sortBy: 'expiration',
+ vendor: 'all',
+ warranty_type: 'all'
+};
+window.addEventListener('state:filtersChanged', (e) => {
+ currentFilters = e.detail.filters || currentFilters;
+ if (typeof applyFilters === 'function') {
+ applyFilters();
+ }
+});
+
+// Tag related variables
+let allTags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];
+window.addEventListener('state:tagsChanged', (e) => {
+ allTags = e.detail.allTags || [];
+});
+let selectedTags = []; // Will hold objects with id, name, color
+
+// Global variable for edit mode tags
+let editSelectedTags = [];
+
+// DOM Elements
+const warrantyForm = document.getElementById('warrantyForm');
+const settingsBtn = document.getElementById('settingsBtn');
+const settingsMenu = document.getElementById('settingsMenu');
+const darkModeToggle = document.getElementById('darkModeToggle');
+const warrantiesList = document.getElementById('warrantiesList');
+const refreshBtn = document.getElementById('refreshBtn');
+const searchInput = document.getElementById('searchWarranties');
+const clearSearchBtn = document.getElementById('clearSearch');
+const statusFilter = document.getElementById('statusFilter');
+const sortBySelect = document.getElementById('sortBy');
+const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
+const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select
+const exportBtn = document.getElementById('exportBtn');
+const gridViewBtn = document.getElementById('gridViewBtn');
+const listViewBtn = document.getElementById('listViewBtn');
+const tableViewBtn = document.getElementById('tableViewBtn');
+const tableViewHeader = document.querySelector('.table-view-header');
+
+// Admin view controls
+const adminViewSwitcher = document.getElementById('adminViewSwitcher');
+const personalViewBtn = document.getElementById('personalViewBtn');
+const globalViewBtn = document.getElementById('globalViewBtn');
+const warrantiesPanelTitle = document.getElementById('warrantiesPanelTitle');
+const fileInput = document.getElementById('invoice');
+const fileName = document.getElementById('fileName');
+const manualInput = document.getElementById('manual');
+const manualFileName = document.getElementById('manualFileName');
+const otherDocumentInput = document.getElementById('otherDocument');
+const otherDocumentFileName = document.getElementById('otherDocumentFileName');
+const editModal = document.getElementById('editModal');
+const deleteModal = document.getElementById('deleteModal');
+const editWarrantyForm = document.getElementById('editWarrantyForm');
+const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
+const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
+const loadingContainer = document.getElementById('loadingContainer');
+const toastContainer = document.getElementById('toastContainer');
+
+// CSV Import Elements
+const importBtn = document.getElementById('importBtn');
+const csvFileInput = document.getElementById('csvFileInput');
+if (importBtn) {
+ importBtn.classList.remove('import-btn');
+ importBtn.classList.add('export-btn');
+}
+
+// Tag DOM Elements
+const selectedTagsContainer = document.getElementById('selectedTags');
+const tagSearch = document.getElementById('tagSearch');
+const tagsList = document.getElementById('tagsList');
+const manageTagsBtn = document.getElementById('manageTagsBtn');
+const tagManagementModal = document.getElementById('tagManagementModal');
+const newTagForm = document.getElementById('newTagForm');
+const existingTagsContainer = document.getElementById('existingTags');
+
+// Claims modal elements
+const claimsModal = document.getElementById('claimsModal');
+const claimFormModal = document.getElementById('claimFormModal');
+const claimsListBody = document.getElementById('claimsListBody');
+const addClaimBtn = document.getElementById('addClaimBtn');
+const claimForm = document.getElementById('claimForm');
+const saveClaimBtn = document.getElementById('saveClaimBtn');
+const editClaimId = document.getElementById('editClaimId');
+const claimFormTitle = document.getElementById('claimFormTitle');
+const warrantyClaimInfo = document.getElementById('warrantyClaimInfo');
+
+// --- Add near other DOM Element declarations ---
+const isLifetimeCheckbox = document.getElementById('isLifetime');
+const warrantyDurationFields = document.getElementById('warrantyDurationFields'); // New container
+const warrantyDurationYearsInput = document.getElementById('warrantyDurationYears');
+const warrantyDurationMonthsInput = document.getElementById('warrantyDurationMonths');
+const warrantyDurationDaysInput = document.getElementById('warrantyDurationDays');
+
+const editIsLifetimeCheckbox = document.getElementById('editIsLifetime');
+const editWarrantyDurationFields = document.getElementById('editWarrantyDurationFields'); // New container
+const editWarrantyDurationYearsInput = document.getElementById('editWarrantyDurationYears');
+const editWarrantyDurationMonthsInput = document.getElementById('editWarrantyDurationMonths');
+const editWarrantyDurationDaysInput = document.getElementById('editWarrantyDurationDays');
+
+// Warranty Type DOM Elements
+const warrantyTypeInput = document.getElementById('warrantyType');
+const warrantyTypeCustomInput = document.getElementById('warrantyTypeCustom');
+const editWarrantyTypeInput = document.getElementById('editWarrantyType');
+const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
+
+// Warranty method selection elements
+const durationMethodRadio = document.getElementById('durationMethod');
+const exactDateMethodRadio = document.getElementById('exactDateMethod');
+const exactExpirationField = document.getElementById('exactExpirationField');
+const exactExpirationDateInput = document.getElementById('exactExpirationDate');
+
+const editDurationMethodRadio = document.getElementById('editDurationMethod');
+const editExactDateMethodRadio = document.getElementById('editExactDateMethod');
+const editExactExpirationField = document.getElementById('editExactExpirationField');
+const editExactExpirationDateInput = document.getElementById('editExactExpirationDate');
+
+// Add near other DOM Element declarations
+const showAddWarrantyBtn = document.getElementById('showAddWarrantyBtn');
+const addWarrantyModal = document.getElementById('addWarrantyModal');
+
+// Currency dropdown elements
+const currencySelect = document.getElementById('currency');
+const editCurrencySelect = document.getElementById('editCurrency');
+const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Ensure this is defined
+
+/**
+ * Get current user type (admin or user)
+ * @returns {string} 'admin' or 'user'
+ */
+function getUserType() {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.is_admin === true ? 'admin' : 'user';
+ } catch (e) {
+ console.error('Error determining user type:', e);
+ return 'user'; // Default to user if we can't determine
+ }
+}
+
+/**
+ * Initialize view controls for all authenticated users
+ */
+async function initViewControls() {
+ // Check if global view is enabled
+ try {
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ const scopeDropdown = document.getElementById('scopeDropdown');
+ // Keep bottom admin switcher hidden; control only the header scope dropdown
+ if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
+ if (result.enabled) {
+ if (scopeDropdown) scopeDropdown.style.display = 'block';
+ // Apply saved scope (update title and state)
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ isGlobalView = true;
+ updateWarrantiesPanelTitle(true);
+ } else {
+ isGlobalView = false;
+ updateWarrantiesPanelTitle(false);
+ }
+ } else {
+ if (scopeDropdown) scopeDropdown.style.display = 'none';
+ if (isGlobalView) {
+ isGlobalView = false;
+ updateWarrantiesPanelTitle(false);
+ await loadWarranties(true);
+ applyFilters();
+ }
+ }
+ } else {
+ console.error('Failed to check global view status');
+ // Hide bottom switcher even on failure; show header dropdown for fallback
+ if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
+ const scopeDropdown = document.getElementById('scopeDropdown');
+ if (scopeDropdown) scopeDropdown.style.display = 'block';
+ }
+ } catch (error) {
+ console.error('Error checking global view status:', error);
+ // Keep bottom switcher hidden; show header dropdown as fallback
+ if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
+ const scopeDropdown = document.getElementById('scopeDropdown');
+ if (scopeDropdown) scopeDropdown.style.display = 'block';
+ }
+}
+
+/**
+ * Switch to personal view (user's own warranties)
+ */
+async function switchToPersonalView() {
+ if (!personalViewBtn || !globalViewBtn) return;
+
+ isGlobalView = false;
+ personalViewBtn.classList.add('active');
+ globalViewBtn.classList.remove('active');
+
+ // Save view preference
+ saveViewScopePreference('personal');
+
+ // Update title
+ updateWarrantiesPanelTitle(false);
+
+ // Update header scope label
+ try {
+ const currentScopeIcon = document.getElementById('currentScopeIcon');
+ if (currentScopeIcon) {
+ currentScopeIcon.className = 'fas fa-user';
+ currentScopeIcon.setAttribute('aria-label', 'Personal');
+ }
+ } catch (e) { /* no-op */ }
+
+ // Reload warranties
+ try {
+ const token = window.auth.getToken();
+ if (token) {
+ await loadWarranties(true);
+ applyFilters();
+ }
+ } catch (error) {
+ console.error('Error switching to personal view:', error);
+ showToast(window.t('messages.error_loading_personal_warranties'), 'error');
+ }
+}
+
+/**
+ * Switch to global view (all users' warranties) - available to all users
+ */
+async function switchToGlobalView() {
+ if (!personalViewBtn || !globalViewBtn) return;
+
+ // Check if global view is still enabled
+ try {
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ if (!result.enabled) {
+ showToast(window.t('messages.global_view_disabled'), 'error');
+ return;
+ }
+ }
+ } catch (error) {
+ console.error('Error checking global view status:', error);
+ }
+
+ isGlobalView = true;
+ personalViewBtn.classList.remove('active');
+ globalViewBtn.classList.add('active');
+
+ // Save view preference
+ saveViewScopePreference('global');
+
+ // Update title
+ updateWarrantiesPanelTitle(true);
+
+ // Update header scope label
+ try {
+ const currentScopeIcon = document.getElementById('currentScopeIcon');
+ if (currentScopeIcon) {
+ currentScopeIcon.className = 'fas fa-globe';
+ currentScopeIcon.setAttribute('aria-label', 'Global');
+ }
+ } catch (e) { /* no-op */ }
+
+ // Reload warranties
+ try {
+ const token = window.auth.getToken();
+ if (token) {
+ await loadWarranties(true);
+ applyFilters();
+ }
+ } catch (error) {
+ console.error('Error switching to global view:', error);
+ showToast(window.t('messages.error_loading_global_warranties'), 'error');
+ }
+}
+
+/**
+ * Update warranties panel title with proper translation
+ * @param {boolean} isGlobal - Whether to show global or personal title
+ */
+function updateWarrantiesPanelTitle(isGlobal = false) {
+ if (warrantiesPanelTitle) {
+ if (window.i18next && window.i18next.t) {
+ warrantiesPanelTitle.textContent = isGlobal ?
+ window.i18next.t('warranties.title_global') :
+ window.i18next.t('warranties.title');
+ } else {
+ warrantiesPanelTitle.textContent = isGlobal ? 'All Users\' Warranties' : 'Your Warranties';
+ }
+ }
+}
+
+/**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+}
+
+/**
+ * Save view scope preference to localStorage
+ * @param {string} scope - 'personal' or 'global'
+ */
+function saveViewScopePreference(scope) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}viewScope`, scope);
+ console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
+ } catch (error) {
+ console.error('Error saving view scope preference:', error);
+ }
+}
+
+/**
+ * Load view scope preference from localStorage
+ * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
+ */
+function loadViewScopePreference() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedScope = localStorage.getItem(`${prefix}viewScope`);
+ console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
+ return savedScope || 'personal'; // Default to personal view
+ } catch (error) {
+ console.error('Error loading view scope preference:', error);
+ return 'personal'; // Default to personal view on error
+ }
+}
+
+// Theme Management - Simplified
+function setTheme(isDark) {
+ const theme = isDark ? 'dark' : 'light';
+ console.log('Setting theme to:', theme);
+
+ // 1. Apply theme attribute to document root
+ document.documentElement.setAttribute('data-theme', theme);
+
+ // 2. Save the single source of truth to localStorage
+ localStorage.setItem('darkMode', isDark);
+
+ // Update toggle state if the toggle exists on this page (e.g., in the header)
+ const headerToggle = document.getElementById('darkModeToggle');
+ if (headerToggle) {
+ headerToggle.checked = isDark;
+ }
+}
+
+// Persist theme to API similar to view/filters
+async function saveThemePreference(isDark, saveToApi = true) {
+ try {
+ // Always persist locally first
+ setTheme(isDark);
+
+ if (saveToApi && window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ const token = window.auth.getToken();
+ if (token) {
+ try {
+ console.log('[Theme] Saving theme preference to API:', isDark ? 'dark' : 'light');
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ theme: isDark ? 'dark' : 'light' })
+ });
+ if (!response.ok) {
+ console.warn('[Theme] Failed to save theme to API:', response.status);
+ }
+ } catch (err) {
+ console.error('[Theme] Error saving theme to API:', err);
+ }
+ }
+ }
+ } catch (e) {
+ console.warn('Failed to save theme preference', e);
+ }
+}
+
+// Initialization logic on DOMContentLoaded
+document.addEventListener('DOMContentLoaded', function() {
+ // Register Service Worker
+ if ('serviceWorker' in navigator) {
+ window.addEventListener('load', () => {
+ navigator.serviceWorker.register('./sw.js')
+ .then(registration => {
+ console.log('Service Worker registered with scope:', registration.scope);
+ })
+ .catch(error => {
+ console.error('Service Worker registration failed:', error);
+ });
+ });
+ }
+
+ // --- Search button click triggers search ---
+ const searchBtn = document.getElementById('searchBtn');
+ const searchInput = document.getElementById('searchWarranties');
+ if (searchBtn && searchInput) {
+ searchBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());
+ currentFilters.search = searchInput.value.toLowerCase();
+ applyFilters();
+ });
+ }
+ // --- Ensure globalManageTagsBtn triggers modal and tag form is always initialized ---
+ // (Redundant with setupUIEventListeners, but ensures modal is always ready)
+ const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');
+ if (globalManageTagsBtn) {
+ globalManageTagsBtn.addEventListener('click', async () => {
+ if (!allTags || allTags.length === 0) {
+ showLoadingSpinner();
+ try {
+ await loadTags();
+ } catch (error) {
+ console.error("Failed to load tags before opening modal:", error);
+ showToast(window.t('messages.could_not_load_tags'), "error");
+ hideLoadingSpinner();
+ return;
+ }
+ hideLoadingSpinner();
+ }
+ openTagManagementModal();
+ });
+ }
+ console.log('[DEBUG] Registering authStateReady event handler');
+ // ... other initialization ...
+
+ // --- BEGIN REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
+ const globalTagManagementModal = document.getElementById('tagManagementModal');
+ const globalNewTagForm = document.getElementById('newTagForm'); // Inside tagManagementModal
+ const mainTagSearchInput = document.getElementById('tagSearch'); // For the main "Add Warranty" form's tag search
+ const warrantyFormElement = document.getElementById('warrantyForm'); // The main add warranty form
+
+ // 1. ALWAYS Initialize listeners for the global Tag Management Modal IF IT EXISTS
+ if (globalTagManagementModal) {
+ if (globalNewTagForm) {
+ // Ensure the event listener is attached only once, or manage it if DOMContentLoaded could fire multiple times (not typical)
+ // For simplicity, assuming DOMContentLoaded runs once per page load.
+ globalNewTagForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ // Inline implementation for creating a new tag from the modal
+ const tagNameInput = document.getElementById('newTagName');
+ const tagColorInput = document.getElementById('newTagColor');
+ const name = tagNameInput ? tagNameInput.value.trim() : '';
+ const color = tagColorInput ? tagColorInput.value : '#808080';
+ if (!name) {
+ showToast(window.t('messages.tag_name_required'), 'error');
+ return;
+ }
+ // Use the existing createTag function if available
+ if (typeof createTag === 'function') {
+ createTag(name, color)
+ .then(() => {
+ if (tagNameInput) tagNameInput.value = '';
+ if (tagColorInput) tagColorInput.value = '#808080';
+ renderExistingTags && renderExistingTags();
+ })
+ .catch((err) => {
+ showToast((err && err.message) || window.t('messages.failed_to_create_tag'), 'error');
+ });
+ } else {
+ showToast(window.t('messages.tag_creation_function_not_found'), 'error');
+ }
+ });
+ }
+
+ const closeButtons = globalTagManagementModal.querySelectorAll('[data-dismiss="modal"]');
+ closeButtons.forEach(button => {
+ button.addEventListener('click', (event) => {
+ globalTagManagementModal.style.display = 'none';
+ event.stopPropagation(); // This was the fix from before, ensuring it's applied
+ });
+ });
+ console.log('Global Tag Management Modal listeners initialized directly in DOMContentLoaded.');
+ }
+
+ // 2. Initialize Tag functionality FOR THE MAIN ADD WARRANTY FORM (if its specific tag search input exists)
+ // initTagFunctionality is now refactored to be specific to the main form's tag UI.
+ if (mainTagSearchInput) {
+ initTagFunctionality(); // Sets up main form tag search, its manage button, etc.
+ // Also calls loadTags() if needed for the main form.
+ }
+ // --- END REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
+
+
+ // Setup form submission (assuming addWarrantyForm exists - this is 'warrantyFormElement')
+ // const form = document.getElementById('addWarrantyForm'); // Old selector
+ if (warrantyFormElement) { // Use the variable defined above
+ warrantyFormElement.addEventListener('submit', handleFormSubmit);
+ // Initialize form tabs if the form exists
+ // initFormTabs(); // This should be called when the ADD MODAL is SHOWN, not globally here.
+ // It's correctly in setupModalTriggers for the addWarrantyModal.
+ }
+
+
+ // Initialize theme toggle state *after* DOM is loaded
+ // ... (theme toggle init logic remains) ...
+
+ // Setup view switcher (assuming view switcher elements exist)
+ if (document.getElementById('gridViewBtn')) {
+ // setupViewSwitcher(); // Removed undefined function
+ loadViewPreference(); // This is fine here, loads initial view preference.
+ }
+
+ // Setup filter controls (assuming filter controls exist)
+ if (document.getElementById('filterControls')) {
+ // setupFilterControls(); // Removed: function not defined
+ // populateTagFilter(); // This should be called AFTER warranties (and their tags) are loaded.
+ // It's called in loadWarranties -> processAllWarranties or similar flow.
+ }
+
+ // Initialize modal interactions (general modal triggers like close buttons, backdrop)
+ setupModalTriggers(); // This sets up general modal behaviors and specific triggers for add/edit.
+
+ // Initialize form-specific lifetime checkbox handler FOR THE MAIN ADD FORM
+ const lifetimeCheckbox = document.getElementById('isLifetime'); // Main form's checkbox
+ if (lifetimeCheckbox) {
+ lifetimeCheckbox.addEventListener('change', handleLifetimeChange);
+ handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
+ }
+
+ // Initialize warranty method selection handlers
+ if (durationMethodRadio && exactDateMethodRadio) {
+ durationMethodRadio.addEventListener('change', handleWarrantyMethodChange);
+ exactDateMethodRadio.addEventListener('change', handleWarrantyMethodChange);
+ handleWarrantyMethodChange(); // Initial setup
+ }
+
+ if (editDurationMethodRadio && editExactDateMethodRadio) {
+ editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ handleEditWarrantyMethodChange(); // Initial setup for edit form
+ }
+
+ // --- LOAD WARRANTIES AFTER AUTH ---
+ let authStateHandled = false;
+
+ async function runAuthenticatedTasks(isAuthenticated) { // Added isAuthenticated parameter
+ if (!isAuthenticated) {
+ console.log('[DEBUG] runAuthenticatedTasks: Called with isAuthenticated = false. Not running tasks yet.');
+ // Do not set authStateHandled = true here, allow a subsequent call with true.
+ return;
+ }
+ // If we reach here, isAuthenticated is true.
+ if (authStateHandled) {
+ console.log('[DEBUG] runAuthenticatedTasks: Tasks already handled (or in progress by another call).');
+ return;
+ }
+ authStateHandled = true; // Set flag only when tasks are actually starting with isAuthenticated = true.
+ console.log('[DEBUG] runAuthenticatedTasks: Executing with isAuthenticated = true.');
+
+ // Set prefix
+ userPreferencePrefix = getPreferenceKeyPrefix();
+ console.log(`[runAuthenticatedTasks] Determined and stored global prefix: ${userPreferencePrefix}`);
+
+ // Re-check auth status just before critical data loads
+ const currentAuthStatus = window.auth && window.auth.isAuthenticated();
+ console.log(`[runAuthenticatedTasks] Current auth status before loading prefs/warranties: ${currentAuthStatus}`);
+
+ if (currentAuthStatus) {
+ await loadAndApplyUserPreferences(true); // Pass true, as we've confirmed auth
+ await loadTags(); // Ensure all available tags are loaded
+ await loadCurrencies(); // Load currencies for dropdowns
+
+ // Initialize Paperless-ngx integration
+ await initPaperlessNgxIntegration();
+
+ // Initialize view controls for all users
+ initViewControls();
+
+ if (document.getElementById('warrantiesList')) {
+ console.log("[runAuthenticatedTasks] Loading warranty data...");
+ await loadWarranties(true); // Pass true
+ console.log('[DEBUG] After loadWarranties, warranties array:', warranties);
+ // After warranties are loaded and filter dropdowns populated, load filter/sort prefs and apply
+ loadFilterAndSortPreferences();
+ // Reflect saved filters in UI selects if present
+ const statusFilterEl = document.getElementById('statusFilter');
+ const tagFilterEl = document.getElementById('tagFilter');
+ const vendorFilterEl = document.getElementById('vendorFilter');
+ const warrantyTypeFilterEl = document.getElementById('warrantyTypeFilter');
+ const sortByEl = document.getElementById('sortBy');
+ if (statusFilterEl && currentFilters.status) statusFilterEl.value = currentFilters.status;
+ if (tagFilterEl && currentFilters.tag) tagFilterEl.value = currentFilters.tag;
+ if (vendorFilterEl && currentFilters.vendor) vendorFilterEl.value = currentFilters.vendor;
+ if (warrantyTypeFilterEl && currentFilters.warranty_type) warrantyTypeFilterEl.value = currentFilters.warranty_type;
+ if (sortByEl && currentFilters.sortBy) sortByEl.value = currentFilters.sortBy;
+ // Update the filter indicator if available
+ if (typeof window.updateFilterIndicator === 'function') {
+ window.updateFilterIndicator();
+ }
+ } else {
+ console.log("[runAuthenticatedTasks] Warranties list element not found.");
+ }
+ } else {
+ console.warn("[runAuthenticatedTasks] Auth status became false before loading data. Aborting data load.");
+ // Optionally, reset authStateHandled if we want to allow another attempt
+ // authStateHandled = false;
+ }
+
+ // Now that data and preferences are ready, apply view/currency and render via applyFilters
+ console.log("[runAuthenticatedTasks] Applying preferences and rendering...");
+ loadViewPreference(); // Sets currentView and UI classes/buttons
+ updateCurrencySymbols(); // Update symbols
+
+ // Apply filters using the loaded data and render the list
+ if (document.getElementById('warrantiesList')) {
+ applyFilters();
+ }
+ }
+
+ // Listener for the 'authStateReady' event
+ window.addEventListener('authStateReady', async function handleAuthEvent(event) {
+ console.log('[DEBUG] authStateReady event received in script.js. Detail:', event.detail);
+ // Pass the isAuthenticated status from the event detail to runAuthenticatedTasks
+ await runAuthenticatedTasks(event.detail && event.detail.isAuthenticated);
+ }); // Removed { once: true } to allow re-evaluation if auth state changes
+
+ // Proactive check after a brief delay to allow auth.js to initialize
+ setTimeout(async () => {
+ console.log('[DEBUG] Proactive auth check in script.js (after timeout).');
+ if (window.auth) {
+ // Pass the current authentication status to runAuthenticatedTasks
+ await runAuthenticatedTasks(window.auth.isAuthenticated());
+ } else {
+ console.log('[DEBUG] Proactive check: window.auth not available. Event listener should handle it.');
+ // Call with false if auth module isn't ready, to avoid tasks running prematurely.
+ await runAuthenticatedTasks(false);
+ }
+ }, 500); // Delay
+ // --- END LOAD WARRANTIES AFTER AUTH ---
+
+ // updateCurrencySymbols(); // Call removed, rely on loadWarranties triggering render with correct symbol
+});
+
+// Initialize theme based on user preference or system preference
+function initializeTheme() {
+ // Only use the global darkMode key for theme persistence
+ const savedTheme = localStorage.getItem('darkMode');
+ if (savedTheme !== null) {
+ setTheme(savedTheme === 'true');
+ } else {
+ setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches);
+ }
+}
+
+// Variables
+let currentView = 'grid'; // Default view
+let expiringSoonDays = 30; // Default value, will be updated from user preferences
+
+// API URL
+const API_URL = '/api/warranties';
+async function toggleArchiveStatus(warrantyId, shouldArchive) {
+ try {
+ const token = window.auth.getToken();
+ if (!token) throw new Error('No auth token');
+ const response = await fetch(`/api/warranties/${warrantyId}/archive`, {
+ method: 'PATCH',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ archived: !!shouldArchive })
+ });
+ if (!response.ok) {
+ const err = await response.json().catch(() => ({}));
+ throw new Error(err.error || `HTTP ${response.status}`);
+ }
+ // Reload appropriate list
+ // Always reload current view to ensure accurate list source
+ await loadWarranties(true);
+ showToast(shouldArchive ? (window.t ? window.t('messages.archived_success') : 'Archived') : (window.t ? window.t('messages.unarchived_success') : 'Unarchived'), 'success');
+ } catch (e) {
+ console.error('Failed to toggle archive status', e);
+ showToast(window.t ? window.t('messages.error_updating_archive_status') : 'Failed to update archive status', 'error');
+ }
+}
+
+// Utility function to escape HTML
+function escapeHtml(text) {
+ if (typeof text !== 'string') return text;
+ const map = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#039;'
+ };
+ return text.replace(/[&<>"']/g, function(m) { return map[m]; });
+}
+
+// Form tab navigation variables (simplified)
+let formTabs = []; // Changed from const to let, initialized as empty
+// Removed const formTabsElements = document.querySelectorAll('.form-tab');
+// Removed const formTabs = formTabsElements ? Array.from(formTabsElements) : [];
+// Removed const tabContentsElements = document.querySelectorAll('.tab-content');
+// Removed tabContents assignment here
+
+// const nextButton = document.querySelector('.next-tab'); // Keep these if needed globally, otherwise might remove
+// const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove
+
+// --- Add near other DOM Element declarations ---
+ // ... existing code ...
+ // Add save button handler for notes modal (if not already present)
+ const saveNotesBtn = document.getElementById('saveNotesBtn');
+ if (saveNotesBtn) {
+ saveNotesBtn.onclick = async function() {
+ // Get the warranty ID being edited
+ const warrantyId = notesModalWarrantyId;
+ const notesValue = document.getElementById('notesModalTextarea').value;
+ if (!warrantyId || !notesModalWarrantyObj) return;
+ // Get auth token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ showToast(window.t('messages.authentication_required'), 'error');
+ return;
+ }
+ showLoadingSpinner();
+ try {
+ // Use FormData and send all required fields, just like the edit modal
+ const formData = new FormData();
+ formData.append('product_name', notesModalWarrantyObj.product_name);
+ formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
+ formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
+ if (!notesModalWarrantyObj.is_lifetime) {
+ // Append duration components instead of warranty_years
+ formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
+ formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
+ formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
+
+ // If all duration fields are 0 but we have an expiration date, this was created with exact date method
+ const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
+ notesModalWarrantyObj.expiration_date;
+
+ if (isExactDateWarranty) {
+ // For exact date warranties, send the expiration date as exact_expiration_date
+ formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
+ }
+ }
+ if (notesModalWarrantyObj.product_url) {
+ formData.append('product_url', notesModalWarrantyObj.product_url);
+ }
+ if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) {
+ formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
+ }
+ if (notesModalWarrantyObj.vendor) {
+ formData.append('vendor', notesModalWarrantyObj.vendor);
+ }
+ if (notesModalWarrantyObj.warranty_type) {
+ formData.append('warranty_type', notesModalWarrantyObj.warranty_type);
+ }
+ if (typeof notesModalWarrantyObj.model_number !== 'undefined' && notesModalWarrantyObj.model_number !== null) {
+ formData.append('model_number', notesModalWarrantyObj.model_number);
+ }
+ if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
+ notesModalWarrantyObj.serial_numbers.forEach(sn => {
+ if (sn && sn.trim() !== '') {
+ formData.append('serial_numbers[]', sn); // Use [] for arrays
+ }
+ });
+ } else if (!formData.has('serial_numbers[]')) {
+ // Send empty array if none exist
+ // formData.append('serial_numbers[]', ''); // Sending empty string might not work as expected, better to not send if empty
+ }
+ if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
+ const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ } else {
+ formData.append('tag_ids', JSON.stringify([]));
+ }
+ formData.append('notes', notesValue);
+ // Also include model number value from edit input if present on DOM
+ const editModelNumberInput = document.getElementById('editModelNumber');
+ if (editModelNumberInput && editModelNumberInput.value.trim() !== '') {
+ formData.set('model_number', editModelNumberInput.value.trim());
+ }
+ const response = await fetch(`/api/warranties/${warrantyId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to update notes');
+ }
+ hideLoadingSpinner();
+ showToast(window.t('messages.notes_updated_successfully'), 'success');
+ // Close the modal
+ const notesModal = document.getElementById('notesModal');
+ if (notesModal) notesModal.style.display = 'none';
+ // Now reload warranties and re-render UI
+ await loadWarranties();
+ applyFilters();
+ } catch (error) {
+ hideLoadingSpinner();
+ console.error('Error updating notes:', error);
+ showToast(error.message || window.t('messages.failed_to_update_notes'), 'error');
+ }
+ };
+ }
+
+// Initialize form tabs
+function initFormTabs() {
+ console.log('Initializing form tabs...');
+ // Use the modal context if available, otherwise query document
+ const modalContext = document.getElementById('addWarrantyModal'); // Assuming this is the context
+ const context = modalContext && modalContext.classList.contains('active') ? modalContext : document;
+
+ const tabsContainer = context.querySelector('.form-tabs');
+ // Re-query tabContents and formTabs within the correct context and update global variables
+ const contentsElements = context.querySelectorAll('.tab-content');
+ tabContents = contentsElements ? Array.from(contentsElements) : []; // Update global variable
+
+ const tabsElements = tabsContainer ? tabsContainer.querySelectorAll('.form-tab') : [];
+ formTabs = tabsElements ? Array.from(tabsElements) : []; // Update global variable
+
+ const nextButton = context.querySelector('#nextTabBtn'); // Use context
+ const prevButton = context.querySelector('#prevTabBtn'); // Use context
+ const submitButton = context.querySelector('#submitWarrantyBtn'); // Use context
+
+ // Use the updated global variables length for checks
+ if (!tabsContainer || !tabContents.length || !formTabs.length || !nextButton || !prevButton || !submitButton) {
+ console.warn('Form tab elements not found in the expected context. Skipping tab initialization.');
+ return; // Don't proceed if elements aren't present
+ }
+
+ // Remove the local 'tabs' and 'contents' variables, use global ones now
+ // let currentTabIndex = 0; // Already global
+ // const tabs = tabsContainer.querySelectorAll('.form-tab'); // Use global formTabs
+ // const contents = document.querySelectorAll('.tab-content'); // Use global tabContents
+
+ // Remove the inner switchToTab and updateNavigationButtons functions as they are defined globally
+ /*
+ function switchToTab(index) {
+ // ... removed inner function ...
+ }
+
+ function updateNavigationButtons() {
+ // ... removed inner function ...
+ }
+ */
+
+ // --- CLONE AND REPLACE NAV BUTTONS TO REMOVE OLD LISTENERS ---
+ // Ensure buttons exist before cloning
+ let nextButtonCloned = nextButton;
+ let prevButtonCloned = prevButton;
+ if (nextButton && prevButton) {
+ nextButtonCloned = nextButton.cloneNode(true);
+ prevButtonCloned = prevButton.cloneNode(true);
+ nextButton.parentNode.replaceChild(nextButtonCloned, nextButton);
+ prevButton.parentNode.replaceChild(prevButtonCloned, prevButton);
+ } else {
+ console.warn("Next/Prev buttons not found for cloning listeners.");
+ }
+
+
+ // ... (rest of initFormTabs, including event listeners, ensure element checks)
+ // Make sure event listeners use the correct global functions and variables
+ formTabs.forEach((tab, index) => { // Use global formTabs
+ if (tab) { // Check if tab exists
+ tab.addEventListener('click', () => {
+ // Allow clicking only on previous tabs if valid, or current
+ if (index < currentTabIndex) {
+ let canSwitch = true;
+ for (let i = 0; i < index; i++) {
+ // Ensure validateTab uses the correct global tabContents
+ if (!validateTab(i)) {
+ canSwitch = false;
+ break;
+ }
+ }
+ if (canSwitch) switchToTab(index); // Call global function
+ } else if (index === currentTabIndex) {
+ // Clicking current tab does nothing
+ } else {
+ // Try to navigate forward by clicking tab
+ // Ensure validateTab uses the correct global tabContents
+ if (validateTab(currentTabIndex)) {
+ // Mark current as completed
+ if(formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs
+ switchToTab(index); // Call global function
+ } else {
+ // If current tab is invalid, show errors for it
+ showValidationErrors(currentTabIndex);
+ }
+ }
+ });
+ }
+ });
+
+ if (nextButtonCloned) { // Check button exists
+ nextButtonCloned.addEventListener('click', () => {
+ // Ensure validateTab uses the correct global tabContents
+ if (validateTab(currentTabIndex)) {
+ if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs
+ // Use global formTabs length
+ if (currentTabIndex < formTabs.length - 1) { // <-- Ensure this uses formTabs.length
+ switchToTab(currentTabIndex + 1); // Call global function
+ }
+ } else {
+ // If current tab is invalid, show errors
+ showValidationErrors(currentTabIndex);
+ }
+ });
+ } else {
+ console.warn("Cloned Next button not found, listener not added.");
+ }
+
+ if (prevButtonCloned) { // Check button exists
+ prevButtonCloned.addEventListener('click', () => {
+ if (currentTabIndex > 0) {
+ switchToTab(currentTabIndex - 1);
+ }
+ });
+ }
+
+ // Initialize the first tab
+ switchToTab(0);
+}
+
+// Switch to a specific tab
+function switchToTab(index) {
+ console.log(`Switching to tab ${index} from tab ${currentTabIndex}`);
+
+ // Ensure index is within bounds
+ if (index < 0 || index >= formTabs.length) {
+ console.log(`Invalid tab index: ${index}, not switching`);
+ return;
+ }
+
+ // Update summary FIRST if switching TO the summary tab
+ if (index === formTabs.length - 1) {
+ updateSummary();
+ }
+
+ // Update active tab
+ formTabs.forEach(tab => tab.classList.remove('active'));
+ tabContents.forEach(content => content.classList.remove('active'));
+
+ formTabs[index].classList.add('active');
+ tabContents[index].classList.add('active');
+
+ // Update current tab index
+ currentTabIndex = index;
+
+ // Update progress indicator
+ document.querySelector('.form-tabs').setAttribute('data-step', currentTabIndex);
+
+ // Update completed tabs
+ updateCompletedTabs();
+
+ // Update navigation buttons
+ updateNavigationButtons();
+}
+
+// Update navigation buttons based on current tab
+function updateNavigationButtons() {
+ const prevButton = document.querySelector('.prev-tab');
+ const nextButton = document.querySelector('.next-tab');
+ const submitButton = document.querySelector('button[type="submit"]');
+
+ // Hide/show previous button
+ prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';
+
+ // Hide/show next button and submit button
+ if (currentTabIndex === formTabs.length - 1) {
+ nextButton.style.display = 'none';
+ submitButton.style.display = 'block';
+ } else {
+ nextButton.style.display = 'block';
+ submitButton.style.display = 'none';
+ }
+}
+
+// Update completed tabs
+function updateCompletedTabs() {
+ formTabs.forEach((tab, index) => {
+ if (index < currentTabIndex) {
+ tab.classList.add('completed');
+ } else {
+ tab.classList.remove('completed');
+ }
+ });
+}
+
+// Validate a specific tab
+function validateTab(tabIndex) {
+ const tabContent = tabContents[tabIndex];
+ const controls = tabContent.querySelectorAll('input, textarea, select');
+ let isTabValid = true;
+
+ controls.forEach(control => {
+ // Clear previous validation state
+ control.classList.remove('invalid');
+ let validationMessageElement = control.nextElementSibling;
+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement.remove();
+ }
+
+ // Manual validation for required fields
+ if (control.hasAttribute('required') && control.value.trim() === '') {
+ isTabValid = false;
+ control.classList.add('invalid');
+ // Mark as invalid, message will be added by showValidationErrors
+ } else if (!control.validity.valid) { // For other HTML5 validation issues (e.g., type mismatch)
+ isTabValid = false;
+ control.classList.add('invalid');
+ }
+ });
+ return isTabValid;
+}
+
+// Show validation errors for a specific tab
+function showValidationErrors(tabIndex) {
+ const tabContent = tabContents[tabIndex];
+ const controls = tabContent.querySelectorAll('input, textarea, select');
+ let firstInvalidControl = null;
+ let validationToast = document.querySelector('.validation-toast'); // Check for existing validation toast
+
+ controls.forEach(control => {
+ if (!control.validity.valid) {
+ if (!firstInvalidControl) firstInvalidControl = control;
+ control.classList.add('invalid');
+
+ // Add or update validation message
+ let validationMessageElement = control.nextElementSibling;
+ if (!validationMessageElement || !validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement = document.createElement('div');
+ validationMessageElement.className = 'validation-message';
+ control.parentNode.insertBefore(validationMessageElement, control.nextSibling);
+ }
+ if (control.hasAttribute('required') && control.value.trim() === '') {
+ validationMessageElement.textContent = window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.';
+ } else {
+ validationMessageElement.textContent = control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.');
+ }
+ } else {
+ // Ensure invalid class is removed if somehow missed by validateTab (shouldn't happen)
+ control.classList.remove('invalid');
+ // Remove validation message if control is now valid
+ let validationMessageElement = control.nextElementSibling;
+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement.remove();
+ }
+ }
+ });
+
+ // The browser will attempt to focus the first invalid field when form submission is prevented.
+ // Switching to the tab containing the error (done by handleFormSubmit) is key.
+
+ // Manage a single validation toast
+ if (!validationToast) {
+ validationToast = showToast(window.t('messages.correct_errors_in_tab'), 'error', 0); // 0 duration = persistent
+ validationToast.classList.add('validation-toast'); // Add a class to identify it
+ } else {
+ // Update existing toast message if needed (optional)
+ validationToast.querySelector('span').textContent = window.t('messages.correct_errors_in_tab');
+ }
+}
+
+// Update summary tab with current form values
+function updateSummary() {
+ // Product information
+ const summaryProductName = document.getElementById('summary-product-name');
+ if (summaryProductName) {
+ summaryProductName.textContent =
+ document.getElementById('productName')?.value || '-';
+ }
+
+ const summaryProductUrl = document.getElementById('summary-product-url');
+ if (summaryProductUrl) {
+ summaryProductUrl.textContent =
+ document.getElementById('productUrl')?.value || '-';
+ }
+
+ // Serial numbers
+ const serialNumbers = [];
+ document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {
+ if (input && input.value && input.value.trim()) {
+ serialNumbers.push(input.value.trim());
+ }
+ });
+
+ const serialNumbersContainer = document.getElementById('summary-serial-numbers');
+ if (serialNumbersContainer) {
+ if (serialNumbers.length > 0) {
+ serialNumbersContainer.innerHTML = '<ul>' +
+ serialNumbers.map(sn => `<li>${sn}</li>`).join('') +
+ '</ul>';
+ } else {
+ serialNumbersContainer.textContent = 'None';
+ }
+ }
+
+ // Warranty details
+ const purchaseDateStr = document.getElementById('purchaseDate')?.value;
+ const summaryPurchaseDate = document.getElementById('summary-purchase-date');
+ if (summaryPurchaseDate) {
+ if (purchaseDateStr) {
+ // Use the same logic as formatDate to handle YYYY-MM-DD
+ const parts = String(purchaseDateStr).split('-');
+ let formattedDate = '-'; // Default
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
+ const day = parseInt(parts[2], 10);
+ const dateObj = new Date(Date.UTC(year, month, day));
+ if (!isNaN(dateObj.getTime())) {
+ // Format manually (example: Jan 1, 2023)
+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ formattedDate = `${monthNames[month]} ${day}, ${year}`;
+ }
+ }
+ summaryPurchaseDate.textContent = formattedDate;
+ } else {
+ summaryPurchaseDate.textContent = '-';
+ }
+ }
+
+ // --- Handle Lifetime in Summary ---
+ const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;
+ const summaryWarrantyDuration = document.getElementById('summary-warranty-duration'); // Use new ID
+
+ if (summaryWarrantyDuration) {
+ if (isLifetime) {
+ summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
+ } else {
+ const years = parseInt(warrantyDurationYearsInput?.value || 0);
+ const months = parseInt(warrantyDurationMonthsInput?.value || 0);
+ const days = parseInt(warrantyDurationDaysInput?.value || 0);
+
+ let durationParts = [];
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ durationParts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ durationParts.push(`${months} ${monthText}`);
+ }
+ if (days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ durationParts.push(`${days} ${dayText}`);
+ }
+
+ summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';
+ }
+ }
+
+ // Warranty type - handle dropdown and custom input
+ const warrantyTypeSelect = document.getElementById('warrantyType');
+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
+ const summaryWarrantyType = document.getElementById('summary-warranty-type');
+ if (summaryWarrantyType) {
+ let warrantyTypeText = 'Not specified';
+ if (warrantyTypeSelect && warrantyTypeSelect.value) {
+ if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
+ warrantyTypeText = warrantyTypeCustom.value.trim();
+ } else if (warrantyTypeSelect.value !== 'other') {
+ warrantyTypeText = warrantyTypeSelect.value;
+ }
+ }
+ summaryWarrantyType.textContent = warrantyTypeText;
+ }
+
+ // Purchase price
+ const purchasePrice = document.getElementById('purchasePrice')?.value;
+ const currency = document.getElementById('currency')?.value;
+ const summaryPurchasePrice = document.getElementById('summary-purchase-price');
+ if (summaryPurchasePrice) {
+ if (purchasePrice) {
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ const amount = parseFloat(purchasePrice).toFixed(2);
+ summaryPurchasePrice.innerHTML = formatCurrencyHTML(amount, symbol, position);
+ } else {
+ summaryPurchasePrice.textContent = 'Not specified';
+ }
+ }
+
+ // Documents
+ const productPhotoFile = document.getElementById('productPhoto')?.files[0];
+ const summaryProductPhoto = document.getElementById('summary-product-photo');
+ if (summaryProductPhoto) {
+ summaryProductPhoto.textContent = productPhotoFile ?
+ productPhotoFile.name : 'No photo selected';
+ }
+
+ const invoiceFile = document.getElementById('invoice')?.files[0];
+ const invoiceUrlField = document.getElementById('invoiceUrl');
+ const invoiceUrl = invoiceUrlField ? invoiceUrlField.value : '';
+ const summaryInvoice = document.getElementById('summary-invoice');
+ if (summaryInvoice) {
+ if (invoiceFile) {
+ summaryInvoice.textContent = invoiceFile.name;
+ } else if (invoiceUrl) {
+ summaryInvoice.textContent = 'URL: ' + invoiceUrl;
+ } else {
+ summaryInvoice.textContent = 'Not specified';
+ }
+ }
+
+ const manualFile = document.getElementById('manual')?.files[0];
+ const manualUrlField = document.getElementById('manualUrl');
+ const manualUrl = manualUrlField ? manualUrlField.value : '';
+ const summaryManual = document.getElementById('summary-manual');
+ if (summaryManual) {
+ if (manualFile) {
+ summaryManual.textContent = manualFile.name;
+ } else if (manualUrl) {
+ summaryManual.textContent = 'URL: ' + manualUrl;
+ } else {
+ summaryManual.textContent = 'Not specified';
+ }
+ }
+
+ const otherDocumentFile = document.getElementById('otherDocument')?.files[0];
+ const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
+ const otherDocumentUrl = otherDocumentUrlField ? otherDocumentUrlField.value : '';
+ const summaryOtherDocument = document.getElementById('summary-other-document');
+ if (summaryOtherDocument) {
+ if (otherDocumentFile) {
+ summaryOtherDocument.textContent = otherDocumentFile.name;
+ } else if (otherDocumentUrl) {
+ summaryOtherDocument.textContent = 'URL: ' + otherDocumentUrl;
+ } else {
+ summaryOtherDocument.textContent = 'Not specified';
+ }
+ }
+
+ // Tags
+ const summaryTags = document.getElementById('summary-tags');
+ if (summaryTags) {
+ if (selectedTags && selectedTags.length > 0) {
+ summaryTags.innerHTML = '';
+
+ selectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
+ tagElement.textContent = tag.name;
+
+ summaryTags.appendChild(tagElement);
+ });
+ } else {
+ summaryTags.textContent = 'No tags selected';
+ }
+ }
+
+ // Vendor/Retailer
+ const vendor = document.getElementById('vendor');
+ document.getElementById('summary-vendor').textContent = vendor && vendor.value ? vendor.value : '-';
+}
+
+// Add input event listeners to remove validation errors when user types
+document.addEventListener('input', (e) => {
+ if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {
+ if (e.target.value.trim()) {
+ e.target.classList.remove('invalid');
+
+ // Remove validation message if exists
+ const validationMessage = e.target.nextElementSibling;
+ if (validationMessage && validationMessage.classList.contains('validation-message')) {
+ validationMessage.remove();
+ }
+ }
+ }
+});
+
+// Function to reset the form and initialize serial number inputs
+function resetForm() {
+ // Reset the form
+ warrantyForm.reset();
+
+ // Reset serial numbers container
+ serialNumbersContainer.innerHTML = '';
+
+ // Add the first serial number input
+ addSerialNumberInput();
+
+ // Reset form tabs
+ currentTabIndex = 0;
+ switchToTab(0);
+
+ // Clear any file input displays
+ const productPhotoFileName = document.getElementById('productPhotoFileName');
+ if (productPhotoFileName) productPhotoFileName.textContent = '';
+ fileName.textContent = '';
+ manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+
+ // Reset photo preview
+ const productPhotoPreview = document.getElementById('productPhotoPreview');
+ if (productPhotoPreview) {
+ productPhotoPreview.style.display = 'none';
+ }
+}
+
+async function exportWarranties() {
+ console.log('[EXPORT DEBUG] Starting export process');
+ console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);
+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);
+
+ // Get filtered warranties
+ let warrantiesToExport = [...warranties];
+ console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
+
+ // Apply current filters
+ if (currentFilters.search) {
+ const searchTerm = currentFilters.search.toLowerCase();
+ console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
+ warrantiesToExport = warrantiesToExport.filter(warranty => {
+ // Check if product name contains search term
+ const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
+
+ // Check if any tag name contains search term
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
+
+ // Check if vendor name contains search term
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+
+ // Return true if either product name, tag name, or vendor name matches
+ return productNameMatch || tagMatch || vendorMatch;
+ });
+ console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.status !== 'all') {
+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.status === currentFilters.status
+ );
+ console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
+ }
+
+ // Apply tag filter
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId)
+ );
+ console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
+ }
+
+ // Apply vendor filter
+ if (currentFilters.vendor !== 'all') {
+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
+ }
+
+ // Apply warranty type filter
+ if (currentFilters.warranty_type !== 'all') {
+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
+ }
+
+ console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
+ console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
+
+ // Create CSV content
+ let csvContent = "data:text/csv;charset=utf-8,";
+
+ // Add headers - Updated for duration components
+ csvContent += "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n";
+
+ // Add data rows
+ warrantiesToExport.forEach(warranty => {
+ // Format serial numbers as comma-separated string
+ const serialNumbers = Array.isArray(warranty.serial_numbers)
+ ? warranty.serial_numbers.filter(s => s).join(', ')
+ : '';
+
+ // Format tags as comma-separated string
+ const tags = Array.isArray(warranty.tags)
+ ? warranty.tags.map(tag => tag.name).join(', ')
+ : '';
+
+ // Format row data - Updated for duration components
+ const row = [
+ warranty.product_name || '',
+ formatDateYYYYMMDD(new Date(warranty.purchase_date)),
+ warranty.is_lifetime ? 'TRUE' : 'FALSE',
+ warranty.warranty_duration_years || 0,
+ warranty.warranty_duration_months || 0,
+ warranty.warranty_duration_days || 0,
+ warranty.is_lifetime ? '' : formatDateYYYYMMDD(new Date(warranty.expiration_date)), // Expiration date empty for lifetime
+ warranty.status || '',
+ warranty.purchase_price || '',
+ serialNumbers,
+ warranty.product_url || '',
+ tags,
+ warranty.vendor || ''
+ ];
+
+ // Add row to CSV content
+ csvContent += row.map(field => `"${field.toString().replace(/"/g, '""')}"`).join(',') + '\n';
+ });
+
+ // Create a download link
+ const encodedUri = encodeURI(csvContent);
+ const link = document.createElement('a');
+ link.setAttribute('href', encodedUri);
+ link.setAttribute('download', `warranties_export_${formatDate(new Date())}.csv`);
+ document.body.appendChild(link);
+
+ // Trigger download
+ link.click();
+
+ // Clean up
+ document.body.removeChild(link);
+
+ // Show success notification
+ showToast(window.t('messages.exported_warranties_successfully', {count: warrantiesToExport.length}), 'success');
+}
+
+// Switch view of warranties list
+async function switchView(viewType, saveToApi = true) { // Added saveToApi parameter with default true
+ console.log(`Switching to view: ${viewType}`);
+ currentView = viewType;
+
+ const prefix = getPreferenceKeyPrefix();
+ const viewKey = `${prefix}defaultView`;
+ const currentStoredValue = localStorage.getItem(viewKey);
+
+ // Save to localStorage immediately for responsiveness
+ if (currentStoredValue !== viewType) {
+ localStorage.setItem(viewKey, viewType);
+ // Keep legacy keys for now if needed, but primary is viewKey
+ localStorage.setItem(`${prefix}warrantyView`, viewType);
+ localStorage.setItem('viewPreference', viewType);
+ console.log(`Saved view preference (${viewKey}) to localStorage: ${viewType}`);
+ } else {
+ console.log(`View preference (${viewKey}) already set to ${viewType} in localStorage.`);
+ }
+
+ // --- MODIFIED: Only save preference to API if saveToApi is true ---
+ if (saveToApi && window.auth && window.auth.isAuthenticated()) {
+ const token = window.auth.getToken();
+ if (token) {
+ try {
+ console.log(`Attempting to save view preference (${viewType}) to API...`);
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ default_view: viewType }) // Send only the changed preference
+ });
+
+ if (response.ok) {
+ console.log('Successfully saved view preference to API.');
+ } else {
+ const errorData = await response.json().catch(() => ({}));
+ console.warn(`Failed to save view preference to API: ${response.status}`, errorData.message || '');
+ // Optional: Show a non-intrusive warning toast?
+ // showToast('Failed to sync view preference with server.', 'warning');
+ }
+ } catch (error) {
+ console.error('Error saving view preference to API:', error);
+ // Optional: Show a non-intrusive warning toast?
+ // showToast('Error syncing view preference with server.', 'error');
+ }
+ } else {
+ console.warn('Cannot save view preference to API: No auth token found.');
+ }
+ } else if (!saveToApi) {
+ console.log('Skipping API save as saveToApi is false (likely called from loadViewPreference).');
+ } else {
+ console.warn('Cannot save view preference to API: User not authenticated or auth module not loaded.');
+ }
+ // --- END MODIFIED: Save preference to API ---
+
+ // Make sure warrantiesList exists before modifying classes
+ if (warrantiesList) {
+ warrantiesList.classList.remove('grid-view', 'list-view', 'table-view');
+ warrantiesList.classList.add(`${viewType}-view`);
+ }
+
+ // Make sure view buttons exist
+ if (gridViewBtn && listViewBtn && tableViewBtn) {
+ gridViewBtn.classList.remove('active');
+ listViewBtn.classList.remove('active');
+ tableViewBtn.classList.remove('active');
+ // Add active class to the correct button
+ if (viewType === 'grid') gridViewBtn.classList.add('active');
+ if (viewType === 'list') listViewBtn.classList.add('active');
+ if (viewType === 'table') tableViewBtn.classList.add('active');
+ }
+
+ // Show/hide table header only if it exists
+ if (tableViewHeader) {
+ tableViewHeader.classList.toggle('visible', viewType === 'table');
+ }
+
+ // Re-apply current filters after view change to preserve user's selection
+ try {
+ // Persist current filters before render (defensive no-op if unchanged)
+ // Skip API save on initial load to mirror view settings behavior
+ saveFilterPreferences(false);
+ } catch (_) {}
+
+ if (warrantiesList && warrantiesLoaded) {
+ // Reapply full filter set (status, tag, vendor, type, search, sort)
+ applyFilters();
+ }
+
+ // Update header dropdown label if present
+ try {
+ const currentViewIcon = document.getElementById('currentViewIcon');
+ if (currentViewIcon) {
+ currentViewIcon.className = 'fas';
+ if (viewType === 'list') {
+ currentViewIcon.classList.add('fa-list');
+ currentViewIcon.setAttribute('aria-label', 'List');
+ } else if (viewType === 'table') {
+ currentViewIcon.classList.add('fa-table');
+ currentViewIcon.setAttribute('aria-label', 'Table');
+ } else {
+ currentViewIcon.classList.add('fa-th-large');
+ currentViewIcon.setAttribute('aria-label', 'Grid');
+ }
+ }
+ } catch (e) { /* no-op */ }
+}
+
+// Load view preference from localStorage
+function loadViewPreference() {
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ let savedView = null;
+
+ // --- BEGIN EDIT: Check keys in priority order ---
+ const userSpecificView = localStorage.getItem(`${prefix}defaultView`);
+ const generalView = localStorage.getItem('viewPreference');
+ const legacyWarrantyView = localStorage.getItem(`${prefix}warrantyView`);
+
+ if (userSpecificView) {
+ savedView = userSpecificView;
+ console.log(`Loaded view preference from ${prefix}defaultView:`, savedView);
+ } else if (generalView) {
+ savedView = generalView;
+ console.log('Loaded view preference from viewPreference:', savedView);
+ } else if (legacyWarrantyView) {
+ savedView = legacyWarrantyView;
+ console.log(`Loaded view preference from legacy ${prefix}warrantyView:`, savedView);
+ }
+ // --- END EDIT ---
+
+ // Default to grid view if no preference is saved
+ savedView = savedView || 'grid';
+
+ console.log(`Applying view preference from loadViewPreference: ${savedView}`);
+ // Switch view only if view buttons exist (implying it's the main page)
+ if (gridViewBtn || listViewBtn || tableViewBtn) {
+ switchView(savedView, false); // Pass false to prevent API save on initial load
+ }
+}
+
+// Dark mode toggle
+if (darkModeToggle) { // Add check for darkModeToggle
+ darkModeToggle.addEventListener('change', (e) => {
+ saveThemePreference(e.target.checked);
+ });
+}
+
+// Add event listener for adding new serial number inputs
+// Add check for serialNumbersContainer before adding listener
+if (serialNumbersContainer) {
+ serialNumbersContainer.addEventListener('click', (e) => {
+ if (e.target.closest('.add-serial-number')) {
+ addSerialNumberInput();
+ }
+ });
+}
+
+// Add a serial number input field
+function addSerialNumberInput(container = serialNumbersContainer) {
+ // Check if the container exists before proceeding
+ if (!container) {
+ console.warn('Serial numbers container not found, cannot add input.');
+ return;
+ }
+
+ const div = document.createElement('div');
+ div.className = 'serial-number-input d-flex mb-2';
+
+ // Create an input element
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'form-control';
+ input.name = 'serial_numbers[]';
+ input.placeholder = window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number';
+ console.log('i18next available for serial number placeholder:', !!window.i18next);
+ if (window.i18next) {
+ console.log('Translation for warranties.enter_serial_number:', window.i18next.t('warranties.enter_serial_number'));
+ }
+
+ // Check if this is the first serial number input
+ const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;
+
+ // Append input to the input group
+ div.appendChild(input);
+
+ // Only add remove button if this is not the first input
+ if (!isFirstInput) {
+ // Create a remove button
+ const removeButton = document.createElement('button');
+ removeButton.type = 'button';
+ removeButton.className = 'btn btn-sm btn-danger remove-serial';
+ removeButton.innerHTML = '<i class="fas fa-times"></i>';
+
+ // Add event listener to remove button
+ removeButton.addEventListener('click', function() {
+ container.removeChild(div);
+ });
+
+ // Append remove button to the input group
+ div.appendChild(removeButton);
+ }
+
+ // Insert the new input group before the add button
+ const addButton = container.querySelector('.add-serial');
+ if (addButton) {
+ container.insertBefore(div, addButton);
+ } else {
+ container.appendChild(div);
+
+ // Create and append an add button if it doesn't exist
+ const addButton = document.createElement('button');
+ addButton.type = 'button';
+ addButton.className = 'btn btn-sm btn-secondary add-serial';
+ addButton.innerHTML = '<i class="fas fa-plus"></i> ' + (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');
+ console.log('i18next available in addSerialNumberInput:', !!window.i18next);
+ if (window.i18next) {
+ console.log('Translation for warranties.add_serial_number:', window.i18next.t('warranties.add_serial_number'));
+ }
+
+ addButton.addEventListener('click', function() {
+ addSerialNumberInput(container);
+ });
+
+ container.appendChild(addButton);
+ }
+}
+
+// Functions
+function showLoading() {
+ let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
+ if (localLoadingContainer) {
+ localLoadingContainer.classList.add('active');
+ window.loadingContainer = localLoadingContainer; // Update global reference if found
+ } else {
+ console.error('WarrackerDebug: loadingContainer element not found by showLoading(). Ensure it exists in the HTML and script.js is loaded after it.');
+ }
+}
+
+function hideLoading() {
+ let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
+ if (localLoadingContainer) {
+ localLoadingContainer.classList.remove('active');
+ window.loadingContainer = localLoadingContainer; // Update global reference if found
+ } else {
+ console.error('WarrackerDebug: loadingContainer element not found by hideLoading().');
+ }
+}
+
+function showToast(message, type = 'info', duration = 5000) {
+ // Check if a toast with the same message and type already exists
+ const existingToasts = document.querySelectorAll(`.toast.toast-${type}`);
+ for (let i = 0; i < existingToasts.length; i++) {
+ const span = existingToasts[i].querySelector('span');
+ if (span && span.textContent === message) {
+ return existingToasts[i]; // Don't create a new one
+ }
+ }
+
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ const icon = document.createElement('i');
+ switch (type) {
+ case 'success':
+ icon.className = 'fas fa-check-circle';
+ break;
+ case 'error':
+ icon.className = 'fas fa-exclamation-circle';
+ break;
+ case 'warning':
+ icon.className = 'fas fa-exclamation-triangle';
+ break;
+ default:
+ icon.className = 'fas fa-info-circle';
+ }
+
+ const messageSpan = document.createElement('span');
+ messageSpan.textContent = message;
+
+ toast.appendChild(icon);
+ toast.appendChild(messageSpan);
+
+ toastContainer.appendChild(toast);
+
+ // Add a method to remove the toast
+ toast.remove = function() {
+ toast.classList.add('toast-fade-out');
+ setTimeout(() => {
+ if (toast.parentNode) {
+ toast.parentNode.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Auto-hide toast after specified duration (if not 0)
+ if (duration > 0) {
+ setTimeout(() => {
+ toast.remove();
+ }, duration);
+ }
+
+ return toast;
+}
+
+// Update file name display when a file is selected
+function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
+ const file = event.target.files[0];
+ const output = document.getElementById(outputId);
+
+ if (file && output) {
+ output.textContent = file.name;
+ } else if (output) {
+ output.textContent = '';
+ }
+
+ // Handle photo preview for product photo
+ if (inputId === 'productPhoto' || inputId === 'editProductPhoto') {
+ const previewId = inputId === 'productPhoto' ? 'productPhotoPreview' : 'editProductPhotoPreview';
+ const imgId = inputId === 'productPhoto' ? 'productPhotoImg' : 'editProductPhotoImg';
+ const preview = document.getElementById(previewId);
+ const img = document.getElementById(imgId);
+
+ if (file && file.type.startsWith('image/')) {
+ const reader = new FileReader();
+ reader.onload = function(e) {
+ img.src = e.target.result;
+ preview.style.display = 'block';
+ };
+ reader.readAsDataURL(file);
+ } else {
+ preview.style.display = 'none';
+ }
+ }
+}
+
+// Helper function to process warranty data
+function processWarrantyData(warranty) {
+ console.log('Processing warranty data:', warranty);
+
+ // Create a copy of the warranty object to avoid modifying the original
+ const processedWarranty = { ...warranty };
+ // Flag archived items when merged into All view
+ processedWarranty.is_archived = !!(warranty.__isArchived || warranty.is_archived);
+
+ // Ensure product_name exists
+ if (!processedWarranty.product_name) {
+ processedWarranty.product_name = 'Unnamed Product';
+ }
+
+ const today = new Date();
+ today.setHours(0, 0, 0, 0); // Normalize today to midnight for accurate date comparisons
+
+ // Parse purchase_date string (YYYY-MM-DD) into a UTC Date object
+ let purchaseDateObj = null;
+ if (processedWarranty.purchase_date) {
+ const parts = String(processedWarranty.purchase_date).split('-');
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
+ const day = parseInt(parts[2], 10);
+ purchaseDateObj = new Date(Date.UTC(year, month, day));
+ if (isNaN(purchaseDateObj.getTime())) {
+ purchaseDateObj = null; // Invalid date parsed
+ }
+ } else {
+ // Fallback for unexpected formats, though backend should send YYYY-MM-DD
+ purchaseDateObj = new Date(processedWarranty.purchase_date);
+ if (isNaN(purchaseDateObj.getTime())) {
+ purchaseDateObj = null;
+ }
+ }
+ }
+ processedWarranty.purchaseDate = purchaseDateObj;
+
+ // Parse expiration_date similarly (assuming it's also YYYY-MM-DD)
+ let expirationDateObj = null;
+ if (processedWarranty.expiration_date) {
+ const parts = String(processedWarranty.expiration_date).split('-');
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1;
+ const day = parseInt(parts[2], 10);
+ expirationDateObj = new Date(Date.UTC(year, month, day));
+ if (isNaN(expirationDateObj.getTime())) {
+ expirationDateObj = null;
+ }
+ } else {
+ expirationDateObj = new Date(processedWarranty.expiration_date);
+ if (isNaN(expirationDateObj.getTime())) {
+ expirationDateObj = null;
+ }
+ }
+ }
+ processedWarranty.expirationDate = expirationDateObj;
+
+ // --- Lifetime Handling ---
+ if (processedWarranty.is_lifetime) {
+ processedWarranty.status = 'active';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
+ processedWarranty.daysRemaining = Infinity;
+ // Ensure duration components are 0 for lifetime
+ processedWarranty.warranty_duration_years = 0;
+ processedWarranty.warranty_duration_months = 0;
+ processedWarranty.warranty_duration_days = 0;
+ } else if (processedWarranty.expirationDate && !isNaN(processedWarranty.expirationDate.getTime())) {
+ // Existing logic for dated warranties
+ const expirationDateOnly = new Date(processedWarranty.expirationDate);
+ expirationDateOnly.setHours(0,0,0,0);
+
+ const timeDiff = expirationDateOnly - today;
+ const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+ processedWarranty.daysRemaining = daysRemaining;
+
+ if (daysRemaining < 0) {
+ processedWarranty.status = 'expired';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.expired') : 'Expired';
+ } else if (daysRemaining < expiringSoonDays) {
+ processedWarranty.status = 'expiring';
+ const dayText = window.i18next ?
+ window.i18next.t('warranties.day', {count: daysRemaining}) :
+ `day${daysRemaining !== 1 ? 's' : ''}`;
+ processedWarranty.statusText = window.i18next ?
+ window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
+ `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
+ } else {
+ processedWarranty.status = 'active';
+ const dayText = window.i18next ?
+ window.i18next.t('warranties.day', {count: daysRemaining}) :
+ `day${daysRemaining !== 1 ? 's' : ''}`;
+ processedWarranty.statusText = window.i18next ?
+ window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
+ `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
+ }
+
+ // Preserve original duration values to detect input method
+ const originalYears = processedWarranty.warranty_duration_years || 0;
+ const originalMonths = processedWarranty.warranty_duration_months || 0;
+ const originalDays = processedWarranty.warranty_duration_days || 0;
+
+ // Track the original input method based on duration values
+ const wasExactDateMethod = originalYears === 0 && originalMonths === 0 && originalDays === 0;
+ processedWarranty.original_input_method = wasExactDateMethod ? 'exact_date' : 'duration';
+
+ // Calculate duration from dates if all duration components are 0 (exact date method was used)
+ const hasNoDuration = originalYears === 0 && originalMonths === 0 && originalDays === 0;
+
+ if (hasNoDuration && purchaseDateObj && processedWarranty.expirationDate) {
+ console.log('[DEBUG] Calculating duration from dates for exact date warranty');
+ const calculatedDuration = calculateDurationFromDates(
+ purchaseDateObj.toISOString().split('T')[0],
+ processedWarranty.expirationDate.toISOString().split('T')[0]
+ );
+ if (calculatedDuration) {
+ // Store calculated duration for display purposes
+ processedWarranty.display_duration_years = calculatedDuration.years;
+ processedWarranty.display_duration_months = calculatedDuration.months;
+ processedWarranty.display_duration_days = calculatedDuration.days;
+ console.log('[DEBUG] Calculated duration:', calculatedDuration);
+
+ // Keep original values at 0 to preserve input method detection
+ processedWarranty.warranty_duration_years = 0;
+ processedWarranty.warranty_duration_months = 0;
+ processedWarranty.warranty_duration_days = 0;
+ }
+ } else {
+ // Use original duration values for display
+ processedWarranty.display_duration_years = originalYears;
+ processedWarranty.display_duration_months = originalMonths;
+ processedWarranty.display_duration_days = originalDays;
+ }
+ } else {
+ processedWarranty.status = 'unknown';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.unknown_status') : 'Unknown Status';
+ processedWarranty.daysRemaining = null;
+ }
+
+ console.log('Processed warranty data result:', processedWarranty);
+ return processedWarranty;
+}
+
+// Function to process all warranties in the array
+function processAllWarranties() {
+ console.log('Processing all warranties in array...');
+ if (warranties && warranties.length > 0) {
+ if (window.store && window.store.setWarranties) {
+ window.store.setWarranties(warranties.map(warranty => processWarrantyData(warranty)));
+ }
+ warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : warranties;
+ }
+ console.log('Processed warranties:', warranties);
+}
+
+async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameter
+ // +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) +++
+ // await loadAndApplyUserPreferences();
+ // +++ Preferences Loaded +++
+
+ try {
+ console.log('[DEBUG] Entered loadWarranties, isAuthenticated:', isAuthenticated);
+
+ // Reset the flag when starting to load warranties
+ warrantiesLoaded = false;
+
+ showLoading();
+
+ // Fetch user preferences (including date format) before loading warranties
+ // --- THIS INNER PREFERENCE FETCH IS NOW REDUNDANT, REMOVE/COMMENT OUT ---
+ /*
+ try {
+ const token = window.auth.getToken(); // Ensure token is retrieved here
+ if (!token) throw new Error("No auth token found"); // Added error handling
+
+ const prefsResponse = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+
+ if (prefsResponse.ok) {
+ const prefsData = await prefsResponse.json();
+ console.log("Preferences fetched in loadWarranties:", prefsData);
+
+ // Update expiringSoonDays
+ if (prefsData && typeof prefsData.expiring_soon_days !== 'undefined') {
+ const oldValue = expiringSoonDays;
+ expiringSoonDays = prefsData.expiring_soon_days;
+ console.log('Updated expiring soon days from preferences:', expiringSoonDays);
+ // Reprocess logic moved below warranty fetch
+ }
+
+ // --- ADDED: Update dateFormat in localStorage ---
+ if (prefsData && typeof prefsData.date_format !== 'undefined') {
+ const oldDateFormat = localStorage.getItem('dateFormat');
+ localStorage.setItem('dateFormat', prefsData.date_format);
+ console.log(`Updated dateFormat in localStorage from API: ${prefsData.date_format}`);
+ // Trigger re-render if format changed and warranties already exist (though unlikely at this stage)
+ if (warranties && warranties.length > 0 && oldDateFormat !== prefsData.date_format) {
+ console.log('Date format changed, triggering re-render via applyFilters');
+ applyFilters(); // Re-render warranties with new format
+ }
+ } else {
+ // If API doesn't return date_format, ensure localStorage has a default
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('API did not return date_format, setting localStorage default to MDY');
+ }
+ }
+ // --- END ADDED SECTION ---
+
+ } else {
+ // Handle failed preference fetch
+ console.warn('Failed to fetch preferences:', prefsResponse.status);
+ // Ensure a default date format exists if fetch fails
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('Preferences fetch failed, setting localStorage default date format to MDY');
+ }
+ }
+ } catch (error) {
+ console.error('Error loading preferences:', error);
+ // Ensure a default date format exists on error
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('Error fetching preferences, setting localStorage default date format to MDY');
+ }
+ // Continue loading warranties even if preferences fail
+ }
+ */
+ // --- END REDUNDANT PREFERENCE FETCH ---
+
+ // Check saved view scope preference to determine which API endpoint to use
+ const savedScope = loadViewScopePreference();
+ const shouldUseGlobalView = savedScope === 'global';
+
+ // Use the appropriate API endpoint based on saved preference
+ const baseUrl = window.location.origin;
+ // If status is 'archived', use archived endpoint (support global vs personal)
+ const isArchivedView = currentFilters && currentFilters.status === 'archived';
+ const apiUrl = isArchivedView
+ ? (shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`)
+ : (shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`);
+
+ console.log(`[DEBUG] Using API endpoint based on saved preference '${savedScope}', archivedView=${isArchivedView}: ${apiUrl}`);
+
+ // Check if auth is available and user is authenticated using the passed parameter
+ if (!isAuthenticated) {
+ console.log('[DEBUG] loadWarranties: Early return - User not authenticated based on passed parameter.');
+ renderEmptyState(window.t('messages.login_to_view_warranties'));
+ hideLoading();
+ return;
+ }
+ // Get the auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ console.log('[DEBUG] Early return: No auth token available');
+ renderEmptyState(window.t('messages.authentication_error_login_again'));
+ hideLoading();
+ return;
+ }
+
+ // Create request with auth header
+ const options = {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ };
+
+ console.log('Fetching warranties with auth token');
+ const response = await fetch(apiUrl, options);
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
+ console.error('Error loading warranties:', response.status, errorData);
+ throw new Error(`Error loading warranties: ${errorData.message || response.status}`);
+ }
+ const data = await response.json();
+ console.log('[DEBUG] Received warranties from server:', data);
+ if (!Array.isArray(data)) {
+ console.error('[DEBUG] API did not return an array! Data:', data);
+ }
+
+ // Update isGlobalView to match the loaded data
+ isGlobalView = shouldUseGlobalView;
+ console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
+
+ // Optionally merge archived items into the "All" view (only in personal scope)
+ let combinedData = Array.isArray(data) ? data : [];
+ lastLoadedIncludesArchived = false;
+ if (!isArchivedView && currentFilters && currentFilters.status === 'all') {
+ try {
+ const archivedUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`;
+ const archivedResp = await fetch(archivedUrl, options);
+ if (archivedResp.ok) {
+ const archivedData = await archivedResp.json();
+ const archivedMarked = Array.isArray(archivedData)
+ ? archivedData.map(w => ({ ...w, __isArchived: true }))
+ : [];
+ combinedData = combinedData.concat(archivedMarked);
+ lastLoadedIncludesArchived = true;
+ console.log(`[DEBUG] Merged ${archivedMarked.length} archived warranties into All view`);
+ } else {
+ // Log but do not block rendering of non-archived warranties
+ let errInfo = '';
+ try {
+ const errJson = await archivedResp.json();
+ errInfo = JSON.stringify(errJson);
+ } catch (_) {}
+ console.warn('[DEBUG] Failed to load archived warranties for All view:', archivedResp.status, errInfo);
+ }
+ } catch (mergeErr) {
+ console.warn('[DEBUG] Error while merging archived into All:', mergeErr);
+ }
+ }
+
+ // Process each warranty to calculate status and days remaining
+ if (window.store && window.store.setWarranties) {
+ window.store.setWarranties(Array.isArray(combinedData) ? combinedData.map(warranty => processWarrantyData(warranty)) : []);
+ }
+ warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : (Array.isArray(combinedData) ? combinedData.map(warranty => processWarrantyData(warranty)) : []);
+ lastLoadedArchived = isArchivedView;
+ console.log('[DEBUG] Final warranties array:', warranties);
+ console.log('[DEBUG] Total warranties loaded:', warranties.length);
+ console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));
+
+ // Set flag to indicate warranties have been loaded from API
+ warrantiesLoaded = true;
+
+ if (warranties.length === 0) {
+ console.log('No warranties found, showing empty state');
+ renderEmptyState(window.t('messages.no_warranties_found_add_first'));
+ } else {
+ console.log('Applying filters to display warranties');
+
+ // Populate tag filter dropdown with tags from warranties
+ populateTagFilter();
+ populateVendorFilter(); // Added call to populate vendor filter
+ populateWarrantyTypeFilter(); // Added call to populate warranty type filter
+
+ // Ensure the UI reflects the freshly loaded data
+ applyFilters();
+ }
+ } catch (error) {
+ console.error('[DEBUG] Error loading warranties:', error);
+ warrantiesLoaded = false; // Reset flag on error
+ renderEmptyState(window.t('messages.error_loading_warranties_try_again'));
+ } finally {
+ hideLoading();
+ }
+}
+
+function renderEmptyState(message = 'No warranties yet. Add your first warranty to get started.') {
+ if (window.components && window.components.ui && window.components.ui.renderEmptyState && warrantiesList) {
+ window.components.ui.renderEmptyState(warrantiesList, message);
+ return;
+ }
+ warrantiesList.innerHTML = `
+ <div class="empty-state">
+ <i class="fas fa-box-open"></i>
+ <h3>${window.t ? window.t('messages.no_warranties_found') : 'No warranties found'}</h3>
+ <p>${message || (window.t ? window.t('messages.no_warranties_found_add_first') : 'No warranties yet. Add your first warranty to get started.')}</p>
+ </div>
+ `;
+}
+
+function formatDate(date) {
+ // Input 'date' should now be a Date object created by processWarrantyData (or null)
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
+ return 'N/A';
+ }
+
+ // Get the user's preferred format from localStorage, default to MDY
+ const formatPreference = localStorage.getItem('dateFormat') || 'MDY';
+
+ // Manually extract UTC components to avoid timezone discrepancies
+ const year = date.getUTCFullYear();
+ const monthIndex = date.getUTCMonth(); // 0-indexed for month names array
+ const day = date.getUTCDate();
+
+ // Padded numeric values
+ const monthPadded = (monthIndex + 1).toString().padStart(2, '0');
+ const dayPadded = day.toString().padStart(2, '0');
+
+ // Abbreviated month names
+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ const monthAbbr = monthNames[monthIndex];
+
+ switch (formatPreference) {
+ case 'DMY':
+ return `${dayPadded}/${monthPadded}/${year}`;
+ case 'YMD':
+ return `${year}-${monthPadded}-${dayPadded}`;
+ case 'MDY_WORDS': // Added
+ return `${monthAbbr} ${day}, ${year}`;
+ case 'DMY_WORDS': // Added
+ return `${day} ${monthAbbr} ${year}`;
+ case 'YMD_WORDS': // Added
+ return `${year} ${monthAbbr} ${day}`;
+ case 'MDY':
+ default:
+ return `${monthPadded}/${dayPadded}/${year}`;
+ }
+}
+
+function formatDateYYYYMMDD(date) {
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
+ return 'N/A';
+ }
+
+ const year = date.getUTCFullYear();
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
+ const day = String(date.getUTCDate()).padStart(2, '0');
+
+ return `${year}-${month}-${day}`;
+}
+
+/**
+ * Calculate the age of a product from purchase date to now
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {string} - Formatted age string (e.g., "2 years, 3 months", "6 months", "15 days")
+ */
+function calculateProductAge(purchaseDate) {
+ if (!purchaseDate) return 'Unknown';
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 'Unknown';
+ }
+
+ // Calculate the difference
+ let years = now.getFullYear() - purchase.getFullYear();
+ let months = now.getMonth() - purchase.getMonth();
+ let days = now.getDate() - purchase.getDate();
+
+ // Adjust for negative days
+ if (days < 0) {
+ months--;
+ const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
+ days += lastMonth.getDate();
+ }
+
+ // Adjust for negative months
+ if (months < 0) {
+ years--;
+ months += 12;
+ }
+
+ // Format the result
+ const parts = [];
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ parts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ parts.push(`${months} ${monthText}`);
+ }
+ if (days > 0 && years === 0) { // Only show days if less than a year old
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ parts.push(`${days} ${dayText}`);
+ }
+
+ if (parts.length === 0) {
+ return 'Today'; // Purchased today
+ }
+
+ return parts.join(', ');
+}
+
+/**
+ * Calculate the age of a product in days for sorting purposes
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {number} - Age in days (0 if invalid date)
+ */
+function calculateProductAgeInDays(purchaseDate) {
+ if (!purchaseDate) return 0;
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 0;
+ }
+
+ // Calculate difference in milliseconds and convert to days
+ const diffTime = now.getTime() - purchase.getTime();
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
+
+ return diffDays;
+}
+
+async function renderWarranties(warrantiesToRender) {
+ console.log('renderWarranties called with:', warrantiesToRender);
+
+ // Guard clause: If the main warrantiesList element doesn't exist on the current page, exit.
+ // This can happen if saveWarranty -> applyFilters -> renderWarranties is called from a page
+ // that doesn't have the main list view (e.g., the status page).
+ if (!warrantiesList) {
+ console.warn('renderWarranties: warrantiesList element not found. Aborting render. This might be normal if not on the main warranties page.');
+ return;
+ }
+
+ const isArchivedView = currentFilters && currentFilters.status === 'archived';
+
+ if (!warrantiesToRender || warrantiesToRender.length === 0) {
+ renderEmptyState(isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined); // renderEmptyState should also check for warrantiesList or its specific container
+ return;
+ }
+
+ const today = new Date();
+ const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback
+
+ warrantiesList.innerHTML = '';
+
+ // Apply sorting based on current sort selection
+ const sortedWarranties = [...warrantiesToRender].sort((a, b) => {
+ switch (currentFilters.sortBy) {
+ case 'name':
+ return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());
+ case 'purchase':
+ return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);
+ case 'age': // Added age sorting
+ return calculateProductAgeInDays(b.purchase_date) - calculateProductAgeInDays(a.purchase_date); // Oldest first
+ case 'vendor': // Added vendor sorting
+ return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());
+ case 'warranty_type': // Added warranty type sorting
+ return (a.warranty_type || '').toLowerCase().localeCompare((b.warranty_type || '').toLowerCase());
+ case 'expiration':
+ default:
+ const dateA = new Date(a.expiration_date || 0);
+ const dateB = new Date(b.expiration_date || 0);
+
+ const isExpiredA = dateA < today;
+ const isExpiredB = dateB < today;
+
+ if (isExpiredA && !isExpiredB) return 1;
+ if (!isExpiredA && isExpiredB) return -1;
+
+ // Both active or both expired, sort by date
+ return dateA - dateB;
+ }
+ });
+
+ console.log('Sorted warranties:', sortedWarranties);
+
+ // Update the container class based on current view
+ warrantiesList.className = `warranties-list ${currentView}-view ${isArchivedView ? 'archived-view' : ''}`;
+
+ // Show/hide table header for table view
+ if (tableViewHeader) {
+ tableViewHeader.classList.toggle('visible', currentView === 'table');
+ }
+
+ // Update view buttons to reflect current view
+ if (gridViewBtn && listViewBtn && tableViewBtn) {
+ gridViewBtn.classList.toggle('active', currentView === 'grid');
+ listViewBtn.classList.toggle('active', currentView === 'list');
+ tableViewBtn.classList.toggle('active', currentView === 'table');
+ }
+
+ sortedWarranties.forEach(warranty => {
+ // --- Use processed data ---
+ const purchaseDate = warranty.purchaseDate;
+ const expirationDate = warranty.expirationDate;
+ const isLifetime = warranty.is_lifetime;
+ let statusClass = warranty.status || 'unknown';
+ let statusText = warranty.statusText || 'Unknown Status';
+ // If showing archived-only view or item itself is archived within All view
+ if (isArchivedView || warranty.is_archived) {
+ const archivedTextRaw = window.i18next ? window.i18next.t('warranties.archived') : 'Archived';
+ const archivedLabel = archivedTextRaw && archivedTextRaw !== 'warranties.archived' ? archivedTextRaw : 'Archived';
+ statusClass = 'archived';
+ statusText = archivedLabel;
+ }
+ // Format warranty duration text
+ let warrantyDurationText = window.i18next ? window.i18next.t('warranties.na') : 'N/A';
+ if (isLifetime) {
+ warrantyDurationText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
+ } else {
+ // Use display_duration values if available, otherwise fall back to warranty_duration values
+ const years = warranty.display_duration_years !== undefined ? warranty.display_duration_years : (warranty.warranty_duration_years || 0);
+ const months = warranty.display_duration_months !== undefined ? warranty.display_duration_months : (warranty.warranty_duration_months || 0);
+ const days = warranty.display_duration_days !== undefined ? warranty.display_duration_days : (warranty.warranty_duration_days || 0);
+
+ // If all duration fields are 0 but we have expiration date, calculate from dates
+ if (years === 0 && months === 0 && days === 0 && warranty.expiration_date && warranty.purchase_date) {
+ const calculatedDuration = calculateDurationFromDates(warranty.purchase_date, warranty.expiration_date);
+ if (calculatedDuration) {
+ let parts = [];
+ if (calculatedDuration.years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: calculatedDuration.years}) : `year${calculatedDuration.years !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.years} ${yearText}`);
+ }
+ if (calculatedDuration.months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: calculatedDuration.months}) : `month${calculatedDuration.months !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.months} ${monthText}`);
+ }
+ if (calculatedDuration.days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: calculatedDuration.days}) : `day${calculatedDuration.days !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.days} ${dayText}`);
+ }
+ if (parts.length > 0) {
+ warrantyDurationText = parts.join(', ');
+ }
+ }
+ } else {
+ // Use the stored/calculated duration fields
+ let parts = [];
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ parts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ parts.push(`${months} ${monthText}`);
+ }
+ if (days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ parts.push(`${days} ${dayText}`);
+ }
+ if (parts.length > 0) {
+ warrantyDurationText = parts.join(', ');
+ }
+ }
+ }
+ const expirationDateText = isLifetime ? (window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime') : formatDate(expirationDate);
+
+ // Calculate product age
+ const productAge = calculateProductAge(warranty.purchase_date);
+
+ // Make sure serial numbers array exists and is valid
+ const validSerialNumbers = Array.isArray(warranty.serial_numbers)
+ ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
+ : [];
+ // Prepare user info HTML for global view
+ let userInfoHtml = '';
+ if (isGlobalView && warranty.user_display_name) {
+ const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';
+ userInfoHtml = `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;
+ }
+
+ // Prepare tags array for component-based rendering
+ const tagsArray = Array.isArray(warranty.tags) ? warranty.tags : [];
+ // Add notes display button if present
+ let notesHtml = '';
+ const hasNotes = warranty.notes && warranty.notes.trim() !== '';
+ // Remove the button, and instead prepare a notes link for document-links-row
+ let notesLinkHtml = '';
+ if (hasNotes) {
+ const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';
+ notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;
+ }
+
+ const hasDocuments = Boolean(
+ warranty.product_url ||
+ warranty.invoice_path || warranty.invoice_url ||
+ warranty.manual_path || warranty.manual_url ||
+ warranty.other_document_path || warranty.other_document_url ||
+ warranty.paperless_invoice_id || warranty.paperless_manual_id ||
+ warranty.paperless_photo_id || warranty.paperless_other_id ||
+ hasNotes
+ );
+
+
+ // Get current user ID to check warranty ownership
+ const currentUserId = (() => {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.id;
+ } catch (e) {
+ return null;
+ }
+ })();
+
+ // Check if current user can edit/delete this warranty
+ // Allow if: not in global view, user owns the warranty, or user is admin
+ const isAdmin = getUserType() === 'admin';
+ const canEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
+
+ // Determine claims button class and title based on claim status
+ let claimsButtonClass = 'action-btn claims-link';
+ let claimsTitle = 'Claims';
+
+ if (warranty.claim_status_summary === 'OPEN') {
+ claimsButtonClass += ' claims-open';
+ claimsTitle = 'Claims (Open)';
+ } else if (warranty.claim_status_summary === 'FINISHED') {
+ claimsButtonClass += ' claims-finished';
+ claimsTitle = 'Claims (Finished)';
+ }
+
+ // Generate action buttons HTML based on permissions
+ const actionButtonsHtml = canEdit ? `
+ <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">
+ <i class="fas fa-clipboard-list"></i>
+ </button>
+ ${ (isArchivedView || warranty.is_archived) ? `
+ <button class="action-btn unarchive-btn" title="Unarchive" data-id="${warranty.id}">
+ <i class="fas fa-box-open"></i>
+ </button>
+ <button class="action-btn edit-btn" title="Edit (disabled in archived view)" data-id="${warranty.id}" disabled>
+ <i class="fas fa-edit"></i>
+ </button>
+ ` : `
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn archive-btn" title="Archive" data-id="${warranty.id}">
+ <i class="fas fa-archive"></i>
+ </button>
+ `}
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ ` : `
+ <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">
+ <i class="fas fa-clipboard-list"></i>
+ </button>
+ <span class="action-btn-placeholder" title="View only - not your warranty">
+ <i class="fas fa-eye" style="color: #666;"></i>
+ </span>
+ `;
+
+ let cardElement = document.createElement('div');
+ const isArchivedItem = isArchivedView || warranty.is_archived;
+ cardElement.className = `warranty-card ${isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active')}`;
+
+ // Claims button styling will be handled in the action buttons HTML generation
+
+ if (currentView === 'grid') {
+ const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+ const contentHtml = `
+ ${photoThumbnailHtml}
+ <div class="warranty-info">
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style=\"margin-left: 28px;\">
+ <ul style=\"margin-top: 5px;\">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ ` : ''}
+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
+ ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
+ </div>
+ ${hasDocuments ? `
+ <div class="document-links-row">
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
+ </a>
+ ` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
+ ${notesLinkHtml}
+ </div>
+ </div>
+ ` : ''}
+
+ `;
+ if (window.components && window.components.createWarrantyCard) {
+ cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
+ } else {
+ cardElement.className = `warranty-card ${rootModifierClass}`;
+ cardElement.innerHTML = `
+ <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
+ <div class=\"warranty-content\">${contentHtml}</div>
+ <div class=\"warranty-status-row status-${statusClass}\"><span>${statusText}</span></div>
+ `;
+ }
+ } else if (currentView === 'list') {
+ // List view uses the same component template with different content sizing
+ const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 180px; height: 180px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+
+ const contentHtml = `
+ ${photoThumbnailHtml}
+ <div class="warranty-info">
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style=\"margin-left: 28px;\">
+ <ul style=\"margin-top: 5px;\">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ ` : ''}
+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
+ ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
+ </div>
+ ${hasDocuments ? `
+ <div class="document-links-row">
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
+ </a>
+ ` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
+ ${notesLinkHtml}
+ </div>
+ </div>
+ ` : ''}
+
+ `;
+
+ if (window.components && window.components.createWarrantyCard) {
+ cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
+ } else {
+ cardElement.className = `warranty-card ${rootModifierClass}`;
+ cardElement.innerHTML = `
+ <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
+ <div class=\"warranty-content\">${contentHtml}</div>
+ <div class=\"warranty-status-row status-${statusClass}\"><span>${statusText}</span></div>
+ `;
+ }
+ } else if (currentView === 'table') {
+ // Table view uses the same component template with compact content sizing
+ const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 55px; height: 55px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+
+ const contentHtml = `
+ ${photoThumbnailHtml}
+ <div class="warranty-info">
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style=\"margin-left: 28px;\">
+ <ul style=\"margin-top: 5px;\">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ ` : ''}
+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
+ ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
+ </div>
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
+ </div>
+ ${hasDocuments ? `
+ <div class="document-links-row">
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
+ </a>
+ ` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
+ ${notesLinkHtml}
+ </div>
+ </div>
+ ` : ''}
+
+ `;
+
+ if (window.components && window.components.createWarrantyCard) {
+ cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
+ } else {
+ cardElement.className = `warranty-card ${rootModifierClass}`;
+ cardElement.innerHTML = `
+ <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
+ <div class=\"warranty-content\">${contentHtml}</div>
+ `;
+ }
+ }
+
+ // Append tags via component (replaces previous string-based tagsHtml)
+ if (window.components && window.components.appendTags && tagsArray && tagsArray.length > 0) {
+ try {
+ window.components.appendTags(cardElement, tagsArray);
+ } catch (e) {
+ console.warn('appendTags failed', e);
+ }
+ }
+
+ // Add event listeners
+ warrantiesList.appendChild(cardElement);
+
+ // Add event listeners only if user can edit (buttons exist)
+ if (canEdit) {
+ // Edit button event listener
+ const editBtn = cardElement.querySelector('.edit-btn');
+ if (editBtn && !editBtn.disabled) {
+ editBtn.addEventListener('click', async () => {
+ console.log('[DEBUG] Edit button clicked for warranty ID:', warranty.id);
+ // Find the current warranty data instead of using the potentially stale warranty object
+ const currentWarranty = warranties.find(w => w.id === warranty.id);
+ console.log('[DEBUG] Found current warranty:', currentWarranty ? 'Yes' : 'No', currentWarranty?.notes);
+ if (currentWarranty) {
+ await openEditModal(currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
+ });
+ }
+
+ // Delete button event listener
+ const deleteBtn = cardElement.querySelector('.delete-btn');
+ if (deleteBtn) {
+ deleteBtn.addEventListener('click', () => {
+ openDeleteModal(warranty.id, warranty.product_name);
+ });
+ }
+
+ // Archive/Unarchive button event listeners
+ const archiveBtn = cardElement.querySelector('.archive-btn');
+ if (archiveBtn) {
+ archiveBtn.addEventListener('click', () => {
+ openArchiveModal(warranty.id, warranty.product_name);
+ });
+ }
+ const unarchiveBtn = cardElement.querySelector('.unarchive-btn');
+ if (unarchiveBtn) {
+ unarchiveBtn.addEventListener('click', async () => {
+ await toggleArchiveStatus(warranty.id, false);
+ });
+ }
+ }
+ // View notes button event listener
+ const notesLink = cardElement.querySelector('.notes-link');
+ if (notesLink) {
+ notesLink.addEventListener('click', (e) => {
+ e.preventDefault();
+ // Find the current warranty data instead of using the potentially stale warranty object
+ const currentWarranty = warranties.find(w => w.id === warranty.id);
+ if (currentWarranty) {
+ showNotesModal(currentWarranty.notes, currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
+ });
+ }
+ });
+
+ // Load secure images with authentication after rendering
+ loadSecureImages();
+
+ // Improved: Align card heights after all images have loaded
+ if (currentView === 'grid') {
+ const cards = warrantiesList.querySelectorAll('.warranty-card');
+ if (cards.length > 0) {
+ const images = warrantiesList.querySelectorAll('.secure-image');
+ let loadedCount = 0;
+ const totalImages = images.length;
+
+ const alignHeights = () => {
+ let maxHeight = 0;
+ cards.forEach(card => {
+ card.style.minHeight = ''; // Reset
+ const height = card.getBoundingClientRect().height;
+ if (height > maxHeight) maxHeight = height;
+ });
+ cards.forEach(card => {
+ card.style.minHeight = `${maxHeight}px`;
+ });
+ };
+
+ if (totalImages === 0) {
+ alignHeights(); // No images, align immediately
+ } else {
+ images.forEach(img => {
+ if (img.complete) {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ } else {
+ img.addEventListener('load', () => {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ });
+ img.addEventListener('error', () => {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ });
+ }
+ });
+ }
+ }
+ }
+
+ // Update the timeline chart if on the status page or appropriate
+ if (typeof updateTimelineChart === 'function') {
+ updateTimelineChart();
+ }
+
+ console.log('Warranties rendered successfully');
+}
+
+function filterWarranties() {
+ const searchTerm = searchInput ? searchInput.value.toLowerCase() : ''; // Add null check for searchInput
+
+ // Show or hide the clear search button if it exists
+ if (clearSearchBtn) {
+ clearSearchBtn.style.display = searchTerm ? 'flex' : 'none';
+ }
+
+ if (!searchTerm) {
+ return warranties; // Return the full list if no search term
+ // REMOVED: renderWarranties();
+ // REMOVED: return;
+ }
+
+ const filtered = warranties.filter(warranty => {
+ // Check product name
+ if (warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm)) { // Add null check
+ return true;
+ }
+
+ // Check tags
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ if (warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm))) {
+ return true;
+ }
+ }
+
+ // Check notes
+ if (warranty.notes && warranty.notes.toLowerCase().includes(searchTerm)) {
+ return true;
+ }
+
+ // Check vendor
+ if (warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm)) {
+ return true;
+ }
+
+ // Check model number
+ if (warranty.model_number && warranty.model_number.toLowerCase().includes(searchTerm)) {
+ return true;
+ }
+
+ // Check if any serial number contains search term
+ if (warranty.serial_numbers && Array.isArray(warranty.serial_numbers)) {
+ if (warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm))) {
+ return true;
+ }
+ }
+
+ return false;
+ });
+
+ // REMOVED: Add visual feedback if no results found
+ // REMOVED: if (filtered.length === 0) {
+ // REMOVED: renderEmptyState(`No matches found for "${searchTerm}". Try a different search term.`);
+ // REMOVED: } else {
+ // REMOVED: renderWarranties(filtered);
+ // REMOVED: }
+
+ return filtered; // Return the filtered list
+}
+
+function applyFilters() {
+ console.log('[FILTER DEBUG] Applying filters with:', currentFilters);
+ console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);
+
+ // If user selected archived status, reload data from archived endpoint and return
+ if (currentFilters.status === 'archived') {
+ if (!lastLoadedArchived) {
+ loadWarranties(true);
+ return;
+ }
+ } else if (lastLoadedArchived) {
+ // If leaving archived view, reload normal source
+ loadWarranties(true);
+ return;
+ } else if (currentFilters.status === 'all' && !lastLoadedIncludesArchived) {
+ // Ensure All view re-merges archived items after switching away and back
+ loadWarranties(true);
+ return;
+ }
+
+ // Filter warranties based on currentFilters
+ const filtered = warranties.filter(warranty => {
+ // Exclude archived items from specific status views (only show in 'all' or 'archived')
+ if (warranty.is_archived && currentFilters.status !== 'all' && currentFilters.status !== 'archived') {
+ return false;
+ }
+ // Status filter: allow archived items to pass in All view
+ if (currentFilters.status !== 'all' && currentFilters.status !== 'archived' && warranty.status !== currentFilters.status) {
+ return false;
+ }
+
+ // Tag filter
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ const hasTag = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId);
+ if (!hasTag) {
+ return false;
+ }
+ }
+
+ // Vendor filter
+ if (currentFilters.vendor !== 'all' && (warranty.vendor || '').toLowerCase() !== currentFilters.vendor.toLowerCase()) {
+ return false;
+ }
+
+ // Warranty type filter
+ if (currentFilters.warranty_type !== 'all' && (warranty.warranty_type || '').toLowerCase() !== currentFilters.warranty_type.toLowerCase()) {
+ return false;
+ }
+
+ // Search filter
+ if (currentFilters.search) {
+ const searchTerm = currentFilters.search.toLowerCase();
+ // Check if product name contains search term
+ const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
+ // Check if any tag name contains search term
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
+ // Check if notes contains search term
+ const notesMatch = warranty.notes && warranty.notes.toLowerCase().includes(searchTerm);
+ // Check if vendor contains search term
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+ // Check if model number contains search term
+ const modelNumberMatch = warranty.model_number && warranty.model_number.toLowerCase().includes(searchTerm);
+ // Check if any serial number contains search term
+ const serialNumberMatch = warranty.serial_numbers && Array.isArray(warranty.serial_numbers) &&
+ warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm));
+ // Return true if any match
+ if (!productNameMatch && !tagMatch && !notesMatch && !vendorMatch && !modelNumberMatch && !serialNumberMatch) {
+ return false;
+ }
+ }
+
+ return true;
+ });
+
+ console.log('[FILTER DEBUG] Filtered warranties:', filtered.length);
+ console.log('[FILTER DEBUG] Filtered warranty IDs:', filtered.map(w => w.id));
+
+ // Render the filtered warranties
+ renderWarranties(filtered);
+}
+
+// --- Persist and restore filters/sort ---
+async function saveFilterPreferences(saveToApi = true) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const filtersToSave = {
+ status: currentFilters.status || 'all',
+ tag: currentFilters.tag || 'all',
+ vendor: currentFilters.vendor || 'all',
+ warranty_type: currentFilters.warranty_type || 'all',
+ search: currentFilters.search || '',
+ sortBy: currentFilters.sortBy || 'expiration'
+ };
+ localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(filtersToSave));
+
+ // Save to API if authenticated and saveToApi is true
+ if (saveToApi && window.auth && window.auth.isAuthenticated()) {
+ const token = window.auth.getToken();
+ if (token) {
+ try {
+ console.log('[Filters] Saving filter preferences to API:', filtersToSave);
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ saved_filters: filtersToSave })
+ });
+
+ if (response.ok) {
+ console.log('[Filters] Successfully saved filter preferences to API');
+ } else {
+ console.warn('[Filters] Failed to save filter preferences to API:', response.status);
+ }
+ } catch (error) {
+ console.error('[Filters] Error saving filter preferences to API:', error);
+ }
+ }
+ }
+ } catch (e) {
+ console.warn('Failed to save filter preferences', e);
+ }
+}
+
+// Deprecated: Sort preference is now saved as part of saveFilterPreferences
+
+function loadFilterAndSortPreferences() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedFiltersRaw = localStorage.getItem(`${prefix}warrantyFilters`);
+ if (savedFiltersRaw) {
+ const savedFilters = JSON.parse(savedFiltersRaw);
+ if (savedFilters && typeof savedFilters === 'object') {
+ console.log('[Filters] Loading saved filters from localStorage:', savedFilters);
+ if (window.store && window.store.updateFilter) {
+ if (savedFilters.status) window.store.updateFilter('status', savedFilters.status);
+ if (savedFilters.tag) window.store.updateFilter('tag', savedFilters.tag);
+ if (savedFilters.vendor) window.store.updateFilter('vendor', savedFilters.vendor);
+ if (savedFilters.warranty_type) window.store.updateFilter('warranty_type', savedFilters.warranty_type);
+ window.store.updateFilter('search', savedFilters.search || '');
+ if (savedFilters.sortBy) window.store.updateFilter('sortBy', savedFilters.sortBy);
+ }
+ currentFilters.status = savedFilters.status || currentFilters.status;
+ currentFilters.tag = savedFilters.tag || currentFilters.tag;
+ currentFilters.vendor = savedFilters.vendor || currentFilters.vendor;
+ currentFilters.warranty_type = savedFilters.warranty_type || currentFilters.warranty_type;
+ currentFilters.search = savedFilters.search || '';
+ currentFilters.sortBy = savedFilters.sortBy || currentFilters.sortBy;
+
+ // Restore search input UI state
+ const searchInput = document.getElementById('searchWarranties');
+ const clearSearchBtn = document.getElementById('clearSearch');
+ if (searchInput && savedFilters.search) {
+ searchInput.value = savedFilters.search;
+ // Show clear button if search has value
+ if (clearSearchBtn) {
+ clearSearchBtn.style.display = 'flex';
+ }
+ // Add active search class
+ searchInput.parentElement.classList.add('active-search');
+ }
+ }
+ }
+ } catch (e) {
+ console.warn('Failed to load filter/sort preferences', e);
+ }
+}
+
+async function openEditModal(warranty) {
+ // Close any existing modals first
+ closeModals();
+
+ currentWarrantyId = warranty.id;
+
+ // Load currencies for the dropdown and wait for it to complete
+ await loadCurrencies();
+
+ console.log('[DEBUG] Opening edit modal for warranty:', warranty.id, 'with notes:', warranty.notes);
+
+ // Populate form fields
+ document.getElementById('editProductName').value = warranty.product_name;
+ document.getElementById('editProductUrl').value = warranty.product_url || '';
+ const editModelNumberInput = document.getElementById('editModelNumber');
+ if (editModelNumberInput) {
+ editModelNumberInput.value = warranty.model_number || '';
+ }
+ document.getElementById('editPurchaseDate').value = warranty.purchase_date.split('T')[0];
+ // Populate new duration fields
+ document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
+ document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
+ document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
+
+ document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
+
+ // Set currency dropdown
+ const editCurrencySelect = document.getElementById('editCurrency');
+ if (editCurrencySelect && warranty.currency) {
+ editCurrencySelect.value = warranty.currency;
+ }
+ document.getElementById('editVendor').value = warranty.vendor || '';
+
+ // Populate URL fields for documents (with null checks)
+ const editInvoiceUrl = document.getElementById('editInvoiceUrl');
+ if (editInvoiceUrl) editInvoiceUrl.value = warranty.invoice_url || '';
+
+ const editManualUrl = document.getElementById('editManualUrl');
+ if (editManualUrl) editManualUrl.value = warranty.manual_url || '';
+
+ const editOtherDocumentUrl = document.getElementById('editOtherDocumentUrl');
+ if (editOtherDocumentUrl) editOtherDocumentUrl.value = warranty.other_document_url || '';
+
+ // Handle warranty type - check if it's a predefined option or custom
+ const editWarrantyTypeSelect = document.getElementById('editWarrantyType');
+ const editWarrantyTypeCustom = document.getElementById('editWarrantyTypeCustom');
+ if (editWarrantyTypeSelect && warranty.warranty_type) {
+ // Check if the warranty type exists as an option in the dropdown
+ const options = Array.from(editWarrantyTypeSelect.options);
+ const matchingOption = options.find(option => option.value === warranty.warranty_type);
+
+ if (matchingOption) {
+ // It's a predefined option
+ editWarrantyTypeSelect.value = warranty.warranty_type;
+ if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
+ } else {
+ // It's a custom value
+ editWarrantyTypeSelect.value = 'other';
+ if (editWarrantyTypeCustom) {
+ editWarrantyTypeCustom.style.display = 'block';
+ editWarrantyTypeCustom.value = warranty.warranty_type;
+ }
+ }
+ } else if (editWarrantyTypeSelect) {
+ editWarrantyTypeSelect.value = '';
+ if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
+ }
+
+ // Clear existing serial number inputs
+ const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
+ editSerialNumbersContainer.innerHTML = '';
+
+ // Normalize serial_numbers to array of strings if needed
+ if (Array.isArray(warranty.serial_numbers) && warranty.serial_numbers.length > 0 && typeof warranty.serial_numbers[0] === 'object') {
+ warranty.serial_numbers = warranty.serial_numbers
+ .map(snObj => snObj && snObj.serial_number)
+ .filter(sn => typeof sn === 'string' && sn.trim() !== '');
+ }
+
+ // Add event listener for adding new serial number inputs in edit modal
+ editSerialNumbersContainer.addEventListener('click', (e) => {
+ if (e.target.closest('.add-serial-number')) {
+ addSerialNumberInput(editSerialNumbersContainer);
+ }
+ });
+
+ const validSerialNumbers = Array.isArray(warranty.serial_numbers)
+ ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
+ : [];
+
+ if (validSerialNumbers.length === 0) {
+ // Add a single empty input if there are no serial numbers
+ addSerialNumberInput(editSerialNumbersContainer);
+ } else {
+ // Add the first serial number with an "Add Another" button only (no remove button)
+ const firstInput = document.createElement('div');
+ firstInput.className = 'serial-number-input';
+ firstInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[0]}">
+ <button type="button" class="btn btn-sm btn-primary add-serial-number">
+ <i class="fas fa-plus"></i> ${i18next.t('warranties.add_serial_number')}
+ </button>
+ `;
+
+ // Add event listener for the Add button
+ firstInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
+ e.stopPropagation(); // Stop event from bubbling up
+ addSerialNumberInput(editSerialNumbersContainer);
+ });
+
+ editSerialNumbersContainer.appendChild(firstInput);
+
+ // Add the rest of the serial numbers with "Remove" buttons
+ for (let i = 1; i < validSerialNumbers.length; i++) {
+ const newInput = document.createElement('div');
+ newInput.className = 'serial-number-input';
+ newInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[i]}">
+ <button type="button" class="btn btn-sm btn-danger remove-serial-number">
+ <i class="fas fa-minus"></i> ${i18next.t('actions.delete')}
+ </button>
+ `;
+
+ // Add remove button functionality
+ newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
+ this.parentElement.remove();
+ });
+
+ editSerialNumbersContainer.appendChild(newInput);
+ }
+ }
+
+ // Show current invoice if exists
+ const currentInvoiceElement = document.getElementById('currentInvoice');
+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
+ if (currentInvoiceElement && deleteInvoiceBtn) {
+ const hasLocalInvoice = warranty.invoice_path && warranty.invoice_path !== 'null';
+ const hasPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
+
+ if (hasLocalInvoice) {
+ currentInvoiceElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
+ <a href="#" class="view-document-link" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>
+ (${i18next.t('warranties.upload_new_file_replace')})
+ </span>
+ `;
+ deleteInvoiceBtn.style.display = '';
+ } else if (hasPaperlessInvoice) {
+ currentInvoiceElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
+ <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_invoice_id}, {user_id: ${warranty.user_id}, id: ${warranty.id}}); return false;">View</a>
+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i> (${i18next.t('warranties.upload_new_file_replace')})
+ </span>
+ `;
+ deleteInvoiceBtn.style.display = '';
+ } else {
+ currentInvoiceElement.innerHTML = `<span>${i18next.t('warranties.no_invoice_uploaded')}</span>`;
+ deleteInvoiceBtn.style.display = 'none';
+ }
+ // Reset delete state
+ deleteInvoiceBtn.dataset.delete = 'false';
+ deleteInvoiceBtn.onclick = function() {
+ deleteInvoiceBtn.dataset.delete = 'true';
+ currentInvoiceElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.invoice_will_be_deleted')}</span>`;
+ deleteInvoiceBtn.style.display = 'none';
+ };
+ }
+ // Show current manual (component-based)
+ const currentManualElement = document.getElementById('currentManual');
+ const deleteManualBtn = document.getElementById('deleteManualBtn');
+ if (currentManualElement && deleteManualBtn && window.components && window.components.editModal) {
+ window.components.editModal.renderCurrentManual(currentManualElement, deleteManualBtn, warranty, window.i18next);
+ deleteManualBtn.dataset.delete = 'false';
+ deleteManualBtn.onclick = function() {
+ deleteManualBtn.dataset.delete = 'true';
+ currentManualElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.manual_will_be_deleted')}</span>`;
+ deleteManualBtn.style.display = 'none';
+ };
+ }
+
+ // Show current product photo (component-based)
+ const currentProductPhotoElement = document.getElementById('currentProductPhoto');
+ const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
+ if (currentProductPhotoElement && deleteProductPhotoBtn && window.components && window.components.editModal) {
+ window.components.editModal.renderCurrentPhoto(currentProductPhotoElement, deleteProductPhotoBtn, warranty, window.i18next);
+ deleteProductPhotoBtn.dataset.delete = 'false';
+ deleteProductPhotoBtn.onclick = function() {
+ deleteProductPhotoBtn.dataset.delete = 'true';
+ currentProductPhotoElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.photo_will_be_deleted')}</span>`;
+ deleteProductPhotoBtn.style.display = 'none';
+ };
+ }
+
+ // Show current other document (component-based)
+ const currentOtherDocumentElement = document.getElementById('currentOtherDocument');
+ const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
+ if (currentOtherDocumentElement && deleteOtherDocumentBtn && window.components && window.components.editModal) {
+ window.components.editModal.renderCurrentOther(currentOtherDocumentElement, deleteOtherDocumentBtn, warranty, window.i18next);
+ deleteOtherDocumentBtn.dataset.delete = 'false';
+ deleteOtherDocumentBtn.onclick = function() {
+ deleteOtherDocumentBtn.dataset.delete = 'true';
+ currentOtherDocumentElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.other_document_will_be_deleted')}</span>`;
+ deleteOtherDocumentBtn.style.display = 'none';
+ };
+ }
+
+ // Reset file inputs
+ document.getElementById('editProductPhoto').value = '';
+ document.getElementById('editInvoice').value = '';
+ document.getElementById('editManual').value = '';
+ document.getElementById('editOtherDocument').value = '';
+ document.getElementById('editProductPhotoFileName').textContent = '';
+ document.getElementById('editFileName').textContent = '';
+ document.getElementById('editManualFileName').textContent = '';
+ document.getElementById('editOtherDocumentFileName').textContent = '';
+
+ // Reset photo preview
+ const editPhotoPreview = document.getElementById('editProductPhotoPreview');
+ if (editPhotoPreview) {
+ editPhotoPreview.style.display = 'none';
+ }
+
+ // Set storage options based on current document storage
+ if (paperlessNgxEnabled) {
+ // Set product photo storage option
+ const editProductPhotoStorageRadios = document.getElementsByName('editProductPhotoStorage');
+ if (editProductPhotoStorageRadios.length > 0) {
+ const isPaperlessPhoto = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;
+ editProductPhotoStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessPhoto ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set invoice storage option
+ const editInvoiceStorageRadios = document.getElementsByName('editInvoiceStorage');
+ if (editInvoiceStorageRadios.length > 0) {
+ const isPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
+ editInvoiceStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessInvoice ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set manual storage option
+ const editManualStorageRadios = document.getElementsByName('editManualStorage');
+ if (editManualStorageRadios.length > 0) {
+ const isPaperlessManual = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;
+ editManualStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessManual ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set other document storage option
+ const editOtherDocumentStorageRadios = document.getElementsByName('editOtherDocumentStorage');
+ if (editOtherDocumentStorageRadios.length > 0) {
+ const isPaperlessOther = warranty.paperless_other_id && warranty.paperless_other_id !== null;
+ editOtherDocumentStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessOther ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ console.log('[Edit Modal] Storage options set based on current document storage:', {
+ photo: warranty.paperless_photo_id ? 'paperless' : 'local',
+ invoice: warranty.paperless_invoice_id ? 'paperless' : 'local',
+ manual: warranty.paperless_manual_id ? 'paperless' : 'local',
+ other: warranty.paperless_other_id ? 'paperless' : 'local'
+ });
+ }
+
+ // Initialize file input event listeners
+ const editProductPhotoInput = document.getElementById('editProductPhoto');
+ if (editProductPhotoInput) {
+ editProductPhotoInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editProductPhoto', 'editProductPhotoFileName');
+ });
+ }
+
+ const editInvoiceInput = document.getElementById('editInvoice');
+ if (editInvoiceInput) {
+ editInvoiceInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editInvoice', 'editFileName');
+ });
+ }
+
+ const editManualInput = document.getElementById('editManual');
+ if (editManualInput) {
+ editManualInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editManual', 'editManualFileName');
+ });
+ }
+
+ const editOtherDocumentInput = document.getElementById('editOtherDocument');
+ if (editOtherDocumentInput) {
+ editOtherDocumentInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editOtherDocument', 'editOtherDocumentFileName');
+ });
+ }
+
+ // Show edit modal
+ const modalBackdrop = document.getElementById('editModal');
+ if (modalBackdrop) {
+ modalBackdrop.classList.add('active'); // Add active class to display as flex
+ }
+
+ // Reset tabs to first tab
+ const editTabBtns = document.querySelectorAll('.edit-tab-btn');
+ editTabBtns.forEach(btn => btn.classList.remove('active'));
+ document.querySelector('.edit-tab-btn[data-tab="edit-product-info"]').classList.add('active');
+
+ // Reset tab content
+ document.querySelectorAll('.edit-tab-content').forEach(content => content.classList.remove('active'));
+ document.getElementById('edit-product-info').classList.add('active');
+
+ // Initialize edit mode tags
+ editSelectedTags = [];
+
+ // If warranty has tags, populate editSelectedTags
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ editSelectedTags = warranty.tags.map(tag => ({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ }));
+ }
+
+ // Render selected tags using the helper function
+ renderEditSelectedTags();
+
+ // Set up tag search in edit mode
+ const editTagSearch = document.getElementById('editTagSearch');
+ const editTagsList = document.getElementById('editTagsList');
+
+ if (editTagSearch && editTagsList) {
+ // Add event listeners for tag search
+ editTagSearch.addEventListener('focus', () => {
+ renderEditTagsList();
+ editTagsList.classList.add('show');
+ });
+
+ editTagSearch.addEventListener('input', () => {
+ renderEditTagsList(editTagSearch.value);
+ });
+
+ // Add event listener to close dropdown when clicking outside
+ document.addEventListener('click', (e) => {
+ if (!editTagSearch.contains(e.target) && !editTagsList.contains(e.target)) {
+ editTagsList.classList.remove('show');
+ }
+ });
+ }
+
+ // Set up manage tags button in edit mode
+ const editManageTagsBtn = document.getElementById('editManageTagsBtn');
+ if (editManageTagsBtn) {
+ editManageTagsBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ openTagManagementModal();
+ });
+ }
+
+ // Validate all tabs to update completion indicators
+ validateEditTab('edit-product-info');
+ validateEditTab('edit-warranty-details');
+ validateEditTab('edit-documents');
+ validateEditTab('edit-tags');
+
+ // Add input event listeners to update validation status
+ document.querySelectorAll('#editWarrantyForm input').forEach(input => {
+ input.addEventListener('input', function() {
+ // Find the tab this input belongs to
+ const tabContent = this.closest('.edit-tab-content');
+ if (tabContent) {
+ validateEditTab(tabContent.id);
+ }
+ });
+ });
+
+ // --- Set Lifetime Checkbox and Toggle Duration Fields ---
+ if (editIsLifetimeCheckbox && editWarrantyDurationFields) {
+ editIsLifetimeCheckbox.checked = warranty.is_lifetime || false;
+ handleEditLifetimeChange(); // Call handler to set initial state
+
+ // Remove previous listener if exists
+ editIsLifetimeCheckbox.removeEventListener('change', handleEditLifetimeChange);
+ // Add new listener
+ editIsLifetimeCheckbox.addEventListener('change', handleEditLifetimeChange);
+
+ // Set duration values only if NOT lifetime
+ if (!warranty.is_lifetime) {
+ document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
+ document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
+ document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
+ } else {
+ document.getElementById('editWarrantyDurationYears').value = '';
+ document.getElementById('editWarrantyDurationMonths').value = '';
+ document.getElementById('editWarrantyDurationDays').value = '';
+ }
+ } else {
+ console.error("Lifetime warranty elements or duration fields not found in edit form");
+ }
+
+ // --- Set Warranty Method Selection ---
+ if (editDurationMethodRadio && editExactDateMethodRadio && editExactExpirationDateInput) {
+ console.log('[DEBUG Edit Modal] Warranty method detection:', {
+ originalInputMethod: warranty.original_input_method,
+ isLifetime: warranty.is_lifetime,
+ expirationDate: warranty.expiration_date,
+ warrantyDurationYears: warranty.warranty_duration_years,
+ warrantyDurationMonths: warranty.warranty_duration_months,
+ warrantyDurationDays: warranty.warranty_duration_days
+ });
+
+ // Use the original input method if available, otherwise fall back to previous logic
+ if (!warranty.is_lifetime) {
+ if (warranty.original_input_method === 'exact_date') {
+ // Use exact date method
+ editExactDateMethodRadio.checked = true;
+ editDurationMethodRadio.checked = false;
+ editExactExpirationDateInput.value = warranty.expiration_date.split('T')[0];
+ console.log('[DEBUG Edit Modal] Selected exact date method based on original_input_method');
+ } else {
+ // Use duration method (either explicitly set or fallback)
+ editDurationMethodRadio.checked = true;
+ editExactDateMethodRadio.checked = false;
+ editExactExpirationDateInput.value = '';
+ console.log('[DEBUG Edit Modal] Selected duration method based on original_input_method or fallback');
+ }
+ }
+
+ // Set up event listeners for warranty method change
+ editDurationMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
+ editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+
+ console.log('[DEBUG Edit Modal] Event listeners attached to warranty method radio buttons');
+ console.log('[DEBUG Edit Modal] Initial radio states:', {
+ durationChecked: editDurationMethodRadio.checked,
+ exactDateChecked: editExactDateMethodRadio.checked
+ });
+
+ // Call handler to set initial state
+ handleEditWarrantyMethodChange();
+ }
+
+ // Set notes
+ const notesInput = document.getElementById('editNotes');
+ if (notesInput) {
+ notesInput.value = warranty.notes || '';
+ }
+
+ // Update currency symbols and positioning for the edit form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const editPriceInput = document.getElementById('editPurchasePrice');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ if (editPriceInput && editCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = editPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ editPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ editPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
+
+ // Load secure images with authentication for the edit modal
+ setTimeout(() => loadSecureImages(), 100); // Small delay to ensure DOM is updated
+}
+
+function openDeleteModal(warrantyId, productName) {
+ currentWarrantyId = warrantyId;
+ if (window.components && window.components.modals && window.components.modals.openDeleteModal) {
+ window.components.modals.openDeleteModal(productName);
+ return;
+ }
+ const deleteProductNameElement = document.getElementById('deleteProductName');
+ if (deleteProductNameElement) deleteProductNameElement.textContent = productName || '';
+ const deleteModal = document.getElementById('deleteModal');
+ if (deleteModal) deleteModal.classList.add('active');
+}
+
+// Open Archive confirmation modal
+function openArchiveModal(warrantyId, productName) {
+ currentWarrantyId = warrantyId;
+ if (window.components && window.components.modals && window.components.modals.openArchiveModal) {
+ window.components.modals.openArchiveModal(productName);
+ return;
+ }
+ const archiveProductNameElement = document.getElementById('archiveProductName');
+ if (archiveProductNameElement) archiveProductNameElement.textContent = productName || '';
+ const archiveModal = document.getElementById('archiveModal');
+ if (archiveModal) archiveModal.classList.add('active');
+}
+
+// Confirm archive handler
+async function confirmArchive() {
+ if (!currentWarrantyId) {
+ showToast('No warranty selected', 'error');
+ return;
+ }
+ try {
+ await toggleArchiveStatus(currentWarrantyId, true);
+ closeModals();
+ // Guidance toast for where to find archived items
+ const guidance = 'You can find archived warranties by selecting "Archived" in Filters.';
+ showToast(guidance, 'info');
+ currentWarrantyId = null;
+ } catch (e) {
+ // toggleArchiveStatus already toasts on failure
+ console.error('Archive failed', e);
+ }
+}
+
+// Function to close all modals
+function closeModals() {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.classList.remove('active');
+ });
+}
+
+// Validate file size before upload
+function validateFileSize(formData, maxSizeMB = 32) {
+ let totalSize = 0;
+
+ // Check file sizes
+ if (formData.has('invoice') && formData.get('invoice').size > 0) {
+ totalSize += formData.get('invoice').size;
+ }
+
+ if (formData.has('manual') && formData.get('manual').size > 0) {
+ totalSize += formData.get('manual').size;
+ }
+
+ if (formData.has('other_document') && formData.get('other_document').size > 0) {
+ totalSize += formData.get('other_document').size;
+ }
+
+ // Convert bytes to MB for comparison and display
+ const totalSizeMB = totalSize / (1024 * 1024);
+ console.log(`Total upload size: ${totalSizeMB.toFixed(2)} MB`);
+
+ // Check if total size exceeds limit
+ if (totalSizeMB > maxSizeMB) {
+ return {
+ valid: false,
+ message: `Total file size (${totalSizeMB.toFixed(2)} MB) exceeds the maximum allowed size of ${maxSizeMB} MB. Please reduce file sizes.`
+ };
+ }
+
+ return {
+ valid: true
+ };
+}
+
+// Submit form function - event handler for form submit
+async function handleFormSubmit(event) { // Made async to properly await paperless uploads
+ event.preventDefault();
+
+ const isLifetime = isLifetimeCheckbox.checked;
+ const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
+ const years = parseInt(warrantyDurationYearsInput.value || 0);
+ const months = parseInt(warrantyDurationMonthsInput.value || 0);
+ const days = parseInt(warrantyDurationDaysInput.value || 0);
+ const exactDate = exactExpirationDateInput ? exactExpirationDateInput.value : '';
+
+ // --- Updated Lifetime and Method Check ---
+ if (!isLifetime) {
+ if (isDurationMethod) {
+ // Validate duration fields
+ if (years === 0 && months === 0 && days === 0) {
+ showValidationErrors(1);
+ switchToTab(1); // Switch to warranty details tab
+ // Optionally focus the first duration input
+ if (warrantyDurationYearsInput) warrantyDurationYearsInput.focus();
+ // Add invalid class to the container or individual inputs if needed
+ if (warrantyDurationFields) warrantyDurationFields.classList.add('invalid-duration'); // Example
+ return;
+ }
+ } else {
+ // Validate exact expiration date
+ if (!exactDate) {
+ showValidationErrors(1);
+ switchToTab(1); // Switch to warranty details tab
+ if (exactExpirationDateInput) exactExpirationDateInput.focus();
+ return;
+ }
+
+ // Validate that expiration date is in the future relative to purchase date
+ const purchaseDate = document.getElementById('purchaseDate').value;
+ if (purchaseDate && exactDate <= purchaseDate) {
+ showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
+ switchToTab(1);
+ if (exactExpirationDateInput) exactExpirationDateInput.focus();
+ return;
+ }
+ }
+ }
+
+ // Remove invalid duration class if validation passes
+ if (warrantyDurationFields) warrantyDurationFields.classList.remove('invalid-duration');
+
+ // Validate all tabs
+ for (let i = 0; i < tabContents.length; i++) {
+ if (!validateTab(i)) {
+ // Switch to the first invalid tab
+ switchToTab(i);
+ showValidationErrors(i);
+ return;
+ }
+ }
+
+ // Create form data object
+ const formData = new FormData(warrantyForm);
+ // Ensure model_number is included if present
+ const modelNumberInput = document.getElementById('modelNumber');
+ if (modelNumberInput && modelNumberInput.value.trim() !== '') {
+ formData.set('model_number', modelNumberInput.value.trim());
+ }
+
+ // Handle warranty type - use custom value if "other" is selected
+ const warrantyTypeSelect = document.getElementById('warrantyType');
+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
+ if (warrantyTypeSelect && warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
+ formData.set('warranty_type', warrantyTypeCustom.value.trim());
+ }
+
+ // Debug: Log all form data entries
+ console.log('=== DEBUG: Form Data Contents ===');
+ for (let [key, value] of formData.entries()) {
+ console.log(`${key}: ${value}`);
+ }
+ console.log('=== END DEBUG ===');
+
+ // Product URL handling
+ let productUrlValue = formData.get('product_url');
+ if (productUrlValue && typeof productUrlValue === 'string') {
+ productUrlValue = productUrlValue.trim();
+ if (productUrlValue && !productUrlValue.startsWith('http://') && !productUrlValue.startsWith('https://')) {
+ formData.set('product_url', 'https://' + productUrlValue);
+ } else if (productUrlValue) {
+ // Ensure trimmed value is set back if it was already valid
+ formData.set('product_url', productUrlValue);
+ }
+ }
+
+ // Remove old warranty_years if it exists in formData (it shouldn't if HTML is correct)
+ formData.delete('warranty_years');
+
+ // Append new duration fields (already handled by FormData constructor if names match)
+ // formData.append('warranty_duration_years', years);
+ // formData.append('warranty_duration_months', months);
+ // formData.append('warranty_duration_days', days);
+
+ // Add serial numbers to form data (using correct name 'serial_numbers[]')
+ const serialInputs = document.querySelectorAll('#serialNumbersContainer input[name="serial_numbers[]"]');
+ // Clear existing serial_numbers[] from formData before appending new ones
+ formData.delete('serial_numbers[]');
+ serialInputs.forEach(input => {
+ if (input.value.trim()) {
+ formData.append('serial_numbers[]', input.value.trim()); // Use [] for arrays
+ }
+ });
+
+ // Add tag IDs to form data as JSON string
+ if (selectedTags && selectedTags.length > 0) {
+ const tagIds = selectedTags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ } else {
+ formData.append('tag_ids', JSON.stringify([])); // Send empty array if no tags
+ }
+
+ // Add URL fields for documents (with null checks)
+ const invoiceUrlField = document.getElementById('invoiceUrl');
+ formData.append('invoice_url', invoiceUrlField ? invoiceUrlField.value || '' : '');
+
+ const manualUrlField = document.getElementById('manualUrl');
+ formData.append('manual_url', manualUrlField ? manualUrlField.value || '' : '');
+
+ const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
+ formData.append('other_document_url', otherDocumentUrlField ? otherDocumentUrlField.value || '' : '');
+
+ // --- Ensure is_lifetime is correctly added ---
+ // FormData already includes it if the checkbox is checked. If not checked, it's omitted.
+ // We need to explicitly add 'false' if it's not checked.
+ if (!isLifetimeCheckbox.checked) {
+ formData.append('is_lifetime', 'false');
+
+ // Add warranty method and exact expiration date if using exact date method
+ if (!isDurationMethod && exactDate) {
+ formData.append('exact_expiration_date', exactDate);
+ // Ensure duration fields are 0 when using exact date
+ formData.set('warranty_duration_years', '0');
+ formData.set('warranty_duration_months', '0');
+ formData.set('warranty_duration_days', '0');
+ }
+ } else {
+ // Ensure duration fields are 0 if lifetime is checked
+ formData.set('warranty_duration_years', '0');
+ formData.set('warranty_duration_months', '0');
+ formData.set('warranty_duration_days', '0');
+ }
+
+ // Add other_document file (always, as no storage selection for this)
+ const otherDocumentFile = document.getElementById('otherDocument').files[0];
+ if (otherDocumentFile) {
+ formData.append('other_document', otherDocumentFile);
+ }
+
+ // --- Only append invoice/manual files to FormData if storage is 'local' ---
+ const invoiceFile = document.getElementById('invoice')?.files[0];
+ const manualFile = document.getElementById('manual')?.files[0];
+ let invoiceStorage = 'local';
+ let manualStorage = 'local';
+ const invoiceStorageRadio = document.querySelector('input[name="invoiceStorage"]:checked');
+ const manualStorageRadio = document.querySelector('input[name="manualStorage"]:checked');
+ if (invoiceStorageRadio) invoiceStorage = invoiceStorageRadio.value;
+ if (manualStorageRadio) manualStorage = manualStorageRadio.value;
+ formData.set('invoiceStorage', invoiceStorage);
+ formData.set('manualStorage', manualStorage);
+ console.log('[DEBUG] Invoice storage:', invoiceStorage, 'Manual storage:', manualStorage);
+ console.log('[DEBUG] Invoice file:', invoiceFile);
+ console.log('[DEBUG] Manual file:', manualFile);
+ if (invoiceStorage === 'local' && invoiceFile) {
+ console.log('[DEBUG] Appending invoice file to FormData (local storage)');
+ formData.append('invoice', invoiceFile);
+ }
+ if (manualStorage === 'local' && manualFile) {
+ console.log('[DEBUG] Appending manual file to FormData (local storage)');
+ formData.append('manual', manualFile);
+ }
+ if (invoiceStorage === 'paperless') {
+ console.log('[DEBUG] Invoice should be uploaded to Paperless-ngx');
+ }
+ if (manualStorage === 'paperless') {
+ console.log('[DEBUG] Manual should be uploaded to Paperless-ngx');
+ }
+
+ // Add selected Paperless documents (for linking existing docs, not uploads)
+ const selectedPaperlessProductPhoto = document.getElementById('selectedPaperlessProductPhoto');
+ const selectedPaperlessInvoice = document.getElementById('selectedPaperlessInvoice');
+ const selectedPaperlessManual = document.getElementById('selectedPaperlessManual');
+ const selectedPaperlessOtherDocument = document.getElementById('selectedPaperlessOtherDocument');
+ if (selectedPaperlessProductPhoto && selectedPaperlessProductPhoto.value) {
+ formData.append('paperless_photo_id', selectedPaperlessProductPhoto.value);
+ }
+ if (selectedPaperlessInvoice && selectedPaperlessInvoice.value) {
+ formData.append('paperless_invoice_id', selectedPaperlessInvoice.value);
+ }
+ if (selectedPaperlessManual && selectedPaperlessManual.value) {
+ formData.append('paperless_manual_id', selectedPaperlessManual.value);
+ }
+ if (selectedPaperlessOtherDocument && selectedPaperlessOtherDocument.value) {
+ formData.append('paperless_other_id', selectedPaperlessOtherDocument.value);
+ }
+
+ // Show loading spinner
+ showLoadingSpinner();
+
+ try {
+ // Process Paperless-ngx uploads if enabled
+ const paperlessUploads = await processPaperlessNgxUploads(formData);
+
+ // Add Paperless-ngx document IDs to form data
+ Object.keys(paperlessUploads).forEach(key => {
+ formData.append(key, paperlessUploads[key]);
+ });
+
+ // Send the form data to the server
+ const response = await fetch('/api/warranties', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
+ },
+ body: formData
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to add warranty');
+ }
+
+ const data = await response.json();
+ hideLoadingSpinner();
+ showToast(window.t('messages.warranty_added_successfully'), 'success');
+
+ // Store the new warranty ID for auto-linking
+ const newWarrantyId = data.id;
+
+ // --- Store file info and storage type before upload for auto-link logic ---
+ const invoiceFileInput = document.getElementById('invoice');
+ const manualFileInput = document.getElementById('manual');
+ const invoiceFilePre = invoiceFileInput?.files[0];
+ const manualFilePre = manualFileInput?.files[0];
+ const invoiceStoragePre = formData.get('invoiceStorage');
+ const manualStoragePre = formData.get('manualStorage');
+
+ // Auto-link any documents that were uploaded to Paperless-ngx (match edit modal behavior)
+ const autoLinkTypes = [];
+ const fileInfo = {};
+ if (invoiceStoragePre === 'paperless' && invoiceFilePre) {
+ autoLinkTypes.push('invoice');
+ fileInfo.invoice = invoiceFilePre.name;
+ }
+ if (manualStoragePre === 'paperless' && manualFilePre) {
+ autoLinkTypes.push('manual');
+ fileInfo.manual = manualFilePre.name;
+ }
+ // Other document does not have a storage option, so skip unless you add support
+ // If you want to support auto-linking for 'other', add logic here
+ console.log('[Auto-Link DEBUG] newWarrantyId:', newWarrantyId, 'autoLinkTypes:', autoLinkTypes, 'fileInfo:', fileInfo, 'invoiceStorage:', invoiceStoragePre, 'manualStorage:', manualStoragePre);
+ if (autoLinkTypes.length > 0 && newWarrantyId) {
+ console.log('[Auto-Link] Starting automatic document linking after warranty creation (Paperless-ngx uploads only)', autoLinkTypes, fileInfo);
+ setTimeout(() => {
+ console.log('[Auto-Link DEBUG] Calling autoLinkRecentDocuments with:', newWarrantyId, autoLinkTypes, fileInfo);
+ autoLinkRecentDocuments(newWarrantyId, autoLinkTypes, 10, 10000, fileInfo);
+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
+ }
+
+ // Close and reset the modal on success
+ if (addWarrantyModal) {
+ addWarrantyModal.classList.remove('active');
+ }
+ resetAddWarrantyWizard(); // Reset the wizard form
+
+ try {
+ await loadWarranties(true);
+ console.log('Warranties reloaded after adding new warranty');
+ applyFilters();
+
+ // Load secure images for the new cards
+ setTimeout(() => {
+ console.log('Loading secure images for new warranty cards');
+ loadSecureImages();
+ }, 200);
+ } catch (error) {
+ console.error('Error reloading warranties after adding:', error);
+ }
+ } catch (error) {
+ hideLoadingSpinner();
+ console.error('Error adding warranty:', error);
+ showToast(error.message || window.t('messages.failed_to_add_warranty'), 'error');
+ }
+}
+
+// Initialize page
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize the warranty form *only* if the form element exists
+ if (warrantyForm) {
+ initWarrantyForm();
+ }
+
+ // Load warranties (might need checks if warrantiesList doesn't always exist)
+ if (warrantiesList) {
+ // REMOVED: loadWarranties(); // Now called after authStateReady
+ // REMOVED: loadViewPreference(); // Now called after authStateReady
+ loadTags(); // Load tags for the form
+ initTagFunctionality(); // Initialize tag search/selection
+ }
+
+ // Initialize theme (should be safe on all pages)
+ initializeTheme();
+
+ // Set up event listeners for other UI controls (should contain checks)
+ setupUIEventListeners();
+ setupModalTriggers(); // Add the new modal listeners
+
+ // Check if user is logged in and update UI
+ // checkLoginStatus(); // Removed undefined function
+
+ // Setup form submission
+ const form = document.getElementById('addWarrantyForm');
+ if (form) {
+ form.addEventListener('submit', handleFormSubmit); // Use renamed handler
+ }
+
+ // Setup settings menu toggle
+ // setupSettingsMenu(); // Removed: function not defined, handled by auth.js
+
+ // Initialize theme toggle state *after* DOM is loaded
+ // Find the header toggle (assuming ID 'darkModeToggle')
+ const headerToggle = document.getElementById('darkModeToggle');
+ if (headerToggle) {
+ // Set initial state based on theme applied by theme-loader.js
+ const currentTheme = document.documentElement.getAttribute('data-theme');
+ headerToggle.checked = currentTheme === 'dark';
+
+ // Add listener to update theme when toggled
+ headerToggle.addEventListener('change', function() {
+ setTheme(this.checked);
+ });
+ }
+
+ // REMOVE any direct calls to initializeTheme() from here or globally
+ // initializeTheme();
+
+ // Setup view switcher
+ // setupViewSwitcher(); // Removed undefined function
+
+ // Setup filter controls
+ // setupFilterControls(); // Removed: function not defined
+
+ // Setup form tabs and navigation
+ // initFormTabs(); // <-- Remove this line from DOMContentLoaded
+
+ // Initialize modal interactions
+ // initializeModals(); // Removed: function not defined, handled by setupModalTriggers
+
+ // Load preferences (if needed for things other than theme)
+ // loadPreferences(); // Consider if needed
+
+ // REMOVED: updateCurrencySymbols(); // Now called after authStateReady
+
+ // Initialize claims functionality
+ initClaimsEventListeners();
+});
+
+// ====== WARRANTY CLAIMS FUNCTIONALITY ======
+
+// Global variables for claims
+let currentClaimsWarrantyId = null;
+let currentClaims = [];
+let currentClaimsCanEdit = false; // Track if current user can edit the warranty being viewed
+
+/**
+ * Initialize claims event listeners
+ */
+function initClaimsEventListeners() {
+ // Event delegation for claims links
+ if (warrantiesList) {
+ warrantiesList.addEventListener('click', (e) => {
+ if (e.target.closest('.claims-link')) {
+ e.preventDefault();
+ const warrantyId = parseInt(e.target.closest('.claims-link').dataset.id);
+ openClaimsModal(warrantyId);
+ return;
+ }
+ // Archive button
+ if (e.target.closest('.archive-btn')) {
+ e.preventDefault();
+ const el = e.target.closest('.archive-btn');
+ const warrantyId = parseInt(el.dataset.id);
+ const card = el.closest('.warranty-card');
+ const titleEl = card ? card.querySelector('.product-name-header .warranty-title') : null;
+ const productName = titleEl ? titleEl.textContent.trim() : '';
+ openArchiveModal(warrantyId, productName);
+ return;
+ }
+ // Unarchive button
+ if (e.target.closest('.unarchive-btn')) {
+ e.preventDefault();
+ const warrantyId = parseInt(e.target.closest('.unarchive-btn').dataset.id);
+ toggleArchiveStatus(warrantyId, false);
+ return;
+ }
+ });
+ }
+
+ // Add claim button
+ if (addClaimBtn) {
+ addClaimBtn.addEventListener('click', () => {
+ openClaimFormModal();
+ });
+ }
+
+ // Claim form submission
+ if (claimForm) {
+ claimForm.addEventListener('submit', handleClaimFormSubmit);
+ }
+
+ // Modal close handling - Removed backdrop click listeners to match warranty modal behavior
+ // Claims modals now only close via explicit close buttons with [data-dismiss="modal"]
+ // The general modal click prevention (e.stopPropagation) handles preventing backdrop clicks
+
+ // Add event listeners for claims modal close buttons
+ if (claimsModal) {
+ claimsModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ closeClaimsModal();
+ });
+ });
+ }
+
+ if (claimFormModal) {
+ claimFormModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ closeClaimFormModal();
+ });
+ });
+ }
+}
+
+/**
+ * Open the claims modal for a specific warranty
+ */
+async function openClaimsModal(warrantyId) {
+ try {
+ currentClaimsWarrantyId = warrantyId;
+
+ // Find warranty info
+ const warranty = warranties.find(w => w.id === warrantyId);
+ if (!warranty) {
+ showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');
+ return;
+ }
+
+ // Determine if current user can edit this warranty
+ const currentUserId = (() => {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.id;
+ } catch (e) {
+ return null;
+ }
+ })();
+ const isAdmin = getUserType() === 'admin';
+ currentClaimsCanEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
+
+ // Show/hide the Add New Claim button based on edit permissions
+ if (addClaimBtn) {
+ addClaimBtn.style.display = currentClaimsCanEdit ? 'inline-block' : 'none';
+ }
+
+ // Update warranty info in modal
+ if (warrantyClaimInfo) {
+ if (window.components && window.components.claims && window.components.claims.renderWarrantyInfo) {
+ window.components.claims.renderWarrantyInfo(warrantyClaimInfo, warranty, formatDate);
+ } else {
+ warrantyClaimInfo.innerHTML = `
+ <div class="warranty-info-card">
+ <h4>${warranty.product_name || 'Unnamed Product'}</h4>
+ <div class="warranty-details">
+ <span><i class="fas fa-building"></i> ${warranty.vendor || 'Unknown Vendor'}</span>
+ <span><i class="fas fa-calendar"></i> Expires: ${formatDate(warranty.expiration_date ? new Date(warranty.expiration_date) : null)}</span>
+ <span class="warranty-status status-${warranty.status || 'unknown'}">
+ ${warranty.statusText || 'Unknown Status'}
+ </span>
+ </div>
+ </div>
+ `;
+ }
+ }
+
+ // Show modal
+ claimsModal.classList.add('active');
+
+ // Load claims
+ await loadClaims(warrantyId);
+
+ } catch (error) {
+ console.error('Error opening claims modal:', error);
+ showToast('Failed to open claims modal', 'error');
+ }
+}
+
+/**
+ * Load claims for a warranty
+ */
+async function loadClaims(warrantyId) {
+ try {
+ // Show loading
+ if (claimsListBody) {
+ if (window.components && window.components.claims && window.components.claims.renderClaimsLoading) {
+ window.components.claims.renderClaimsLoading(claimsListBody);
+ } else {
+ claimsListBody.innerHTML = `
+ <div class="loading-message" style="text-align: center; padding: 20px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading claims...
+ </div>
+ `;
+ }
+ }
+
+ // Fetch claims
+ const response = await fetch(`/api/warranties/${warrantyId}/claims`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to load claims');
+ }
+
+ currentClaims = await response.json();
+ renderClaims();
+
+ } catch (error) {
+ console.error('Error loading claims:', error);
+ if (claimsListBody) {
+ if (window.components && window.components.claims && window.components.claims.renderClaimsError) {
+ window.components.claims.renderClaimsError(claimsListBody, window.i18next ? window.i18next.t('claims.failed_to_load') : 'Failed to load claims');
+ } else {
+ claimsListBody.innerHTML = `
+ <div class="error-message" style="text-align: center; padding: 20px; color: var(--danger-color);">
+ <i class="fas fa-exclamation-triangle"></i> Failed to load claims
+ </div>
+ `;
+ }
+ }
+ }
+}
+
+/**
+ * Render claims list
+ */
+function renderClaims() {
+ if (!claimsListBody) return;
+
+ if (currentClaims.length === 0) {
+ if (window.components && window.components.claims && window.components.claims.renderClaimsList) {
+ window.components.claims.renderClaimsList(claimsListBody, [], currentClaimsCanEdit, formatDate);
+ } else {
+ const noClaimsMessage = currentClaimsCanEdit
+ ? (window.i18next ? window.i18next.t('claims.no_claims_message') : 'Click "Add New Claim" to get started')
+ : 'No claims have been filed for this warranty';
+ claimsListBody.innerHTML = `
+ <div class="no-claims-message" style="text-align: center; padding: 40px;">
+ <i class="fas fa-clipboard-list" style="font-size: 3rem; color: var(--medium-gray); margin-bottom: 1rem;"></i>
+ <h4 style="color: var(--text-color); margin-bottom: 0.5rem;">${window.i18next ? window.i18next.t('claims.no_claims_yet') : 'No Claims Yet'}</h4>
+ <p style="color: var(--dark-gray); margin-bottom: 0;">${noClaimsMessage}</p>
+ </div>
+ `;
+ }
+ return;
+ }
+
+ if (window.components && window.components.claims && window.components.claims.renderClaimsList) {
+ window.components.claims.renderClaimsList(claimsListBody, currentClaims, currentClaimsCanEdit, formatDate);
+ } else {
+ let claimsHtml = '';
+ currentClaims.forEach(claim => {
+ claimsHtml += `
+ <div class="claim-item" data-claim-id="${claim.id}">
+ <div class="claim-header">
+ <div class="claim-info">
+ <div class="claim-title">
+ ${claim.claim_number ? `<strong>${claim.claim_number}</strong>` : `<strong>Claim #${claim.id}</strong>`}
+ <span class="claim-status-badge claim-status-${claim.status.toLowerCase().replace(' ', '-')}">
+ ${claim.status}
+ </span>
+ </div>
+ <div class="claim-date">
+ <i class="fas fa-calendar"></i> ${formatDate(claim.claim_date ? new Date(claim.claim_date) : null)}
+ ${claim.resolution_date && claim.resolution_date.trim() ? `<span style=\"margin-left: 10px;\"><i class=\"fas fa-check-circle\"></i> Resolved: ${formatDate(new Date(claim.resolution_date))}</span>` : ''}
+ </div>
+ </div>
+ <div class="claim-actions">
+ ${currentClaimsCanEdit ? `
+ <button class="btn btn-sm btn-secondary edit-claim-btn" data-claim-id="${claim.id}">
+ <i class="fas fa-edit"></i> Edit
+ </button>
+ <button class="btn btn-sm btn-danger delete-claim-btn" data-claim-id="${claim.id}">
+ <i class="fas fa-trash"></i> Delete
+ </button>
+ ` : `
+ <span class="claim-readonly-indicator" style="color: var(--medium-gray); font-size: 0.9em;">
+ <i class="fas fa-eye"></i> View Only
+ </span>
+ `}
+ </div>
+ </div>
+ ${claim.description ? `<div class=\"claim-description\">${escapeHtml(claim.description)}</div>` : ''}
+ ${claim.resolution ? `<div class=\"claim-resolution\"><strong>Resolution:</strong> ${escapeHtml(claim.resolution)}</div>` : ''}
+ </div>
+ `;
+ });
+ claimsListBody.innerHTML = claimsHtml;
+ }
+
+ // Add event listeners for edit and delete buttons (only if user can edit)
+ if (currentClaimsCanEdit) {
+ claimsListBody.addEventListener('click', (e) => {
+ if (e.target.closest('.edit-claim-btn')) {
+ const claimId = parseInt(e.target.closest('.edit-claim-btn').dataset.claimId);
+ const claim = currentClaims.find(c => c.id === claimId);
+ if (claim) {
+ openClaimFormModal(claim);
+ }
+ }
+
+ if (e.target.closest('.delete-claim-btn')) {
+ const claimId = parseInt(e.target.closest('.delete-claim-btn').dataset.claimId);
+ if (confirm(window.i18next ? window.i18next.t('claims.confirm_delete_claim') : 'Are you sure you want to delete this claim?')) {
+ deleteClaim(claimId);
+ }
+ }
+ });
+ }
+}
+
+/**
+ * Open claim form modal for adding or editing
+ */
+function openClaimFormModal(claim = null) {
+ if (!claimFormModal) return;
+
+ // Update title
+ if (claimFormTitle) {
+ claimFormTitle.textContent = claim ? (window.i18next ? window.i18next.t('claims.edit_claim') : 'Edit Claim') : (window.i18next ? window.i18next.t('claims.add_new_claim') : 'Add New Claim');
+ }
+
+ // Reset form
+ if (claimForm) {
+ claimForm.reset();
+ }
+
+ if (claim) {
+ // Populate form with claim data
+ if (editClaimId) editClaimId.value = claim.id;
+ if (document.getElementById('claimDate')) document.getElementById('claimDate').value = claim.claim_date || '';
+ if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = claim.status;
+ if (document.getElementById('claimNumber')) document.getElementById('claimNumber').value = claim.claim_number || '';
+ if (document.getElementById('claimDescription')) document.getElementById('claimDescription').value = claim.description || '';
+ if (document.getElementById('claimResolution')) document.getElementById('claimResolution').value = claim.resolution || '';
+ if (document.getElementById('resolutionDate')) document.getElementById('resolutionDate').value = claim.resolution_date || '';
+ } else {
+ // Set default values for new claim
+ if (editClaimId) editClaimId.value = '';
+ if (document.getElementById('claimDate')) document.getElementById('claimDate').value = new Date().toISOString().split('T')[0];
+ if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = 'Submitted';
+ }
+
+ // Show modal
+ claimFormModal.classList.add('active');
+}
+
+/**
+ * Handle claim form submission
+ */
+async function handleClaimFormSubmit(event) {
+ event.preventDefault();
+
+ try {
+ const formData = new FormData(claimForm);
+ const claimId = editClaimId.value;
+
+ const claimData = {
+ claim_date: formData.get('claim_date'),
+ status: formData.get('status'),
+ claim_number: formData.get('claim_number'),
+ description: formData.get('description'),
+ resolution: formData.get('resolution'),
+ resolution_date: formData.get('resolution_date')
+ };
+
+ // Remove empty strings
+ Object.keys(claimData).forEach(key => {
+ if (claimData[key] === '') {
+ claimData[key] = null;
+ }
+ });
+
+ const isEdit = claimId && claimId !== '';
+ const url = isEdit
+ ? `/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`
+ : `/api/warranties/${currentClaimsWarrantyId}/claims`;
+ const method = isEdit ? 'PUT' : 'POST';
+
+ const response = await fetch(url, {
+ method: method,
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(claimData)
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to save claim');
+ }
+
+ showToast(isEdit ? (window.i18next ? window.i18next.t('claims.claim_updated_successfully') : 'Claim updated successfully') : (window.i18next ? window.i18next.t('claims.claim_created_successfully') : 'Claim created successfully'), 'success');
+ closeClaimFormModal();
+
+ // Reload claims
+ await loadClaims(currentClaimsWarrantyId);
+
+ } catch (error) {
+ console.error('Error saving claim:', error);
+ showToast(error.message || 'Failed to save claim', 'error');
+ }
+}
+
+/**
+ * Delete a claim
+ */
+async function deleteClaim(claimId) {
+ try {
+ const response = await fetch(`/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete claim');
+ }
+
+ showToast(window.i18next ? window.i18next.t('claims.claim_deleted_successfully') : 'Claim deleted successfully', 'success');
+
+ // Reload claims
+ await loadClaims(currentClaimsWarrantyId);
+
+ } catch (error) {
+ console.error('Error deleting claim:', error);
+ showToast(error.message || 'Failed to delete claim', 'error');
+ }
+}
+
+/**
+ * Close claims modal
+ */
+function closeClaimsModal() {
+ if (claimsModal) {
+ claimsModal.classList.remove('active');
+ }
+ currentClaimsWarrantyId = null;
+ currentClaims = [];
+ currentClaimsCanEdit = false;
+}
+
+/**
+ * Close claim form modal
+ */
+function closeClaimFormModal() {
+ if (claimFormModal) {
+ claimFormModal.classList.remove('active');
+ }
+}
+
+/**
+ * Escape HTML to prevent XSS
+ */
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+// Add this function to handle edit tab functionality
+function initEditTabs() {
+ const editTabBtns = document.querySelectorAll('.edit-tab-btn');
+
+ editTabBtns.forEach(btn => {
+ btn.addEventListener('click', () => {
+ // Remove active class from all tabs
+ editTabBtns.forEach(b => b.classList.remove('active'));
+
+ // Add active class to clicked tab
+ btn.classList.add('active');
+
+ // Hide all tab content
+ document.querySelectorAll('.edit-tab-content').forEach(content => {
+ content.classList.remove('active');
+ });
+
+ // Show the selected tab content
+ const tabId = btn.getAttribute('data-tab');
+ document.getElementById(tabId).classList.add('active');
+ });
+ });
+}
+
+// Update validateEditTabs function
+function validateEditTab(tabId) {
+ const tab = document.getElementById(tabId);
+ if (!tab) {
+ console.warn('validateEditTab: Could not find tab with ID:', tabId);
+ return false; // Or true, depending on desired behavior for missing tabs
+ }
+ let isTabValid = true;
+
+ // Get all relevant form controls within the tab
+ const controls = tab.querySelectorAll('input, textarea, select');
+
+ controls.forEach(control => {
+ // Check the native HTML5 validity state
+ if (!control.validity.valid) {
+ isTabValid = false;
+ control.classList.add('invalid');
+ // Optionally, you could add logic here to display specific messages
+ // or rely on browser default behavior if the form is submitted.
+ } else {
+ control.classList.remove('invalid');
+ }
+ });
+
+ // Update the tab button to show completion status
+ const tabBtn = document.querySelector(`.edit-tab-btn[data-tab="${tabId}"]`);
+ if (tabBtn) {
+ if (isTabValid) {
+ tabBtn.classList.add('completed');
+ } else {
+ tabBtn.classList.remove('completed');
+ }
+ }
+ return isTabValid;
+}
+
+// Add this function for secure file access
+function openSecureFile(filePath) {
+ console.log(`[openSecureFile] Opening file: ${filePath}`);
+
+ // Get the file name from the path, handling both uploads/ prefix and direct filenames
+ let fileName = filePath;
+ if (filePath.startsWith('uploads/')) {
+ fileName = filePath.substring(8); // Remove 'uploads/' prefix
+ } else if (filePath.startsWith('/uploads/')) {
+ fileName = filePath.substring(9); // Remove '/uploads/' prefix
+ }
+
+ console.log(`[openSecureFile] Processed filename: ${fileName}`);
+
+ const token = auth.getToken();
+
+ if (!token) {
+ showToast(window.t('messages.login_to_access_files'), 'error');
+ return false;
+ }
+
+ // Enhanced fetch with retry logic and better error handling
+ const fetchWithRetry = async (url, options, retries = 2) => {
+ for (let i = 0; i <= retries; i++) {
+ try {
+ console.log(`[openSecureFile] Attempt ${i + 1} to fetch: ${url}`);
+ const response = await fetch(url, options);
+
+ if (!response.ok) {
+ if (response.status === 401) {
+ throw new Error('Authentication error. Please log in again.');
+ } else if (response.status === 403) {
+ throw new Error('You are not authorized to access this file.');
+ } else if (response.status === 404) {
+ throw new Error('File not found. It may have been deleted.');
+ } else {
+ throw new Error(`Server error: ${response.status} ${response.statusText}`);
+ }
+ }
+
+ // Check if response has content-length header
+ const contentLength = response.headers.get('content-length');
+ console.log(`[openSecureFile] Response Content-Length: ${contentLength}`);
+
+ // Convert to blob with error handling
+ const blob = await response.blob();
+ console.log(`[openSecureFile] Blob size: ${blob.size} bytes`);
+
+ // Verify blob size matches content-length if available
+ if (contentLength && parseInt(contentLength) !== blob.size) {
+ console.warn(`[openSecureFile] Content-Length mismatch: header=${contentLength}, blob=${blob.size}`);
+ if (i < retries) {
+ console.log(`[openSecureFile] Retrying due to content-length mismatch...`);
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retry
+ continue;
+ } else {
+ console.error(`[openSecureFile] Final attempt failed with content-length mismatch`);
+ }
+ }
+
+ return blob;
+
+ } catch (error) {
+ console.error(`[openSecureFile] Attempt ${i + 1} failed:`, error);
+
+ // If this is a content-length mismatch or network error, retry
+ if (i < retries && (
+ error.message.includes('content-length') ||
+ error.message.includes('Failed to fetch') ||
+ error.name === 'TypeError'
+ )) {
+ console.log(`[openSecureFile] Retrying after error: ${error.message}`);
+ await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // Exponential backoff
+ continue;
+ }
+
+ throw error;
+ }
+ }
+ };
+
+ fetchWithRetry(`/api/secure-file/${fileName}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
+ 'Pragma': 'no-cache'
+ }
+ })
+ .then(blob => {
+ console.log(`[openSecureFile] Successfully received blob of size: ${blob.size}`);
+
+ // Create a URL for the blob
+ const blobUrl = window.URL.createObjectURL(blob);
+
+ // Open in new tab
+ const newWindow = window.open(blobUrl, '_blank');
+
+ // Clean up the blob URL after a delay to prevent memory leaks
+ setTimeout(() => {
+ window.URL.revokeObjectURL(blobUrl);
+ }, 10000); // Clean up after 10 seconds
+
+ // Check if window was blocked by popup blocker
+ if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
+ showToast(window.t('messages.popup_blocked'), 'warning');
+ window.URL.revokeObjectURL(blobUrl); // Clean up immediately if blocked
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching file:', error);
+
+ // Provide more specific error messages
+ let errorMessage = 'Error opening file';
+ if (error.message.includes('Authentication')) {
+ errorMessage = 'Authentication error. Please refresh and try again.';
+ } else if (error.message.includes('authorized')) {
+ errorMessage = 'You are not authorized to access this file.';
+ } else if (error.message.includes('not found')) {
+ errorMessage = 'File not found. It may have been deleted.';
+ } else if (error.message.includes('Failed to fetch') || error.name === 'TypeError') {
+ errorMessage = 'Network error. Please check your connection and try again.';
+ } else {
+ errorMessage = `Error opening file: ${error.message}`;
+ }
+
+ showToast(errorMessage, 'error');
+ });
+
+ return false;
+}
+
+/**
+ * Open a Paperless-ngx document by ID
+ */
+
+/**
+ * Generate document link HTML for both local and Paperless-ngx documents
+ */
+function generateDocumentLink(warranty, docType) {
+ const docConfig = {
+ invoice: {
+ localPath: warranty.invoice_path,
+ paperlessId: warranty.paperless_invoice_id,
+ url: warranty.invoice_url,
+ icon: 'fas fa-file-invoice',
+ label: 'Invoice',
+ className: 'invoice-link'
+ },
+ manual: {
+ localPath: warranty.manual_path,
+ paperlessId: warranty.paperless_manual_id,
+ url: warranty.manual_url,
+ icon: 'fas fa-book',
+ label: 'Manual',
+ className: 'manual-link'
+ },
+ other: {
+ localPath: warranty.other_document_path,
+ paperlessId: warranty.paperless_other_id,
+ url: warranty.other_document_url,
+ icon: 'fas fa-file-alt',
+ label: 'Files',
+ className: 'other-document-link'
+ },
+ photo: {
+ localPath: warranty.product_photo_path,
+ paperlessId: warranty.paperless_photo_id,
+ url: null, // Photos don't have URLs
+ icon: 'fas fa-image',
+ label: 'Photo',
+ className: 'photo-link'
+ }
+ };
+
+ const config = docConfig[docType];
+ if (!config) return '';
+
+ // Check Global View permissions for "other" documents
+ if (docType === 'other' && isGlobalView) {
+ // Get current user ID to check warranty ownership
+ const currentUserId = (() => {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.id;
+ } catch (e) {
+ return null;
+ }
+ })();
+
+ const isAdmin = getUserType() === 'admin';
+ const canViewOtherDocs = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
+
+ // Hide "other" documents in Global View unless user owns the warranty or is admin
+ if (!canViewOtherDocs) {
+ return '';
+ }
+ }
+
+ const hasLocal = config.localPath && config.localPath !== 'null';
+ const hasPaperless = config.paperlessId && config.paperlessId !== null;
+ const hasUrl = config.url && config.url.trim() !== '';
+
+
+ let linksHtml = '';
+
+ if (hasLocal) {
+ linksHtml += `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">
+ <i class="${config.icon}"></i> ${config.label}
+ </a>`;
+ } else if (hasPaperless) {
+ const warrantyContextJson = JSON.stringify({user_id: warranty.user_id, id: warranty.id}).replace(/"/g, '&quot;');
+ linksHtml += `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}, JSON.parse('${warrantyContextJson}')); return false;" class="${config.className}">
+ <i class="${config.icon}"></i> ${config.label} <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>
+ </a>`;
+ }
+
+ // Add URL link if available
+ if (hasUrl) {
+ if (linksHtml) linksHtml += ' ';
+ linksHtml += `<a href="${config.url}" target="_blank" class="document-url-link ${config.className}" title="Open ${config.label} URL">
+ <i class="fas fa-link"></i> ${config.label} Link
+ </a>`;
+ }
+
+ return linksHtml;
+}
+
+// Initialize the warranty form and all its components
+function initWarrantyForm() {
+ // Initialize form tabs
+ if (formTabs && tabContents) {
+ initFormTabs();
+ }
+
+ // Initialize serial number inputs
+ addSerialNumberInput();
+
+ // Initialize file input display
+ if (document.getElementById('productPhoto')) {
+ document.getElementById('productPhoto').addEventListener('change', function(event) {
+ updateFileName(event, 'productPhoto', 'productPhotoFileName');
+ });
+ }
+
+ if (document.getElementById('invoice')) {
+ document.getElementById('invoice').addEventListener('change', function(event) {
+ updateFileName(event, 'invoice', 'fileName');
+ });
+ }
+
+ if (document.getElementById('manual')) {
+ document.getElementById('manual').addEventListener('change', function(event) {
+ updateFileName(event, 'manual', 'manualFileName');
+ });
+ }
+
+ if (document.getElementById('otherDocument')) {
+ document.getElementById('otherDocument').addEventListener('change', function(event) {
+ updateFileName(event, 'otherDocument', 'otherDocumentFileName');
+ });
+ }
+
+ // Initialize tag functionality
+ initTagFunctionality();
+
+ // Form submission
+ if (warrantyForm) {
+ warrantyForm.addEventListener('submit', handleFormSubmit); // Use renamed handler
+ }
+
+ // Initialize lifetime checkbox listener
+ if (isLifetimeCheckbox && warrantyDurationFields) { // Check for new container
+ isLifetimeCheckbox.addEventListener('change', handleLifetimeChange);
+ handleLifetimeChange(); // Initial check
+ } else {
+ console.error("Lifetime warranty elements or duration fields not found in add form");
+ }
+}
+
+// Initialize tag functionality
+function initTagFunctionality() {
+ // This function now ONLY sets up listeners for the main "Add Warranty" form's tag interface.
+ // Assumes globalTagManagementModal listeners (new tag form, close buttons) are set up separately if the modal exists.
+
+ // Get main form tag elements
+ const mainFormTagSearch = document.getElementById('tagSearch');
+ const mainFormTagsList = document.getElementById('tagsList'); // Dropdown for search in main form
+ const mainFormManageTagsBtn = document.getElementById('manageTagsBtn'); // "Manage Tags" button in main form
+ const mainFormSelectedTagsContainer = document.getElementById('selectedTags'); // Container for selected tags in main form
+
+ // Skip if main form specific tag elements don't exist
+ if (!mainFormTagSearch || !mainFormTagsList || !mainFormManageTagsBtn || !mainFormSelectedTagsContainer) {
+ console.log('Main form tag UI elements (tagSearch, tagsList, manageTagsBtn, or selectedTagsContainer) not found, skipping main form tag UI initialization.');
+ return;
+ }
+
+ console.log('Initializing main form tag UI functionality (search, selection, manage button).');
+
+ // Load allTags if not already loaded (needed for search suggestions in the main form)
+ if (allTags.length === 0) {
+ loadTags(); // loadTags is async
+ }
+
+ mainFormTagSearch.addEventListener('focus', () => {
+ renderTagsList(); // Renders suggestions into mainFormTagsList based on allTags
+ mainFormTagsList.classList.add('show');
+ });
+
+ mainFormTagSearch.addEventListener('input', () => {
+ renderTagsList(mainFormTagSearch.value); // Filters suggestions
+ });
+
+ // Hide main form's tag suggestion dropdown when clicking outside
+ document.addEventListener('click', (e) => {
+ // Check if mainFormTagSearch and mainFormTagsList are still valid (e.g. not removed from DOM)
+ if (mainFormTagSearch && mainFormTagsList &&
+ !mainFormTagSearch.contains(e.target) &&
+ !mainFormTagsList.contains(e.target)) {
+ mainFormTagsList.classList.remove('show');
+ }
+ });
+
+ // "Manage Tags" button in the main form opens the global tagManagementModal
+ mainFormManageTagsBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ openTagManagementModal(); // This function shows the global modal
+ });
+
+ // Initial rendering of selected tags for the main form (if any are pre-selected or loaded)
+ renderSelectedTags(); // Renders into mainFormSelectedTagsContainer
+}
+
+// Function to load all tags
+async function loadTags(force = false) {
+ console.log('[script.js] loadTags() called. Current page:', window.location.pathname);
+
+ // Check if tags are already loaded and reasonably populated
+ if (!force && allTags && allTags.length > 0) {
+ console.log('[script.js] Tags already loaded in allTags global. Skipping fetch. Count:', allTags.length);
+ // Optionally, re-dispatch the event if other components might need it on subsequent (though now less likely) calls
+ // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
+ return;
+ }
+
+ try {
+ const token = auth.getToken();
+ if (!token) {
+ console.warn('[script.js] No token available for loadTags. User might not be authenticated yet.');
+ allTags = []; // Ensure allTags is empty if we can't load
+ if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
+ return;
+ }
+ const response = await fetch('/api/tags', {
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error('[script.js] Failed to load tags:', response.status, errorText);
+ allTags = []; // Default to empty on error
+ if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
+ return;
+ }
+ const fetchedTags = await response.json();
+ // Assuming fetchedTags is an array of {id, name, color, ...} as expected by other functions
+ allTags = fetchedTags;
+ if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
+ console.log('[script.js] All tags loaded into global allTags variable:', allTags.length, 'tags. Sample:', allTags.slice(0,2));
+ // Dispatch event for any components that might be waiting for tags (e.g., Tagify instances)
+ document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
+
+ } catch (error) {
+ console.error('[script.js] Error in loadTags():', error);
+ allTags = []; // Default to empty on critical error
+ if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
+ }
+}
+
+// Render the tags dropdown list
+function renderTagsList(searchTerm = '') {
+ if (!tagsList) return;
+
+ while (tagsList.firstChild) tagsList.removeChild(tagsList.firstChild);
+
+ // Filter tags based on search term
+ const filteredTags = allTags.filter(tag =>
+ !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
+ );
+
+ // Add option to create new tag if search term is provided and not in list
+ if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
+ const createOption = document.createElement('div');
+ createOption.className = 'tag-option create-tag';
+ const icon = document.createElement('i'); icon.className = 'fas fa-plus';
+ createOption.appendChild(icon);
+ const createText = (window.i18next ? window.i18next.t('actions.create') : 'Create');
+ createOption.appendChild(document.createTextNode(` ${createText} "${searchTerm}"`));
+ createOption.addEventListener('click', () => {
+ createTag(searchTerm).then(newTag => {
+ // Add the new tag to selectedTags
+ selectedTags.push(newTag);
+ renderSelectedTags();
+ renderTagsList(''); // Clear search and refresh list
+ });
+ tagsList.classList.remove('show');
+ });
+ tagsList.appendChild(createOption);
+ }
+
+ // Add existing tags to dropdown
+ filteredTags.forEach(tag => {
+ const option = document.createElement('div');
+ option.className = 'tag-option';
+
+ // Check if tag is already selected
+ const isSelected = selectedTags.some(selected => selected.id === tag.id);
+
+ const color = document.createElement('span'); color.className = 'tag-color'; color.style.backgroundColor = tag.color;
+ const name = document.createTextNode(` ${tag.name}`);
+ const status = document.createElement('span'); status.className = 'tag-status';
+ if (isSelected) {
+ const check = document.createElement('i'); check.className = 'fas fa-check';
+ status.appendChild(check);
+ }
+ option.appendChild(color);
+ option.appendChild(name);
+ option.appendChild(status);
+
+ option.addEventListener('click', () => {
+ if (isSelected) {
+ // Remove tag if already selected
+ selectedTags = selectedTags.filter(selected => selected.id !== tag.id);
+ } else {
+ // Add tag if not selected
+ selectedTags.push({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ });
+ }
+
+ renderSelectedTags();
+ renderTagsList(searchTerm);
+ });
+
+ tagsList.appendChild(option);
+ });
+
+ // Show the dropdown
+ tagsList.classList.add('show');
+}
+
+// Update renderEditTagsList to add new tag to editSelectedTags after creation
+function renderEditTagsList(searchTerm = '') {
+ const editTagsList = document.getElementById('editTagsList');
+ if (!editTagsList) return;
+ while (editTagsList.firstChild) editTagsList.removeChild(editTagsList.firstChild);
+ // Filter tags based on search term
+ const filteredTags = allTags.filter(tag =>
+ !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
+ );
+ // Add option to create new tag if search term is provided and not in list
+ if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
+ const createOption = document.createElement('div');
+ createOption.className = 'tag-option create-tag';
+ const plus = document.createElement('i');
+ plus.className = 'fas fa-plus';
+ createOption.appendChild(plus);
+ createOption.appendChild(document.createTextNode(' ' + (window.i18next ? window.i18next.t('actions.create') : 'Create') + ` "${searchTerm}"`));
+ createOption.addEventListener('click', () => {
+ createTag(searchTerm).then(newTag => {
+ // Add the new tag to editSelectedTags
+ editSelectedTags.push(newTag);
+ renderEditSelectedTags();
+ renderEditTagsList(''); // Clear search and refresh list
+ });
+ editTagsList.classList.remove('show');
+ });
+ editTagsList.appendChild(createOption);
+ }
+ // Add existing tags to dropdown
+ filteredTags.forEach(tag => {
+ const option = document.createElement('div');
+ option.className = 'tag-option';
+
+ // Check if tag is already selected
+ const isSelected = editSelectedTags.some(selected => selected.id === tag.id);
+ const colorSpan = document.createElement('span');
+ colorSpan.className = 'tag-color';
+ colorSpan.style.backgroundColor = tag.color;
+ const nameText = document.createTextNode(tag.name);
+ const statusSpan = document.createElement('span');
+ statusSpan.className = 'tag-status';
+ if (isSelected) {
+ const check = document.createElement('i');
+ check.className = 'fas fa-check';
+ statusSpan.appendChild(check);
+ }
+ option.appendChild(colorSpan);
+ option.appendChild(document.createTextNode(' '));
+ option.appendChild(nameText);
+ option.appendChild(statusSpan);
+
+ option.addEventListener('click', () => {
+ if (isSelected) {
+ // Remove tag if already selected
+ editSelectedTags = editSelectedTags.filter(selected => selected.id !== tag.id);
+ } else {
+ // Add tag if not selected
+ editSelectedTags.push({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ });
+ }
+
+ // Use our helper function to render selected tags
+ renderEditSelectedTags();
+
+ renderEditTagsList(searchTerm);
+ });
+
+ editTagsList.appendChild(option);
+ });
+
+ // Show the dropdown
+ editTagsList.classList.add('show');
+}
+
+// Render the selected tags
+function renderSelectedTags() {
+ if (!selectedTagsContainer) return;
+ while (selectedTagsContainer.firstChild) selectedTagsContainer.removeChild(selectedTagsContainer.firstChild);
+
+ if (selectedTags.length === 0) {
+ const placeholder = document.createElement('span');
+ placeholder.className = 'no-tags-selected';
+ placeholder.textContent = 'No tags selected';
+ selectedTagsContainer.appendChild(placeholder);
+ return;
+ }
+
+ selectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
+ tagElement.appendChild(document.createTextNode(tag.name + ' '));
+ const removeSpan = document.createElement('span');
+ removeSpan.className = 'remove-tag';
+ removeSpan.dataset.id = String(tag.id);
+ removeSpan.textContent = '×';
+ tagElement.appendChild(removeSpan);
+
+ // Add event listener for removing tag
+ removeSpan.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedTags = selectedTags.filter(t => t.id !== tag.id);
+ renderSelectedTags();
+
+ // Update summary if needed
+ if (document.getElementById('summary-tags')) {
+ updateSummary();
+ }
+ });
+
+ selectedTagsContainer.appendChild(tagElement);
+ });
+}
+
+// Helper function to render the edit selected tags
+function renderEditSelectedTags() {
+ const editSelectedTagsContainer = document.getElementById('editSelectedTags');
+ if (!editSelectedTagsContainer) return;
+ while (editSelectedTagsContainer.firstChild) editSelectedTagsContainer.removeChild(editSelectedTagsContainer.firstChild);
+
+ if (editSelectedTags.length > 0) {
+ editSelectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
+ tagElement.appendChild(document.createTextNode(tag.name + ' '));
+ const removeSpan = document.createElement('span');
+ removeSpan.className = 'remove-tag';
+ removeSpan.dataset.id = String(tag.id);
+ removeSpan.textContent = '×';
+ tagElement.appendChild(removeSpan);
+
+ // Add event listener for removing tag
+ removeSpan.addEventListener('click', (e) => {
+ e.stopPropagation();
+ e.preventDefault(); // Add this to prevent default action
+
+ // Prevent the event from bubbling up to parent elements
+ if (e.cancelBubble !== undefined) {
+ e.cancelBubble = true;
+ }
+
+ editSelectedTags = editSelectedTags.filter(t => t.id !== tag.id);
+
+ // Re-render just the tags
+ renderEditSelectedTags();
+ return false; // Add return false for older browsers
+ });
+
+ editSelectedTagsContainer.appendChild(tagElement);
+ });
+ } else {
+ const placeholder = document.createElement('span');
+ placeholder.className = 'no-tags-selected';
+ placeholder.textContent = 'No tags selected';
+ editSelectedTagsContainer.appendChild(placeholder);
+ }
+}
+
+// Update createTag to return a Promise
+function createTag(name) {
+ return new Promise((resolve, reject) => {
+ // Enhanced auth manager availability check
+ if (!window.auth) {
+ console.error('[createTag] Auth manager not available');
+ reject(new Error('Authentication system not ready. Please try again.'));
+ return;
+ }
+
+ // Use auth manager's getToken method instead of directly accessing localStorage
+ const token = window.auth.getToken();
+ console.log('[createTag] Debug info:', {
+ hasToken: !!token,
+ tokenLength: token ? token.length : 0,
+ hasUserInfo: !!localStorage.getItem('user_info'),
+ authManagerAvailable: !!window.auth,
+ isAuthenticated: window.auth.isAuthenticated(),
+ tokenSource: 'auth.getToken()'
+ });
+
+ if (!token) {
+ console.error('[createTag] No authentication token found');
+ reject(new Error('No authentication token found. Please try logging in again.'));
+ return;
+ }
+ // Generate a random color for the tag
+ const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
+ fetch('/api/tags', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer ' + token
+ },
+ body: JSON.stringify({
+ name: name,
+ color: color
+ })
+ })
+ .then(response => {
+ if (!response.ok) {
+ // Enhanced error handling to capture specific error details
+ return response.json().then(errorData => {
+ console.error('[createTag] API Error Response:', {
+ status: response.status,
+ statusText: response.statusText,
+ errorData: errorData
+ });
+
+ if (response.status === 409) {
+ reject(new Error(window.t('messages.tag_already_exists')));
+ return;
+ }
+ if (response.status === 401) {
+ reject(new Error('Authentication failed. Please try logging in again.'));
+ return;
+ }
+ if (response.status === 403) {
+ reject(new Error('Permission denied. You may not have access to create tags.'));
+ return;
+ }
+
+ const errorMsg = errorData?.error || errorData?.message || 'Failed to create tag';
+ reject(new Error(errorMsg));
+ }).catch(() => {
+ // If response body is not JSON or is empty
+ console.error('[createTag] Non-JSON error response:', response.status, response.statusText);
+ reject(new Error(`Failed to create tag (${response.status})`));
+ });
+ }
+ return response.json();
+ })
+ .then(data => {
+ if (!data) return;
+ const newTag = {
+ id: data.id,
+ name: data.name,
+ color: data.color
+ };
+ allTags.push(newTag);
+ renderExistingTags();
+ populateTagFilter();
+ showToast(window.t('messages.tag_created_successfully'), 'success');
+ resolve(newTag);
+ })
+ .catch(error => {
+ console.error('Error creating tag:', error);
+ showToast(error.message || window.t('messages.failed_to_create_tag'), 'error');
+ reject(error);
+ });
+ });
+}
+
+// Helper function to determine text color based on background color
+function getContrastColor(hexColor) {
+ // Convert hex to RGB
+ const r = parseInt(hexColor.substr(1, 2), 16);
+ const g = parseInt(hexColor.substr(3, 2), 16);
+ const b = parseInt(hexColor.substr(5, 2), 16);
+
+ // Calculate luminance
+ const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
+
+ // Return black or white depending on luminance
+ return (yiq >= 128) ? '#000000' : '#ffffff';
+}
+
+// Open tag management modal
+function openTagManagementModal() {
+ if (!tagManagementModal) return;
+
+ // Populate existing tags
+ renderExistingTags();
+ addTagManagementEventListeners();
+
+ // Show modal
+ tagManagementModal.classList.add('active');
+}
+
+// Render existing tags in the management modal
+function renderExistingTags() {
+ if (!existingTagsContainer) return;
+ existingTagsContainer.textContent = '';
+
+ const wrapper = document.createElement('div');
+ // Ensure horizontal scroll on small screens
+ wrapper.className = 'table-responsive';
+ const table = document.createElement('table');
+ table.className = 'tag-management-table';
+
+ // Header
+ const thead = document.createElement('thead');
+ const trHead = document.createElement('tr');
+ const thColor = document.createElement('th'); thColor.className = 'tag-color-header'; thColor.textContent = window.i18next ? window.i18next.t('warranties.color') : 'Color';
+ const thName = document.createElement('th'); thName.textContent = window.i18next ? window.i18next.t('warranties.name') : 'Name';
+ const thActions = document.createElement('th'); thActions.className = 'tag-actions-header'; thActions.textContent = window.i18next ? window.i18next.t('actions.actions') : 'Actions';
+ trHead.appendChild(thColor); trHead.appendChild(thName); trHead.appendChild(thActions);
+ thead.appendChild(trHead);
+ table.appendChild(thead);
+
+ const tbody = document.createElement('tbody');
+
+ if (!allTags || allTags.length === 0) {
+ const emptyRow = document.createElement('tr');
+ const td = document.createElement('td'); td.colSpan = 3;
+ const noDiv = document.createElement('div'); noDiv.className = 'no-tags'; noDiv.textContent = window.t ? window.t('messages.no_tags_created_yet') : 'No tags created yet';
+ td.appendChild(noDiv); emptyRow.appendChild(td); tbody.appendChild(emptyRow);
+ } else {
+ allTags.forEach(tag => {
+ const row = document.createElement('tr');
+ row.className = 'existing-tag-row';
+ row.dataset.id = String(tag.id);
+ // Color cell
+ const tdColor = document.createElement('td');
+ const swatchContainer = document.createElement('div'); swatchContainer.className = 'tag-color-swatch-container';
+ const swatch = document.createElement('div'); swatch.className = 'tag-color-swatch'; swatch.style.backgroundColor = tag.color; swatch.setAttribute('aria-label', escapeHtml(tag.name));
+ const colorInput = document.createElement('input'); colorInput.type = 'color'; colorInput.className = 'tag-color-input-hidden'; colorInput.value = tag.color; colorInput.setAttribute('aria-label', 'Pick color');
+ swatchContainer.appendChild(swatch); swatchContainer.appendChild(colorInput); tdColor.appendChild(swatchContainer);
+ // Name cell
+ const tdName = document.createElement('td');
+ const nameDisp = document.createElement('span'); nameDisp.className = 'tag-name-display'; nameDisp.textContent = tag.name;
+ const nameInput = document.createElement('input'); nameInput.type = 'text'; nameInput.className = 'form-control tag-name-input'; nameInput.value = tag.name;
+ tdName.appendChild(nameDisp); tdName.appendChild(nameInput);
+ // Actions cell
+ const tdActions = document.createElement('td'); tdActions.className = 'tag-actions';
+ const viewActions = document.createElement('div'); viewActions.className = 'view-actions';
+ const editBtn = document.createElement('button'); editBtn.className = 'btn btn-sm btn-secondary edit-tag'; editBtn.title = 'Edit'; const editIcon = document.createElement('i'); editIcon.className = 'fas fa-edit'; editBtn.appendChild(editIcon);
+ const delBtn = document.createElement('button'); delBtn.className = 'btn btn-sm btn-danger delete-tag'; delBtn.title = 'Delete'; const delIcon = document.createElement('i'); delIcon.className = 'fas fa-trash'; delBtn.appendChild(delIcon);
+ viewActions.appendChild(editBtn); viewActions.appendChild(delBtn);
+ const editActions = document.createElement('div'); editActions.className = 'edit-actions';
+ const saveBtn = document.createElement('button'); saveBtn.className = 'btn btn-sm btn-primary save-tag'; saveBtn.title = 'Save'; const saveIcon = document.createElement('i'); saveIcon.className = 'fas fa-check'; saveBtn.appendChild(saveIcon);
+ const cancelBtn = document.createElement('button'); cancelBtn.className = 'btn btn-sm btn-secondary cancel-edit'; cancelBtn.title = 'Cancel'; const cancelIcon = document.createElement('i'); cancelIcon.className = 'fas fa-times'; cancelBtn.appendChild(cancelIcon);
+ editActions.appendChild(saveBtn); editActions.appendChild(cancelBtn);
+ tdActions.appendChild(viewActions); tdActions.appendChild(editActions);
+ // Append cells to row
+ row.appendChild(tdColor); row.appendChild(tdName); row.appendChild(tdActions);
+
+ tbody.appendChild(row);
+ });
+ }
+
+ table.appendChild(tbody);
+ wrapper.appendChild(table);
+ existingTagsContainer.appendChild(wrapper);
+
+ // Ensure delegation is attached once
+ addTagManagementEventListeners();
+}
+
+// Edit a tag
+function editTag(row) {
+ // Switch row into edit mode (toggle inputs/buttons)
+ const nameDisplay = row.querySelector('.tag-name-display');
+ const nameInput = row.querySelector('.tag-name-input');
+ const viewActions = row.querySelector('.view-actions');
+ const editActions = row.querySelector('.edit-actions');
+ if (!nameDisplay || !nameInput || !viewActions || !editActions) return;
+
+ nameDisplay.style.display = 'none';
+ nameInput.style.display = 'block';
+ viewActions.style.display = 'none';
+ editActions.style.display = 'flex';
+ row.classList.add('editing');
+}
+
+// Update a tag
+function updateTag(id, name, color) {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ return;
+ }
+
+ fetch(`/api/tags/${id}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer ' + token
+ },
+ body: JSON.stringify({
+ name: name,
+ color: color
+ })
+ })
+ .then(response => {
+ if (!response.ok) {
+ if (response.status === 409) {
+ throw new Error('A tag with this name already exists');
+ }
+ throw new Error(window.t('messages.failed_to_update_tag'));
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Refresh lists to ensure consistency and exit edit mode
+ return loadTags(true).then(() => {
+ // Update local selections and warranties to reflect new tag data immediately
+ try {
+ if (data && typeof data.id !== 'undefined') {
+ // Update selected tags in Add Warranty flow
+ if (Array.isArray(selectedTags) && selectedTags.length > 0) {
+ selectedTags = selectedTags.map(t => t.id === data.id ? { id: data.id, name: data.name, color: data.color } : t);
+ }
+ // Update selected tags in Edit Warranty flow
+ if (Array.isArray(editSelectedTags) && editSelectedTags.length > 0) {
+ editSelectedTags = editSelectedTags.map(t => t.id === data.id ? { id: data.id, name: data.name, color: data.color } : t);
+ }
+ // Update tags inside existing warranties so cards reflect changes
+ if (Array.isArray(warranties) && warranties.length > 0) {
+ warranties.forEach(w => {
+ if (Array.isArray(w.tags)) {
+ w.tags.forEach(tag => {
+ if (tag.id === data.id) {
+ tag.name = data.name;
+ tag.color = data.color;
+ }
+ });
+ }
+ });
+ }
+ }
+ } catch (e) {
+ console.warn('[script.js] Non-fatal error while updating local tag state after update:', e);
+ }
+
+ renderExistingTags();
+ renderSelectedTags();
+ renderEditSelectedTags();
+ populateTagFilter();
+ renderWarranties(warranties);
+ if (document.getElementById('summary-tags')) {
+ updateSummary();
+ }
+ showToast(window.t('messages.tag_updated_successfully'), 'success');
+ });
+ })
+ .catch(error => {
+ console.error('Error updating tag:', error);
+ showToast(error.message || window.t('messages.failed_to_update_tag'), 'error');
+ });
+}
+
+// Centralized event delegation for tag management table
+function addTagManagementEventListeners() {
+ if (!tagManagementModal) return;
+ const container = existingTagsContainer;
+ if (!container) return;
+
+ // Avoid attaching multiple times
+ if (container.dataset.tmListenersAttached === 'true') return;
+ container.dataset.tmListenersAttached = 'true';
+
+ container.addEventListener('click', (e) => {
+ const row = e.target.closest('tr.existing-tag-row');
+ if (!row) return;
+ const id = parseInt(row.dataset.id, 10);
+ if (Number.isNaN(id)) return;
+
+ if (e.target.closest('.edit-tag')) {
+ editTag(row);
+ return;
+ }
+ if (e.target.closest('.cancel-edit')) {
+ // Exit edit mode: revert inputs/buttons visibility
+ const nameDisplay = row.querySelector('.tag-name-display');
+ const nameInput = row.querySelector('.tag-name-input');
+ const viewActions = row.querySelector('.view-actions');
+ const editActions = row.querySelector('.edit-actions');
+ if (nameDisplay && nameInput && viewActions && editActions) {
+ nameDisplay.style.display = '';
+ nameInput.style.display = 'none';
+ viewActions.style.display = '';
+ editActions.style.display = 'none';
+ }
+ row.classList.remove('editing');
+ return;
+ }
+ if (e.target.closest('.save-tag')) {
+ const nameInput = row.querySelector('.tag-name-input');
+ const colorInput = row.querySelector('.tag-color-input-hidden');
+ const newName = (nameInput && nameInput.value ? nameInput.value.trim() : '');
+ const newColor = colorInput ? colorInput.value : undefined;
+ if (!newName) {
+ showToast(window.t('messages.tag_name_required'), 'error');
+ return;
+ }
+ updateTag(id, newName, newColor);
+ row.classList.remove('editing');
+ return;
+ }
+ if (e.target.closest('.delete-tag')) {
+ deleteTag(id);
+ return;
+ }
+ });
+
+ // Color picker change via delegation
+ container.addEventListener('input', (e) => {
+ if (e.target.matches('.tag-color-input-hidden')) {
+ const row = e.target.closest('tr.existing-tag-row');
+ const swatch = row ? row.querySelector('.tag-color-swatch') : null;
+ if (swatch) swatch.style.backgroundColor = e.target.value;
+ }
+ });
+
+ // Auto-save color changes without requiring Edit/Save click
+ container.addEventListener('change', (e) => {
+ if (e.target.matches('.tag-color-input-hidden')) {
+ const row = e.target.closest('tr.existing-tag-row');
+ if (!row) return;
+ const id = parseInt(row.dataset.id, 10);
+ if (Number.isNaN(id)) return;
+ const nameInput = row.querySelector('.tag-name-input');
+ const nameDisplay = row.querySelector('.tag-name-display');
+ const currentName = (nameInput && nameInput.style.display !== 'none' ? nameInput.value : (nameDisplay ? nameDisplay.textContent : '')).trim();
+ const newColor = e.target.value;
+ if (!currentName) {
+ showToast(window.t ? window.t('messages.tag_name_required') : 'Tag name is required', 'error');
+ return;
+ }
+ updateTag(id, currentName, newColor);
+ }
+ });
+}
+
+// Delete a tag
+function deleteTag(id) {
+ if (!confirm('Are you sure you want to delete this tag? It will be removed from all warranties.')) {
+ return;
+ }
+
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ showToast(window.t('messages.authentication_required'), 'error'); // Added toast for better feedback
+ return;
+ }
+
+ showLoadingSpinner(); // Show loading indicator
+
+ fetch(`/api/tags/${id}`, { // Use the correct URL with tag ID
+ method: 'DELETE', // Use DELETE method
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ // Log the status for debugging the 405 error
+ console.error(`Failed to delete tag. Status: ${response.status} ${response.statusText}`);
+ // Try to get error message from response body
+ return response.json().then(errData => {
+ throw new Error(errData.error || errData.message || 'Failed to delete tag');
+ }).catch(() => {
+ // If response body is not JSON or empty
+ throw new Error(`Failed to delete tag. Status: ${response.status}`);
+ });
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Remove tag from allTags array
+ allTags = allTags.filter(tag => tag.id !== id);
+ if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
+
+ // Remove tag from selectedTags if present (in both add and edit modes)
+ selectedTags = selectedTags.filter(tag => tag.id !== id);
+ editSelectedTags = editSelectedTags.filter(tag => tag.id !== id);
+
+ // Remove tag from warranties array
+ warranties.forEach(warranty => {
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ warranty.tags = warranty.tags.filter(tag => tag.id !== id);
+ }
+ });
+
+ // --- FIX: Re-render UI elements ---
+ renderExistingTags(); // Update the list in the modal
+ renderSelectedTags(); // Update selected tags in the add form
+ renderEditSelectedTags(); // Update selected tags in the edit form
+ populateTagFilter(); // Update the filter dropdown on the main page
+ renderWarranties(warranties); // Update warranty cards to remove deleted tag
+ // --- END FIX ---
+
+ showToast(window.t('messages.tag_deleted_successfully'), 'success');
+ })
+ .catch(error => {
+ console.error('Error deleting tag:', error);
+ showToast(error.message || window.t('messages.failed_to_delete_tag'), 'error'); // Show specific error message
+ })
+ .finally(() => {
+ hideLoadingSpinner(); // Hide loading indicator
+ });
+}
+
+// Set up event listeners for UI controls
+function setupUIEventListeners() {
+ // --- Global Manage Tags Button ---
+ const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');
+ if (globalManageTagsBtn) {
+ globalManageTagsBtn.addEventListener('click', async () => {
+ // Ensure allTags are loaded before opening the modal
+ if (!allTags || allTags.length === 0) {
+ showLoadingSpinner();
+ try {
+ await loadTags();
+ } catch (error) {
+ console.error("Failed to load tags before opening modal:", error);
+ showToast(window.t('messages.could_not_load_tags'), "error");
+ hideLoadingSpinner();
+ return;
+ }
+ hideLoadingSpinner();
+ }
+ openTagManagementModal();
+ });
+ }
+ // Initialize edit tabs
+ initEditTabs();
+
+ // Close modals when clicking outside or on close button
+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
+ element.addEventListener('click', (e) => {
+ // Check if the click is on the backdrop itself OR a dismiss button
+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {
+ // Find the closest modal backdrop to the element clicked
+ const modalToClose = e.target.closest('.modal-backdrop');
+
+ if (modalToClose) {
+ // *** MODIFIED CHECK ***
+ // If the click target is the backdrop itself (not a dismiss button)
+ // AND the modal is one of the protected modals, then DO NOTHING.
+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal' ||
+ modalToClose.id === 'claimsModal' || modalToClose.id === 'claimFormModal') && e.target === modalToClose) {
+ return; // Ignore backdrop click for protected modals
+ }
+ // *** END MODIFIED CHECK ***
+
+ // Otherwise, close the modal (handles other modals' backdrop clicks and all dismiss buttons)
+ modalToClose.classList.remove('active');
+
+ // Reset forms only when closing the respective modal
+ if (modalToClose.id === 'editModal') {
+ // Optional: Add any edit form reset logic here if needed
+ console.log('Edit modal closed, reset logic (if any) can go here.');
+ } else if (modalToClose.id === 'addWarrantyModal') {
+ // This reset will now only trigger if closed via dismiss button
+ resetAddWarrantyWizard();
+ }
+ // Add similar reset logic for other modals like deleteModal if needed
+ // else if (modalToClose.id === 'deleteModal') { ... }
+ }
+ }
+ });
+ });
+
+ // Prevent modal content clicks from closing the modal
+ document.querySelectorAll('.modal').forEach(modal => {
+ modal.addEventListener('click', (e) => {
+ e.stopPropagation();
+ });
+ });
+
+ // Filter event listeners
+ const searchInput = document.getElementById('searchWarranties');
+ const clearSearchBtn = document.getElementById('clearSearch');
+ const statusFilter = document.getElementById('statusFilter');
+ const tagFilter = document.getElementById('tagFilter');
+ const sortBySelect = document.getElementById('sortBy');
+ const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
+ const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select
+
+ if (searchInput) {
+ // Debounce logic: only apply filters after user stops typing for 300ms
+ let searchDebounceTimeout;
+ searchInput.addEventListener('input', () => {
+ currentFilters.search = searchInput.value.toLowerCase();
+ // Show/hide clear button based on search input
+ if (clearSearchBtn) {
+ clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';
+ }
+ // Add visual feedback class to search box when active
+ if (searchInput.value) {
+ searchInput.parentElement.classList.add('active-search');
+ } else {
+ searchInput.parentElement.classList.remove('active-search');
+ }
+ // Debounce applyFilters
+ if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);
+ searchDebounceTimeout = setTimeout(() => {
+ applyFilters();
+ saveFilterPreferences();
+ }, 300);
+ });
+ }
+
+ if (clearSearchBtn) {
+ clearSearchBtn.addEventListener('click', () => {
+ if (searchInput) {
+ searchInput.value = '';
+ if (window.store && window.store.updateFilter) window.store.updateFilter('search', '');
+ currentFilters.search = '';
+ clearSearchBtn.style.display = 'none';
+ searchInput.parentElement.classList.remove('active-search');
+ searchInput.focus();
+ applyFilters();
+ saveFilterPreferences();
+ }
+ });
+ }
+
+ if (statusFilter) {
+ statusFilter.addEventListener('change', () => {
+ if (window.store && window.store.updateFilter) window.store.updateFilter('status', statusFilter.value);
+ currentFilters.status = statusFilter.value;
+ applyFilters();
+ saveFilterPreferences();
+ });
+ }
+
+ if (tagFilter) {
+ tagFilter.addEventListener('change', () => {
+ if (window.store && window.store.updateFilter) window.store.updateFilter('tag', tagFilter.value);
+ currentFilters.tag = tagFilter.value;
+ applyFilters();
+ saveFilterPreferences();
+ });
+ }
+
+ if (vendorFilter) { // Added event listener for vendor filter
+ vendorFilter.addEventListener('change', () => {
+ if (window.store && window.store.updateFilter) window.store.updateFilter('vendor', vendorFilter.value);
+ currentFilters.vendor = vendorFilter.value;
+ applyFilters();
+ saveFilterPreferences();
+ });
+ }
+
+ if (warrantyTypeFilter) { // Added event listener for warranty type filter
+ warrantyTypeFilter.addEventListener('change', () => {
+ if (window.store && window.store.updateFilter) window.store.updateFilter('warranty_type', warrantyTypeFilter.value);
+ currentFilters.warranty_type = warrantyTypeFilter.value;
+ applyFilters();
+ saveFilterPreferences();
+ });
+ }
+
+ if (sortBySelect) {
+ sortBySelect.addEventListener('change', () => {
+ if (window.store && window.store.updateFilter) window.store.updateFilter('sortBy', sortBySelect.value);
+ currentFilters.sortBy = sortBySelect.value;
+ applyFilters();
+ saveFilterPreferences();
+ });
+ }
+
+ // Note: Clear Filters button handler is in index.html inline script to close popover
+
+ // View switcher event listeners
+ const gridViewBtn = document.getElementById('gridViewBtn');
+ const listViewBtn = document.getElementById('listViewBtn');
+ const tableViewBtn = document.getElementById('tableViewBtn');
+
+ if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));
+ if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));
+ if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));
+
+ // Export button event listener
+ const exportBtn = document.getElementById('exportBtn');
+ if (exportBtn) exportBtn.addEventListener('click', exportWarranties);
+
+ // Import button event listener
+ if (importBtn && csvFileInput) {
+ importBtn.addEventListener('click', () => {
+ csvFileInput.click(); // Trigger hidden file input
+ });
+ csvFileInput.addEventListener('change', (event) => {
+ if (event.target.files && event.target.files.length > 0) {
+ handleImport(event.target.files[0]);
+ }
+ });
+ }
+
+ // Refresh button
+ const refreshBtn = document.getElementById('refreshBtn');
+ if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
+
+ // Warranty Type dropdown handlers for custom option
+ if (warrantyTypeInput && warrantyTypeCustomInput) {
+ warrantyTypeInput.addEventListener('change', () => {
+ if (warrantyTypeInput.value === 'other') {
+ warrantyTypeCustomInput.style.display = 'block';
+ warrantyTypeCustomInput.focus();
+ } else {
+ warrantyTypeCustomInput.style.display = 'none';
+ warrantyTypeCustomInput.value = '';
+ }
+ updateSummary(); // Update summary when warranty type changes
+ });
+
+ // Also update summary when custom warranty type changes
+ warrantyTypeCustomInput.addEventListener('input', updateSummary);
+ }
+
+ if (editWarrantyTypeInput && editWarrantyTypeCustomInput) {
+ editWarrantyTypeInput.addEventListener('change', () => {
+ if (editWarrantyTypeInput.value === 'other') {
+ editWarrantyTypeCustomInput.style.display = 'block';
+ editWarrantyTypeCustomInput.focus();
+ } else {
+ editWarrantyTypeCustomInput.style.display = 'none';
+ editWarrantyTypeCustomInput.value = '';
+ }
+ });
+ }
+
+ // Save warranty changes
+ const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
+ if (saveWarrantyBtn) {
+ let functionToAttachOnClick = saveWarranty; // Default to the original saveWarranty from script.js
+
+ // Check if the observer setup function from status.js is available
+ if (typeof window.setupSaveWarrantyObserver === 'function') {
+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was FOUND. Attempting to wrap local saveWarranty function.');
+ try {
+ // Call the observer setup function, passing it the original saveWarranty from this script.
+ // The observer setup function is expected to return a new function that wraps the original.
+ functionToAttachOnClick = window.setupSaveWarrantyObserver(saveWarranty);
+
+ // Optional: A flag to let status.js know that script.js has handled the wrapping.
+ // This can be useful if status.js has any fallback/polling logic to prevent double-wrapping.
+ window.saveWarrantyObserverAttachedByScriptJS = true;
+ console.log('[script.js] Local saveWarranty function has been successfully WRAPPED by the observer from status.js.');
+ } catch (e) {
+ console.error('[script.js] An error occurred while trying to wrap saveWarranty with the observer from status.js:', e);
+ // If an error occurs during wrapping, functionToAttachOnClick will remain the original saveWarranty.
+ }
+ } else {
+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was NOT FOUND. Using the original saveWarranty function for the button.');
+ }
+
+ // Add the event listener using the (potentially) wrapped function.
+ saveWarrantyBtn.addEventListener('click', () => {
+ console.log('[script.js] Save button (saveWarrantyBtn) clicked. Invoking the determined save function (functionToAttachOnClick).');
+ if (typeof functionToAttachOnClick === 'function') {
+ functionToAttachOnClick(); // Execute the determined save function
+ } else {
+ console.error('[script.js] CRITICAL: functionToAttachOnClick is not a function when save button was clicked!');
+ }
+ });
+
+ } else {
+ console.warn('[script.js] saveWarrantyBtn DOM element not found. Cannot attach click listener.');
+ }
+
+ // Confirm delete button
+ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
+ if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
+
+ // Confirm archive button
+ const confirmArchiveBtn = document.getElementById('confirmArchiveBtn');
+ if (confirmArchiveBtn) confirmArchiveBtn.addEventListener('click', confirmArchive);
+
+ // Load saved view preference
+ // loadViewPreference(); // Disabled: now called after authStateReady
+}
+
+// Function to show loading spinner
+function showLoadingSpinner() {
+ if (loadingContainer) {
+ loadingContainer.style.display = 'flex';
+ }
+}
+
+// Function to hide loading spinner
+function hideLoadingSpinner() {
+ if (loadingContainer) {
+ loadingContainer.style.display = 'none';
+ }
+}
+
+// Paperless upload loading functions
+function showPaperlessUploadLoading(documentType) {
+ // Create or show the Paperless upload overlay
+ let overlay = document.getElementById('paperless-upload-overlay');
+ if (!overlay) {
+ overlay = document.createElement('div');
+ overlay.id = 'paperless-upload-overlay';
+ overlay.innerHTML = `
+ <div class="paperless-upload-modal">
+ <div class="paperless-upload-content">
+ <div class="paperless-upload-spinner"></div>
+ <h3>Uploading to Paperless-ngx</h3>
+ <p id="paperless-upload-status">Uploading document...</p>
+ <div class="paperless-upload-progress">
+ <div class="paperless-upload-progress-bar" id="paperless-progress-bar"></div>
+ </div>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ // Add CSS styles
+ const style = document.createElement('style');
+ style.textContent = `
+ #paperless-upload-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.7);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 10000;
+ backdrop-filter: blur(2px);
+ }
+
+ .paperless-upload-modal {
+ background: var(--card-bg, #fff);
+ border-radius: 12px;
+ padding: 2rem;
+ max-width: 400px;
+ width: 90%;
+ text-align: center;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
+ border: 1px solid var(--border-color, #ddd);
+ }
+
+ .paperless-upload-content h3 {
+ margin: 1rem 0 0.5rem 0;
+ color: var(--text-color, #333);
+ font-size: 1.2rem;
+ }
+
+ .paperless-upload-content p {
+ margin: 0.5rem 0 1.5rem 0;
+ color: var(--text-secondary, #666);
+ font-size: 0.9rem;
+ }
+
+ .paperless-upload-spinner {
+ width: 40px;
+ height: 40px;
+ border: 4px solid var(--border-color, #ddd);
+ border-top: 4px solid var(--primary-color, #007bff);
+ border-radius: 50%;
+ animation: paperless-spin 1s linear infinite;
+ margin: 0 auto 1rem auto;
+ }
+
+ @keyframes paperless-spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+
+ .paperless-upload-progress {
+ width: 100%;
+ height: 6px;
+ background: var(--border-color, #ddd);
+ border-radius: 3px;
+ overflow: hidden;
+ margin-top: 1rem;
+ }
+
+ .paperless-upload-progress-bar {
+ height: 100%;
+ background: linear-gradient(90deg, var(--primary-color, #007bff), var(--success-color, #28a745));
+ border-radius: 3px;
+ width: 0%;
+ transition: width 0.3s ease;
+ animation: paperless-progress-pulse 2s ease-in-out infinite;
+ }
+
+ @keyframes paperless-progress-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.7; }
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ overlay.style.display = 'flex';
+
+ // Update status text
+ const statusEl = document.getElementById('paperless-upload-status');
+ if (statusEl) {
+ statusEl.textContent = `Uploading ${documentType} to Paperless-ngx...`;
+ }
+
+ // Animate progress bar
+ const progressBar = document.getElementById('paperless-progress-bar');
+ if (progressBar) {
+ progressBar.style.width = '30%';
+ setTimeout(() => {
+ progressBar.style.width = '60%';
+ }, 1000);
+ setTimeout(() => {
+ progressBar.style.width = '80%';
+ }, 2000);
+ }
+}
+
+function updatePaperlessUploadStatus(message, isProcessing = false) {
+ const statusEl = document.getElementById('paperless-upload-status');
+ const progressBar = document.getElementById('paperless-progress-bar');
+
+ if (statusEl) {
+ statusEl.textContent = message;
+ }
+
+ if (isProcessing && progressBar) {
+ progressBar.style.width = '90%';
+ }
+}
+
+function hidePaperlessUploadLoading() {
+ const overlay = document.getElementById('paperless-upload-overlay');
+ if (overlay) {
+ // Complete the progress bar first
+ const progressBar = document.getElementById('paperless-progress-bar');
+ if (progressBar) {
+ progressBar.style.width = '100%';
+ }
+
+ // Hide after a short delay to show completion
+ setTimeout(() => {
+ overlay.style.display = 'none';
+ // Reset progress bar for next use
+ if (progressBar) {
+ progressBar.style.width = '0%';
+ }
+ }, 500);
+ }
+}
+
+// Delete warranty function
+function deleteWarranty() {
+ if (!currentWarrantyId) {
+ showToast(window.t('messages.no_warranty_selected_for_deletion'), 'error');
+ return;
+ }
+
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ showToast('Authentication required', 'error');
+ return;
+ }
+
+ showLoadingSpinner();
+
+ fetch(`/api/warranties/${currentWarrantyId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to delete warranty');
+ }
+ return response.json();
+ })
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty deleted successfully', 'success');
+ closeModals();
+
+ // --- BEGIN FIX: Update UI immediately ---
+ // Remove the deleted warranty from the global array
+ const deletedId = currentWarrantyId; // Store ID before resetting
+ if (window.store && window.store.setWarranties) {
+ window.store.setWarranties(warranties.filter(warranty => warranty.id !== deletedId));
+ }
+ warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : warranties;
+ currentWarrantyId = null; // Reset current ID
+
+ // Re-render the list using the updated local array
+ applyFilters();
+ // --- END FIX ---
+ })
+ .catch(error => {
+ hideLoadingSpinner();
+ console.error('Error deleting warranty:', error);
+ showToast('Failed to delete warranty', 'error');
+ });
+}
+
+// Save warranty updates
+function saveWarranty() {
+ console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");
+ if (!currentWarrantyId) {
+ showToast(window.t('messages.no_warranty_selected_for_update'), 'error');
+ return;
+ }
+
+ // --- Get form values ---
+ const productName = document.getElementById('editProductName').value.trim();
+ const purchaseDate = document.getElementById('editPurchaseDate').value;
+ const isLifetime = document.getElementById('editIsLifetime').checked;
+ const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
+ // Get new duration values
+ const years = parseInt(document.getElementById('editWarrantyDurationYears').value || 0);
+ const months = parseInt(document.getElementById('editWarrantyDurationMonths').value || 0);
+ const days = parseInt(document.getElementById('editWarrantyDurationDays').value || 0);
+ const exactDate = editExactExpirationDateInput ? editExactExpirationDateInput.value : '';
+
+ // Basic validation
+ if (!productName) {
+ showToast(window.t('messages.product_name_required'), 'error');
+ return;
+ }
+
+ if (!purchaseDate) {
+ showToast(window.t('messages.purchase_date_required'), 'error');
+ return;
+ }
+
+ // --- Updated Validation ---
+ if (!isLifetime) {
+ if (isDurationMethod) {
+ // Validate duration fields
+ if (years === 0 && months === 0 && days === 0) {
+ showToast(window.t('messages.warranty_duration_required'), 'error');
+ // Optional: focus the years input again
+ const yearsInput = document.getElementById('editWarrantyDurationYears');
+ if (yearsInput) { // Check if element exists
+ yearsInput.focus();
+ // Add invalid class to container or inputs
+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.add('invalid-duration');
+ }
+ return;
+ }
+ } else {
+ // Validate exact expiration date
+ if (!exactDate) {
+ showToast(window.t('messages.exact_expiration_date_required'), 'error');
+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
+ return;
+ }
+
+ // Validate that expiration date is in the future relative to purchase date
+ if (purchaseDate && exactDate <= purchaseDate) {
+ showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
+ return;
+ }
+ }
+ }
+
+ // Remove invalid duration class if validation passes
+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');
+ // --- End Updated Validation ---
+
+ // Create form data
+ const formData = new FormData();
+ formData.append('product_name', productName);
+ formData.append('purchase_date', purchaseDate);
+
+ // Optional fields
+ let productUrl = document.getElementById('editProductUrl').value.trim();
+ if (productUrl) {
+ if (!productUrl.startsWith('http://') && !productUrl.startsWith('https://')) {
+ productUrl = 'https://' + productUrl;
+ }
+ formData.append('product_url', productUrl);
+ }
+
+ const purchasePrice = document.getElementById('editPurchasePrice').value;
+ const currency = document.getElementById('editCurrency').value;
+ if (purchasePrice) {
+ formData.append('purchase_price', purchasePrice);
+ }
+ if (currency) {
+ formData.append('currency', currency);
+ }
+
+ // Serial numbers (use correct name 'serial_numbers[]')
+ const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');
+ // Clear existing before appending
+ formData.delete('serial_numbers[]');
+ serialInputs.forEach(input => {
+ if (input.value.trim()) {
+ formData.append('serial_numbers[]', input.value.trim()); // Use []
+ }
+ });
+
+ // Tags - add tag IDs as JSON string
+ if (editSelectedTags && editSelectedTags.length > 0) {
+ const tagIds = editSelectedTags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ } else {
+ // Send empty array to clear tags
+ formData.append('tag_ids', JSON.stringify([]));
+ }
+
+ // Add URL fields for documents (with null checks)
+ const editInvoiceUrlField = document.getElementById('editInvoiceUrl');
+ formData.append('invoice_url', editInvoiceUrlField ? editInvoiceUrlField.value || '' : '');
+
+ const editManualUrlField = document.getElementById('editManualUrl');
+ formData.append('manual_url', editManualUrlField ? editManualUrlField.value || '' : '');
+
+ const editOtherDocumentUrlField = document.getElementById('editOtherDocumentUrl');
+ formData.append('other_document_url', editOtherDocumentUrlField ? editOtherDocumentUrlField.value || '' : '');
+
+ // Files
+ const invoiceFile = document.getElementById('editInvoice').files[0];
+ if (invoiceFile) {
+ formData.append('invoice', invoiceFile);
+ }
+
+ const manualFile = document.getElementById('editManual').files[0];
+ if (manualFile) {
+ formData.append('manual', manualFile);
+ }
+
+ const otherDocumentFile = document.getElementById('editOtherDocument').files[0];
+ if (otherDocumentFile) {
+ formData.append('other_document', otherDocumentFile);
+ }
+
+ // Product photo
+ const productPhotoFile = document.getElementById('editProductPhoto').files[0];
+ if (productPhotoFile) {
+ formData.append('product_photo', productPhotoFile);
+ }
+
+ // Document deletion flags
+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
+ if (deleteInvoiceBtn && deleteInvoiceBtn.dataset.delete === 'true') {
+ formData.append('delete_invoice', 'true');
+ }
+ const deleteManualBtn = document.getElementById('deleteManualBtn');
+ if (deleteManualBtn && deleteManualBtn.dataset.delete === 'true') {
+ formData.append('delete_manual', 'true');
+ }
+ const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
+ if (deleteOtherDocumentBtn && deleteOtherDocumentBtn.dataset.delete === 'true') {
+ formData.append('delete_other_document', 'true');
+ }
+ const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
+ if (deleteProductPhotoBtn && deleteProductPhotoBtn.dataset.delete === 'true') {
+ formData.append('delete_product_photo', 'true');
+ }
+
+ // --- Append is_lifetime and duration components ---
+ formData.append('is_lifetime', isLifetime.toString());
+ if (!isLifetime) {
+ if (isDurationMethod) {
+ formData.append('warranty_duration_years', years);
+ formData.append('warranty_duration_months', months);
+ formData.append('warranty_duration_days', days);
+ } else {
+ // Using exact date method
+ formData.append('exact_expiration_date', exactDate);
+ // Ensure duration fields are 0 when using exact date
+ formData.append('warranty_duration_years', 0);
+ formData.append('warranty_duration_months', 0);
+ formData.append('warranty_duration_days', 0);
+ }
+ } else {
+ // Ensure duration is 0 if lifetime
+ formData.append('warranty_duration_years', 0);
+ formData.append('warranty_duration_months', 0);
+ formData.append('warranty_duration_days', 0);
+ }
+ // Add notes
+ const notes = document.getElementById('editNotes').value;
+ if (notes && notes.trim() !== '') {
+ formData.append('notes', notes);
+ } else {
+ // Explicitly clear notes if empty
+ formData.append('notes', '');
+ }
+
+ // Add model number to form data (optional)
+ const editModelNumber = document.getElementById('editModelNumber');
+ if (editModelNumber && editModelNumber.value.trim() !== '') {
+ formData.append('model_number', editModelNumber.value.trim());
+ } else {
+ // Explicitly clear if empty
+ formData.append('model_number', '');
+ }
+
+ // Add vendor/retailer to form data
+ const editVendorInput = document.getElementById('editVendor'); // Use the correct ID
+ formData.append('vendor', editVendorInput ? editVendorInput.value.trim() : ''); // Use the correct variable
+
+ // Add warranty type to form data - handle custom type
+ const editWarrantyTypeInput = document.getElementById('editWarrantyType');
+ const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
+ let warrantyTypeValue = '';
+ if (editWarrantyTypeInput) {
+ if (editWarrantyTypeInput.value === 'other' && editWarrantyTypeCustomInput && editWarrantyTypeCustomInput.value.trim()) {
+ warrantyTypeValue = editWarrantyTypeCustomInput.value.trim();
+ } else {
+ warrantyTypeValue = editWarrantyTypeInput.value.trim();
+ }
+ }
+ formData.append('warranty_type', warrantyTypeValue);
+
+ // Add selected Paperless documents for edit form
+ const selectedEditPaperlessProductPhoto = document.getElementById('selectedEditPaperlessProductPhoto');
+ const selectedEditPaperlessInvoice = document.getElementById('selectedEditPaperlessInvoice');
+ const selectedEditPaperlessManual = document.getElementById('selectedEditPaperlessManual');
+ const selectedEditPaperlessOtherDocument = document.getElementById('selectedEditPaperlessOtherDocument');
+
+ if (selectedEditPaperlessProductPhoto && selectedEditPaperlessProductPhoto.value) {
+ formData.append('paperless_photo_id', selectedEditPaperlessProductPhoto.value);
+ }
+ if (selectedEditPaperlessInvoice && selectedEditPaperlessInvoice.value) {
+ formData.append('paperless_invoice_id', selectedEditPaperlessInvoice.value);
+ }
+ if (selectedEditPaperlessManual && selectedEditPaperlessManual.value) {
+ formData.append('paperless_manual_id', selectedEditPaperlessManual.value);
+ }
+ if (selectedEditPaperlessOtherDocument && selectedEditPaperlessOtherDocument.value) {
+ formData.append('paperless_other_id', selectedEditPaperlessOtherDocument.value);
+ }
+
+ // DEBUG: Log what we're sending to the backend
+ console.log('[DEBUG saveWarranty] Form data being sent:');
+ console.log('[DEBUG saveWarranty] isLifetime:', isLifetime);
+ console.log('[DEBUG saveWarranty] isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG saveWarranty] exactDate:', exactDate);
+ console.log('[DEBUG saveWarranty] years/months/days:', years, months, days);
+
+ // Log all form data entries
+ for (let [key, value] of formData.entries()) {
+ console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);
+ }
+
+ // Get auth token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ showToast('Authentication required', 'error');
+ return;
+ }
+
+ showLoadingSpinner();
+
+ // Process Paperless-ngx uploads if enabled
+ processEditPaperlessNgxUploads(formData)
+ .then(paperlessUploads => {
+ // Add Paperless-ngx document IDs to form data
+ Object.keys(paperlessUploads).forEach(key => {
+ formData.append(key, paperlessUploads[key]);
+ });
+
+ // Send request
+ return fetch(`/api/warranties/${currentWarrantyId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+ })
+ .then(response => {
+ if (!response.ok) {
+ return response.json().then(data => {
+ throw new Error(data.error || 'Failed to update warranty');
+ });
+ }
+ return response.json();
+ })
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty updated successfully', 'success');
+ closeModals();
+
+ // Always reload from server to ensure we get the latest data including product photo paths
+ console.log('Reloading warranties after edit to ensure latest data including product photos');
+ loadWarranties(true).then(() => {
+ console.log('Warranties reloaded after editing warranty');
+ applyFilters();
+ // Load secure images for the updated cards - additional call to ensure they load
+ setTimeout(() => {
+ console.log('Loading secure images for updated warranty cards');
+ loadSecureImages();
+ }, 200); // Slightly longer delay to ensure everything is rendered
+
+ // Always close the notes modal if open, to ensure UI is in sync
+ const notesModal = document.getElementById('notesModal');
+ if (notesModal && notesModal.style.display === 'block') {
+ notesModal.style.display = 'none';
+ }
+
+ console.log('Warranty updated and reloaded from server');
+
+ // Auto-link any documents that were uploaded to Paperless-ngx
+ if ((invoiceFile || manualFile || otherDocumentFile) && currentWarrantyId) {
+ console.log('[Auto-Link] Starting automatic document linking after warranty update');
+
+ // Collect filename information for intelligent searching
+ const fileInfo = {};
+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;
+ if (manualFile) fileInfo.manual = manualFile.name;
+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;
+
+ setTimeout(() => {
+ autoLinkRecentDocuments(currentWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);
+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
+ }
+ }).catch(error => {
+ console.error('Error reloading warranties after edit:', error);
+ });
+ })
+ .catch(error => {
+ hideLoadingSpinner();
+ console.error('Error updating warranty:', error);
+ showToast(error.message || 'Failed to update warranty', 'error');
+ });
+}
+
+// Function to populate tag filter dropdown
+function populateTagFilter() {
+ const tagFilter = document.getElementById('tagFilter');
+ if (!tagFilter) return;
+
+ // Clear existing options (except "All Tags")
+ while (tagFilter.options.length > 1) {
+ tagFilter.remove(1);
+ }
+
+ // Create a Set to store unique tag names
+ const uniqueTags = new Set();
+
+ // Collect all unique tags from warranties
+ warranties.forEach(warranty => {
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ warranty.tags.forEach(tag => {
+ uniqueTags.add(JSON.stringify({id: tag.id, name: tag.name, color: tag.color}));
+ });
+ }
+ });
+
+ // Sort tags alphabetically by name
+ const sortedTags = Array.from(uniqueTags)
+ .map(tagJson => JSON.parse(tagJson))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ // Add options to the dropdown
+ // Add options to the dropdown
+ sortedTags.forEach(tag => {
+ const option = document.createElement('option');
+ option.value = tag.id;
+ option.textContent = tag.name; // Reverted to textContent
+ // Apply background color directly for now, acknowledging potential contrast issues
+ // option.style.backgroundColor = tag.color; // Removed to prevent individual option background colors
+ tagFilter.appendChild(option);
+ });
+}
+
+// Function to populate vendor filter dropdown
+function populateVendorFilter() {
+ const vendorFilterElement = document.getElementById('vendorFilter');
+ if (!vendorFilterElement) return;
+
+ // Clear existing options (except "All Vendors")
+ while (vendorFilterElement.options.length > 1) {
+ vendorFilterElement.remove(1);
+ }
+
+ // Create a Set to store unique vendor names (case-insensitive)
+ const uniqueVendors = new Set();
+
+ // Collect all unique, non-empty vendors from warranties
+ warranties.forEach(warranty => {
+ if (warranty.vendor && warranty.vendor.trim() !== '') {
+ uniqueVendors.add(warranty.vendor.trim().toLowerCase());
+ }
+ });
+
+ // Sort vendors alphabetically (after converting back to original case for display if needed, or just use lowercase)
+ // For simplicity, we'll sort the lowercase versions and display them as is.
+ // If original casing is important, a map could be used to store original values.
+ const sortedVendors = Array.from(uniqueVendors).sort((a, b) => a.localeCompare(b));
+
+ // Add options to the dropdown
+ sortedVendors.forEach(vendor => {
+ const option = document.createElement('option');
+ option.value = vendor; // Use lowercase for value consistency
+ // Capitalize first letter for display
+ option.textContent = vendor.charAt(0).toUpperCase() + vendor.slice(1);
+ vendorFilterElement.appendChild(option);
+ });
+}
+
+// Function to populate warranty type filter dropdown
+function populateWarrantyTypeFilter() {
+ const warrantyTypeFilterElement = document.getElementById('warrantyTypeFilter');
+ if (!warrantyTypeFilterElement) return;
+
+ // Clear existing options (except "All Types")
+ while (warrantyTypeFilterElement.options.length > 1) {
+ warrantyTypeFilterElement.remove(1);
+ }
+
+ // Create a Set to store unique warranty types (case-insensitive)
+ const uniqueWarrantyTypes = new Set();
+
+ // Collect all unique, non-empty warranty types from warranties
+ warranties.forEach(warranty => {
+ if (warranty.warranty_type && warranty.warranty_type.trim() !== '') {
+ uniqueWarrantyTypes.add(warranty.warranty_type.trim().toLowerCase());
+ }
+ });
+
+ // Sort warranty types alphabetically
+ const sortedWarrantyTypes = Array.from(uniqueWarrantyTypes).sort((a, b) => a.localeCompare(b));
+
+ // Add options to the dropdown
+ sortedWarrantyTypes.forEach(warrantyType => {
+ const option = document.createElement('option');
+ option.value = warrantyType; // Use lowercase for value consistency
+ // Capitalize first letter for display
+ option.textContent = warrantyType.charAt(0).toUpperCase() + warrantyType.slice(1);
+ warrantyTypeFilterElement.appendChild(option);
+ });
+}
+
+// --- Updated Function ---
+function handleLifetimeChange(event) {
+ const checkbox = event ? event.target : isLifetimeCheckbox;
+ const durationFields = warrantyDurationFields; // Use new container ID
+ const yearsInput = warrantyDurationYearsInput;
+ const monthsInput = warrantyDurationMonthsInput;
+ const daysInput = warrantyDurationDaysInput;
+ const warrantyEntryMethod = document.getElementById('warrantyEntryMethod');
+
+ if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
+ console.error("Lifetime or duration elements not found in add form");
+ return;
+ }
+
+ if (checkbox.checked) {
+ // Hide warranty method selection and both input methods
+ if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'none';
+ durationFields.style.display = 'none';
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+
+ // Clear and make fields not required
+ yearsInput.required = false;
+ monthsInput.required = false;
+ daysInput.required = false;
+ yearsInput.value = '';
+ monthsInput.value = '';
+ daysInput.value = '';
+ if (exactExpirationDateInput) exactExpirationDateInput.value = '';
+ } else {
+ // Show warranty method selection
+ if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'block';
+
+ // Call method change handler to show appropriate fields
+ handleWarrantyMethodChange();
+ }
+}
+
+// --- Updated Function ---
+function handleEditLifetimeChange(event) {
+ const checkbox = event ? event.target : editIsLifetimeCheckbox;
+ const durationFields = editWarrantyDurationFields; // Use new container ID
+ const yearsInput = editWarrantyDurationYearsInput;
+ const monthsInput = editWarrantyDurationMonthsInput;
+ const daysInput = editWarrantyDurationDaysInput;
+ const editWarrantyEntryMethod = document.getElementById('editWarrantyEntryMethod');
+
+ if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
+ console.error("Lifetime or duration elements not found in edit form");
+ return;
+ }
+
+ if (checkbox.checked) {
+ // Hide warranty method selection and both input methods
+ if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'none';
+ durationFields.style.display = 'none';
+ if (editExactExpirationField) editExactExpirationField.style.display = 'none';
+
+ // Clear and make fields not required
+ yearsInput.required = false;
+ monthsInput.required = false;
+ daysInput.required = false;
+ yearsInput.value = '';
+ monthsInput.value = '';
+ daysInput.value = '';
+ if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
+ } else {
+ // Show warranty method selection
+ if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'block';
+
+ // Call method change handler to show appropriate fields
+ handleEditWarrantyMethodChange();
+ }
+}
+
+// --- Add this function to reset the wizard ---
+function resetAddWarrantyWizard() {
+ console.log('Resetting Add Warranty Wizard...');
+ // Reset the form fields
+ if (warrantyForm) {
+ warrantyForm.reset();
+
+ // Explicitly set storage options to 'local'
+ const storageTypes = ['invoice', 'manual'];
+ storageTypes.forEach(type => {
+ const localRadio = document.querySelector(`input[name="${type}Storage"][value="local"]`);
+ if (localRadio) {
+ localRadio.checked = true;
+ }
+ });
+ }
+
+ // Reset serial numbers container (remove all but the first input structure)
+ if (serialNumbersContainer) {
+ serialNumbersContainer.innerHTML = ''; // Clear it
+ addSerialNumberInput(); // Add the initial input back
+ }
+
+ // Reset file input displays
+ if (fileName) fileName.textContent = '';
+ if (manualFileName) manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+
+ // Clear Paperless document selections (only for invoice and manual)
+ clearPaperlessSelection('invoice');
+ clearPaperlessSelection('manual');
+
+ // Reset selected tags
+ selectedTags = [];
+ console.log('Resetting Add Warranty Wizard...');
+
+ // No need to reset the form again as we already did it above
+
+ // Reset serial numbers container (remove all but the first input structure)
+ if (serialNumbersContainer) {
+ serialNumbersContainer.innerHTML = ''; // Clear it
+ addSerialNumberInput(); // Add the initial input back
+ }
+
+ // Reset file input displays
+ if (fileName) fileName.textContent = '';
+ if (manualFileName) manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+
+ // Reset selected tags
+ selectedTags = [];
+ renderSelectedTags(); // Update the display
+
+ // Reset tabs to the first one
+ // Use the globally defined tabContents if available
+ const tabs = addWarrantyModal?.querySelectorAll('.form-tab');
+ const contents = addWarrantyModal?.querySelectorAll('.tab-content');
+ if (tabs && contents && tabs.length > 0 && contents.length > 0) {
+ currentTabIndex = 0;
+ switchToTab(0); // Use the existing function to switch
+ } else {
+ console.warn("Could not find tabs/contents inside addWarrantyModal to reset.");
+ }
+
+ // Clear any validation states
+ addWarrantyModal?.querySelectorAll('.invalid').forEach(el => el.classList.remove('invalid'));
+ addWarrantyModal?.querySelectorAll('.validation-message').forEach(el => el.remove());
+
+ // Reset lifetime checkbox state if needed (ensure handler runs)
+ if (isLifetimeCheckbox) {
+ isLifetimeCheckbox.checked = false; // Explicitly uncheck
+ handleLifetimeChange({ target: isLifetimeCheckbox }); // Trigger handler to reset visibility/required state
+ }
+}
+
+// --- Modify setupUIEventListeners or add this within DOMContentLoaded ---
+function setupModalTriggers() {
+ // Show Add Warranty Modal
+ if (showAddWarrantyBtn && addWarrantyModal) {
+ showAddWarrantyBtn.addEventListener('click', () => {
+ resetAddWarrantyWizard(); // Reset before showing
+ addWarrantyModal.classList.add('active');
+ initFormTabs(); // Initialize tabs only when modal is shown
+ switchToTab(0); // Ensure the first tab content is displayed correctly after reset
+
+ // Set currency dropdown to user's preferred currency after form reset
+ const preferredCurrencyCode = getCurrencyCode();
+ if (currencySelect && preferredCurrencyCode) {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[Modal Open] Set currency dropdown to user preference: ${preferredCurrencyCode}`);
+ }
+
+ // Update currency symbols and positioning for the add form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const addPriceInput = document.getElementById('purchasePrice');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ if (addPriceInput && addCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = addPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ addPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ addPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
+ });
+ }
+
+ // Hide Add Warranty Modal (using existing close logic)
+ if (addWarrantyModal) {
+ // Close button inside modal
+ const closeBtn = addWarrantyModal.querySelector('.close-btn');
+ if (closeBtn) {
+ closeBtn.addEventListener('click', () => {
+ addWarrantyModal.classList.remove('active');
+ resetAddWarrantyWizard(); // Reset on close
+ });
+ }
+ // REMOVED: Backdrop click listener
+ /*
+ addWarrantyModal.addEventListener('click', (e) => {
+ if (e.target === addWarrantyModal) {
+ addWarrantyModal.classList.remove('active');
+ resetAddWarrantyWizard(); // Reset on close
+ }
+ });
+ */
+ // Optional: Cancel button in footer if you add one
+ // ... (cancel button logic remains unchanged)
+ }
+
+ // --- Edit Modal Triggers (Keep existing logic) ---
+ // Close edit/delete modals when clicking outside or on close button
+ document.querySelectorAll('#editModal, #deleteModal, #archiveModal, [data-dismiss="modal"]').forEach(element => {
+ element.addEventListener('click', (e) => {
+ // Check if the click is on the backdrop itself OR a dismiss button
+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {
+ // Find the closest modal backdrop to the element clicked
+ const modalToClose = e.target.closest('.modal-backdrop');
+ if (modalToClose) {
+ // *** ADD CHECK: Do NOT close addWarrantyModal or editModal via this general listener for backdrop clicks ***
+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal') && e.target === modalToClose) {
+ return; // Ignore backdrop clicks for the add and edit modals here
+ }
+ // *** END ADD CHECK ***
+
+ modalToClose.classList.remove('active');
+ // Reset edit form state if closing edit modal
+ if (modalToClose.id === 'editModal') {
+ // Optional: Add any edit form reset logic here if needed
+ }
+ }
+ }
+ });
+ });
+
+ // Prevent modal content clicks from closing the modal (Keep for all modals)
+ document.querySelectorAll('.modal').forEach(modal => {
+ modal.addEventListener('click', (e) => {
+ e.stopPropagation();
+ });
+ });
+}
+
+// --- CSV Import Functionality ---
+
+async function handleImport(file) {
+ if (!file) {
+ showToast('No file selected.', 'warning');
+ return;
+ }
+
+ if (!file.name.toLowerCase().endsWith('.csv')) {
+ showToast('Invalid file type. Please select a .csv file.', 'error');
+ return;
+ }
+
+ // Show loading indicator
+ showLoadingSpinner();
+
+ const formData = new FormData();
+ formData.append('csv_file', file);
+
+ try {
+ // const token = localStorage.getItem('token'); // Incorrect key
+ const token = localStorage.getItem('auth_token'); // Correct key used elsewhere
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ hideLoadingSpinner();
+ // Maybe redirect to login: window.location.href = '/login.html';
+ return;
+ }
+
+ const response = await fetch('/api/warranties/import', {
+ method: 'POST',
+ headers: {
+ // Content-Type is automatically set by browser when using FormData
+ 'Authorization': `Bearer ${token}`
+ },
+ body: formData
+ });
+
+ hideLoadingSpinner();
+ const result = await response.json();
+
+ if (response.ok) {
+ const { success_count, failure_count, errors } = result;
+ let message = `${success_count} warranties imported successfully.`;
+ if (failure_count > 0) {
+ message += ` ${failure_count} rows failed.`;
+ // Log detailed errors to the console for now
+ console.warn('Import errors:', errors);
+ // Consider showing errors in a modal or separate report later
+ }
+ showToast(message, 'success');
+
+ // ***** FIX: Reload the tags list *****
+ console.log("Import successful, reloading tags...");
+ await loadTags(true); // Fetch the updated list of all tags
+ // ***** END FIX *****
+
+ // Add a small delay to ensure backend has processed the data
+ await new Promise(resolve => setTimeout(resolve, 500));
+
+ // Await the warranties load to ensure UI is updated
+ await loadWarranties(true);
+
+ // Force a UI refresh by reapplying filters
+ applyFilters();
+ } else {
+ showToast(`Import failed: ${result.error || 'Unknown error'}`, 'error');
+ if (result.errors) {
+ console.error('Detailed import errors:', result.errors);
+ }
+ }
+
+ } catch (error) {
+ hideLoadingSpinner();
+ console.error('Error during file import:', error);
+ showToast('An error occurred during import. Check console for details.', 'error');
+ } finally {
+ // Reset the file input so the user can select the same file again if needed
+ if (csvFileInput) {
+ csvFileInput.value = '';
+ }
+ }
+}
+
+// --- End CSV Import Functionality ---
+
+// --- Add Storage Event Listener for Real-time Sync ---
+window.addEventListener('storage', (event) => {
+ const currentPrefix = getPreferenceKeyPrefix(); // Re-calculate prefix
+ const viewKeysToWatch = [
+ `${currentPrefix}defaultView`,
+ 'viewPreference',
+ `${currentPrefix}warrantyView`,
+ // Add `${currentPrefix}viewPreference` if still used/relevant
+ `${currentPrefix}viewPreference`
+ ];
+
+ // Check for view preference changes
+ if (viewKeysToWatch.includes(event.key) && event.newValue) {
+ console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);
+ // Check if the new value is different from the current view to avoid loops
+ if (event.newValue !== currentView) {
+ // Ensure view buttons exist before switching (we're on the main page)
+ if (gridViewBtn || listViewBtn || tableViewBtn) {
+ switchView(event.newValue, false); // Apply change, don't re-save to API
+ }
+ } else {
+ console.log('Storage event value matches current view, ignoring.');
+ }
+ }
+
+ // --- Added: Check for date format changes ---
+ if (event.key === 'dateFormat' && event.newValue) {
+ console.log(`Storage event detected for dateFormat. New value: ${event.newValue}`);
+ // Re-apply filters to re-render warranties with the new date format
+ if (warrantiesList) { // Only apply if the warranty list exists on the page
+ applyFilters();
+ showToast('Date format updated.', 'info'); // Optional: Notify user
+ }
+ }
+ // --- End Added Check ---
+
+ // --- Added: Check for currency symbol changes ---
+ if (event.key === `${currentPrefix}currencySymbol` && event.newValue) {
+ console.log(`Storage event detected for ${currentPrefix}currencySymbol. New value: ${event.newValue}`);
+ if (warrantiesList) { // Only apply if on the main page
+ updateCurrencySymbols(); // Update symbols outside cards (e.g., in forms if they exist)
+ applyFilters(); // Re-render cards to update symbols inside them
+ showToast('Currency symbol updated.', 'info'); // Optional: Notify user
+ }
+ }
+ // --- End Added Check ---
+});
+// --- End Storage Event Listener ---
+
+// Add modal HTML to the end of the body if not present (componentized)
+if (!document.getElementById('notesModal')) {
+ if (window.components && window.components.notes && window.components.notes.ensureNotesModal) {
+ window.components.notes.ensureNotesModal();
+ } else {
+ // Fallback: Build via DOM API
+ const notesModal = document.createElement('div');
+ notesModal.id = 'notesModal';
+ notesModal.className = 'modal-backdrop';
+ const modal = document.createElement('div'); modal.className = 'modal'; modal.style.maxWidth = '500px';
+ const header = document.createElement('div'); header.className = 'modal-header';
+ const title = document.createElement('h3'); title.className = 'modal-title'; title.textContent = 'Warranty Notes';
+ const close = document.createElement('button'); close.className = 'close-btn'; close.id = 'closeNotesModal'; close.textContent = '×';
+ header.appendChild(title); header.appendChild(close);
+ const body = document.createElement('div'); body.className = 'modal-body';
+ const content = document.createElement('div'); content.id = 'notesModalContent'; content.style.whiteSpace = 'pre-line';
+ const textarea = document.createElement('textarea'); textarea.id = 'notesModalTextarea'; textarea.style.display = 'none'; textarea.style.width = '100%'; textarea.style.minHeight = '100px';
+ body.appendChild(content); body.appendChild(textarea);
+ const footer = document.createElement('div'); footer.className = 'modal-footer'; footer.id = 'notesModalFooter';
+ const editBtn = document.createElement('button'); editBtn.className = 'btn btn-secondary'; editBtn.id = 'editNotesBtn'; editBtn.textContent = 'Edit Notes';
+ const editWBtn = document.createElement('button'); editWBtn.className = 'btn btn-info'; editWBtn.id = 'editWarrantyBtn'; editWBtn.textContent = 'Edit Warranty';
+ const saveBtn = document.createElement('button'); saveBtn.className = 'btn btn-primary'; saveBtn.id = 'saveNotesBtn'; saveBtn.style.display = 'none'; saveBtn.textContent = 'Save';
+ const cancelBtn = document.createElement('button'); cancelBtn.className = 'btn btn-danger'; cancelBtn.id = 'cancelEditNotesBtn'; cancelBtn.style.display = 'none'; cancelBtn.textContent = 'Cancel';
+ footer.appendChild(editBtn); footer.appendChild(editWBtn); footer.appendChild(saveBtn); footer.appendChild(cancelBtn);
+ modal.appendChild(header); modal.appendChild(body); modal.appendChild(footer);
+ notesModal.appendChild(modal); document.body.appendChild(notesModal);
+ document.getElementById('closeNotesModal').addEventListener('click', () => notesModal.classList.remove('active'));
+ }
+
+ // Add event listener for Edit Warranty button
+ document.getElementById('editWarrantyBtn').addEventListener('click', async () => {
+ // Find the current warranty data from the global array
+ const currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);
+ if (currentWarranty) {
+ console.log('[DEBUG] Edit Warranty button clicked, opening edit modal with warranty:', currentWarranty.id, 'notes:', currentWarranty.notes);
+ // Close the notes modal first
+ document.getElementById('notesModal').classList.remove('active');
+ // Open the edit modal with current data
+ await openEditModal(currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
+ });
+}
+
+// Add global to track which warranty is being edited in the notes modal
+let notesModalWarrantyId = null;
+let notesModalWarrantyObj = null;
+
+function showNotesModal(notes, warrantyOrId = null) {
+ const notesModal = document.getElementById('notesModal');
+ const notesModalContent = document.getElementById('notesModalContent');
+ const notesModalTextarea = document.getElementById('notesModalTextarea');
+ const editBtn = document.getElementById('editNotesBtn');
+ const saveBtn = document.getElementById('saveNotesBtn');
+ const cancelBtn = document.getElementById('cancelEditNotesBtn');
+
+ // Support both (notes, warrantyObj) and (notes, id) for backward compatibility
+ if (typeof warrantyOrId === 'object' && warrantyOrId !== null) {
+ notesModalWarrantyId = warrantyOrId.id;
+ notesModalWarrantyObj = warrantyOrId;
+ } else {
+ notesModalWarrantyId = warrantyOrId;
+ // Try to find the warranty object from global warranties array
+ notesModalWarrantyObj = warranties.find(w => w.id === notesModalWarrantyId) || null;
+ }
+
+ // Show note content, hide textarea and edit controls
+ notesModalContent.style.display = '';
+ notesModalContent.textContent = notes;
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+
+ // Edit button handler
+ editBtn.onclick = function() {
+ notesModalContent.style.display = 'none';
+ notesModalTextarea.style.display = '';
+ // Use the current content from the modal display instead of the stale notes parameter
+ notesModalTextarea.value = notesModalContent.textContent;
+ editBtn.style.display = 'none';
+ saveBtn.style.display = '';
+ cancelBtn.style.display = '';
+ notesModalTextarea.focus();
+ };
+ // Save button handler
+ saveBtn.onclick = async function() {
+ const newNote = notesModalTextarea.value.trim(); // Trim the note
+ if (!notesModalWarrantyId || !notesModalWarrantyObj) {
+ showToast('No warranty selected for note update', 'error');
+ return;
+ }
+
+ // Frontend check for invalid duration before attempting to save notes
+ if (!notesModalWarrantyObj.is_lifetime &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_years) || 0) === 0 &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_months) || 0) === 0 &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_days) || 0) === 0 &&
+ !notesModalWarrantyObj.expiration_date) {
+ showToast('Cannot save notes: The warranty has an invalid duration. Please edit the full warranty details to set a valid duration first.', 'error', 7000); // Longer toast duration
+ return; // Prevent API call
+ }
+
+ // Save note via API, sending all required fields
+ try {
+ showLoadingSpinner();
+ const token = localStorage.getItem('auth_token');
+ const formData = new FormData();
+ // --- Populate with existing data to avoid clearing fields ---
+ formData.append('product_name', notesModalWarrantyObj.product_name);
+ formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
+ formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
+ if (!notesModalWarrantyObj.is_lifetime) {
+ // Append duration components instead of warranty_years
+ formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
+ formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
+ formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
+
+ // If all duration fields are 0 but we have an expiration date, this was created with exact date method
+ const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
+ notesModalWarrantyObj.expiration_date;
+
+ if (isExactDateWarranty) {
+ // For exact date warranties, send the expiration date as exact_expiration_date
+ formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
+ }
+ }
+ if (notesModalWarrantyObj.product_url) {
+ formData.append('product_url', notesModalWarrantyObj.product_url);
+ }
+ if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) { // Check for null/undefined
+ formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
+ }
+ // Correctly append serial numbers
+ if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
+ notesModalWarrantyObj.serial_numbers.forEach(sn => {
+ // Ensure sn is treated as a string before trim, and append with [] for array
+ if (sn && String(sn).trim() !== '') {
+ formData.append('serial_numbers[]', String(sn).trim());
+ }
+ });
+ }
+ // If notesModalWarrantyObj.serial_numbers is empty or not an array,
+ // no 'serial_numbers[]' fields will be appended, which is typically interpreted as an empty list by backends.
+
+ if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
+ const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ }
+ // Send empty array if no tags exist or are provided
+ else {
+ formData.append('tag_ids', JSON.stringify([]));
+ }
+ // --- End Populate ---
+
+ formData.append('notes', newNote); // Append the potentially empty, trimmed note
+
+ // Add vendor/retailer to form data
+ const editVendorOrRetailer = document.getElementById('editVendorOrRetailer');
+ formData.append('vendor', editVendorOrRetailer ? editVendorOrRetailer.value.trim() : '');
+
+ const response = await fetch(`/api/warranties/${notesModalWarrantyId}`, { // Added await and response handling
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+
+ if (!response.ok) { // Check if the API call was successful
+ const errorData = await response.json().catch(() => ({})); // Try to parse error, default to empty object
+ throw new Error(errorData.error || `Failed to update note (Status: ${response.status})`);
+ }
+
+
+ hideLoadingSpinner();
+ showToast('Note updated', 'success');
+
+ // Update the warranty in the global warranties array immediately
+ const warrantyIndex = warranties.findIndex(w => w.id === notesModalWarrantyId);
+ if (warrantyIndex !== -1) {
+ warranties[warrantyIndex].notes = newNote;
+ }
+
+ // --- Updated UI logic ---
+ if (newNote === '') {
+ // If the note is now empty, close the modal
+ document.getElementById('notesModal').classList.remove('active');
+ } else {
+ // If note is not empty, update the view and stay in the modal
+ notesModalContent.textContent = newNote;
+ notesModalContent.style.display = '';
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+ // Update the local warranty object's notes
+ if (notesModalWarrantyObj) {
+ notesModalWarrantyObj.notes = newNote;
+ }
+ }
+ // --- End Updated UI logic ---
+
+ // Refresh warranties list and THEN update UI
+ await loadWarranties(true); // Wait for data refresh
+ applyFilters(); // Re-render the list with updated data
+
+ } catch (e) {
+ hideLoadingSpinner();
+ console.error("Error updating note:", e); // Log the error
+ showToast(e.message || 'Failed to update note', 'error'); // Show specific error if available
+ }
+ };
+ // Cancel button handler
+ cancelBtn.onclick = function() {
+ notesModalContent.style.display = '';
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+ };
+ notesModal.classList.add('active');
+}
+
+// Utility to get currency symbol from preferences/localStorage
+function getCurrencySymbol() {
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix; // Use let to allow default override
+ if (!prefix) {
+ console.warn('[getCurrencySymbol] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_'; // Default prefix if called too early
+ }
+ console.log(`[getCurrencySymbol] Using determined prefix: ${prefix}`);
+ let symbol = '$'; // Default value
+
+ const rawValue = localStorage.getItem(`${prefix}currencySymbol`);
+ console.log(`[getCurrencySymbol Debug] Raw value read from localStorage key '${prefix}currencySymbol':`, rawValue);
+ // +++ END ADDED LOG +++
+
+ // --- Priority 1: Load from individual key --- (Saved by settings-new.js)
+ const individualSymbol = rawValue; // Use the already read value
+ if (individualSymbol) { // Check uses the already read value
+ symbol = individualSymbol;
+ console.log(`[getCurrencySymbol] Loaded symbol from individual key (${prefix}currencySymbol): ${symbol}`);
+ return symbol;
+ }
+
+ // --- Priority 2: Load from preferences object (Legacy/Fallback) ---
+ try {
+ const prefsString = localStorage.getItem(`${prefix}preferences`);
+ console.log(`[getCurrencySymbol] Read prefsString for ${prefix}preferences:`, prefsString);
+ if (prefsString) {
+ const prefs = JSON.parse(prefsString);
+ if (prefs && prefs.currency_symbol) {
+ symbol = prefs.currency_symbol;
+ console.log(`[getCurrencySymbol] Loaded symbol from object key (${prefix}preferences): ${symbol}`);
+ }
+ }
+ } catch (e) {
+ console.error(`Error reading ${prefix}preferences from localStorage:`, e);
+ // Keep the default '$' symbol in case of error parsing the object
+ }
+
+ console.log(`[getCurrencySymbol] Returning symbol (default or from object): ${symbol}`);
+ return symbol;
+}
+
+// Function to get user's preferred currency code
+function getCurrencyCode() {
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyCode] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+ console.log(`[getCurrencyCode] Using determined prefix: ${prefix}`);
+
+ // Default to USD
+ let currencyCode = 'USD';
+
+ // Try to get currency code from localStorage
+ const rawValue = localStorage.getItem(`${prefix}currencyCode`);
+ console.log(`[getCurrencyCode Debug] Raw value read from localStorage key '${prefix}currencyCode':`, rawValue);
+
+ if (rawValue) {
+ currencyCode = rawValue;
+ console.log(`[getCurrencyCode] Loaded currency code from individual key (${prefix}currencyCode): ${currencyCode}`);
+ return currencyCode;
+ }
+
+ // Fallback: Try to derive currency code from symbol
+ const symbol = getCurrencySymbol();
+ const symbolToCurrencyMap = {
+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
+ 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
+ '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
+ '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
+ 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
+ '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
+ };
+
+ if (symbolToCurrencyMap[symbol]) {
+ currencyCode = symbolToCurrencyMap[symbol];
+ console.log(`[getCurrencyCode] Derived currency code from symbol '${symbol}': ${currencyCode}`);
+ } else {
+ console.log(`[getCurrencyCode] Could not derive currency code from symbol '${symbol}', using default: ${currencyCode}`);
+ }
+
+ return currencyCode;
+}
+
+// Function to load currencies from API and populate dropdowns
+async function loadCurrencies() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ const response = await fetch('/api/currencies', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Get user's preferred currency code for default selection
+ const preferredCurrencyCode = getCurrencyCode();
+
+ // Populate add warranty currency dropdown
+ if (currencySelect) {
+ currencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ currencySelect.appendChild(option);
+ });
+
+ // Set default selection to user's preferred currency
+ console.log(`[loadCurrencies] Preferred currency code: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Available currency options:`, Array.from(currencySelect.options).map(opt => opt.value));
+
+ if (preferredCurrencyCode) {
+ // Use setTimeout to ensure DOM is fully updated
+ setTimeout(() => {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[loadCurrencies] Set add warranty currency default to: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Current selected value: ${currencySelect.value}`);
+
+ // Trigger change event to update any dependent UI
+ const changeEvent = new Event('change', { bubbles: true });
+ currencySelect.dispatchEvent(changeEvent);
+ }, 10);
+ } else {
+ console.log(`[loadCurrencies] No preferred currency code found, keeping default USD`);
+ }
+ }
+
+ // Populate edit warranty currency dropdown
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ editCurrencySelect.appendChild(option);
+ });
+ }
+
+ console.log('Currencies loaded successfully');
+ } catch (error) {
+ console.error('Error loading currencies:', error);
+ // Fallback to USD if loading fails
+ if (currencySelect) {
+ currencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ }
+}
+
+function getCurrencySymbolByCode(currencyCode) {
+ const currencyMap = {
+ 'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CNY': '¥', 'INR': '₹', 'KRW': '₩',
+ 'CHF': 'CHF', 'CAD': 'C$', 'AUD': 'A$', 'SEK': 'kr', 'NOK': 'kr', 'DKK': 'kr',
+ 'PLN': 'zł', 'CZK': 'Kč', 'HUF': 'Ft', 'BGN': 'лв', 'RON': 'lei', 'HRK': 'kn',
+ 'RUB': '₽', 'BRL': 'R$', 'MXN': '$', 'ARS': '$', 'CLP': '$', 'COP': '$',
+ 'PEN': 'S/', 'VES': 'Bs', 'ZAR': 'R', 'EGP': '£', 'NGN': '₦', 'KES': 'KSh',
+ 'GHS': '₵', 'MAD': 'DH', 'TND': 'DT', 'AED': 'AED', 'SAR': 'SR', 'QAR': 'QR',
+ 'KWD': 'KD', 'BHD': 'BD', 'OMR': 'OR', 'JOD': 'JD', 'LBP': 'LL', 'ILS': '₪',
+ 'TRY': '₺', 'IRR': '﷼', 'PKR': '₨', 'BDT': '৳', 'LKR': 'Rs', 'NPR': 'Rs',
+ 'BTN': 'Nu', 'MMK': 'K', 'THB': '฿', 'VND': '₫', 'LAK': '₭', 'KHR': '៛',
+ 'MYR': 'RM', 'SGD': 'S$', 'IDR': 'Rp', 'PHP': '₱', 'TWD': 'NT$', 'HKD': 'HK$',
+ 'MOP': 'MOP', 'KPW': '₩', 'MNT': '₮', 'KZT': '₸', 'UZS': 'soʻm', 'TJS': 'SM',
+ 'KGS': 'с', 'TMT': 'T', 'AFN': '؋', 'AMD': '֏', 'AZN': '₼', 'GEL': '₾',
+ 'MDL': 'L', 'UAH': '₴', 'BYN': 'Br', 'RSD': 'дин', 'MKD': 'ден', 'ALL': 'L',
+ 'BAM': 'KM', 'ISK': 'kr', 'FJD': 'FJ$', 'PGK': 'K', 'SBD': 'SI$', 'TOP': 'T$',
+ 'VUV': 'VT', 'WST': 'WS$', 'XPF': '₣', 'NZD': 'NZ$'
+ };
+ return currencyMap[currencyCode] || currencyCode;
+}
+
+function getCurrencyPosition() {
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyPosition] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+
+ let position = 'left'; // Default position
+ const rawValue = localStorage.getItem(`${prefix}currencyPosition`);
+ console.log(`[getCurrencyPosition] Raw value from localStorage (${prefix}currencyPosition):`, rawValue);
+
+ if (rawValue) {
+ position = rawValue;
+ console.log(`[getCurrencyPosition] Loaded position from localStorage: ${position}`);
+ } else {
+ console.log(`[getCurrencyPosition] No position found, using default: ${position}`);
+ }
+
+ return position;
+}
+
+function formatCurrencyHTML(amount, symbol, position) {
+ const formattedAmount = parseFloat(amount).toFixed(2);
+
+ if (position === 'right') {
+ return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${symbol}</span>`;
+ } else {
+ return `<span class="currency-symbol">${symbol}</span><span>${formattedAmount}</span>`;
+ }
+}
+
+function updateCurrencySymbols() {
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ console.log(`Updating currency symbols to: ${symbol}, position: ${position}`);
+
+ // Update all currency symbols
+ const elements = document.querySelectorAll('.currency-symbol');
+ console.log(`Found ${elements.length} elements with class 'currency-symbol'.`);
+ elements.forEach(el => {
+ el.textContent = symbol;
+ });
+
+ // Update form currency positioning
+ updateFormCurrencyPosition(symbol, position);
+}
+
+function updateFormCurrencyPosition(symbol, position) {
+ // Handle add warranty form
+ const addPriceWrapper = document.getElementById('addPriceInputWrapper');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ const addPriceInput = document.getElementById('purchasePrice');
+
+ if (addPriceWrapper && addCurrencySymbol) {
+ addCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ addPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (addPriceInput) {
+ setupDynamicCurrencyPosition(addPriceInput, addCurrencySymbol);
+ }
+ } else {
+ addPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (addCurrencySymbol) {
+ addCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated add form currency position: ${position}`);
+ }
+
+ // Handle edit warranty form
+ const editPriceWrapper = document.getElementById('editPriceInputWrapper');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ const editPriceInput = document.getElementById('editPurchasePrice');
+
+ if (editPriceWrapper && editCurrencySymbol) {
+ editCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ editPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (editPriceInput) {
+ setupDynamicCurrencyPosition(editPriceInput, editCurrencySymbol);
+ }
+ } else {
+ editPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (editCurrencySymbol) {
+ editCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated edit form currency position: ${position}`);
+ }
+}
+
+function setupDynamicCurrencyPosition(input, currencySymbol) {
+ if (!input || !currencySymbol) return;
+
+ function updatePosition() {
+ const wrapper = input.closest('.price-input-wrapper');
+ if (!wrapper || !wrapper.classList.contains('currency-right')) return;
+
+ // Wait for elements to be fully rendered
+ if (wrapper.offsetWidth === 0) {
+ setTimeout(updatePosition, 50);
+ return;
+ }
+
+ // Get the input value or placeholder
+ const text = input.value || input.placeholder || '0.00';
+
+ // Create a temporary element to measure text width
+ const tempSpan = document.createElement('span');
+ tempSpan.style.visibility = 'hidden';
+ tempSpan.style.position = 'absolute';
+ tempSpan.style.fontSize = window.getComputedStyle(input).fontSize;
+ tempSpan.style.fontFamily = window.getComputedStyle(input).fontFamily;
+ tempSpan.style.fontWeight = window.getComputedStyle(input).fontWeight;
+ tempSpan.style.letterSpacing = window.getComputedStyle(input).letterSpacing;
+ tempSpan.textContent = text;
+
+ document.body.appendChild(tempSpan);
+ const textWidth = tempSpan.offsetWidth;
+ document.body.removeChild(tempSpan);
+
+ // Calculate position: input padding + text width + small gap
+ const inputPaddingLeft = parseInt(window.getComputedStyle(input).paddingLeft) || 12;
+ const gap = 4; // Small gap between text and currency symbol
+ const wrapperWidth = wrapper.offsetWidth;
+ const rightPosition = Math.max(8, wrapperWidth - inputPaddingLeft - textWidth - gap - 20);
+
+ currencySymbol.style.right = rightPosition + 'px';
+ console.log(`[Dynamic Currency] Positioned currency symbol at ${rightPosition}px from right for text: "${text}"`);
+ }
+
+ // Update position on various events
+ input.addEventListener('input', updatePosition);
+ input.addEventListener('focus', updatePosition);
+ input.addEventListener('blur', updatePosition);
+
+ // Initial positioning with better timing
+ // Use requestAnimationFrame to ensure DOM is ready
+ requestAnimationFrame(() => {
+ updatePosition();
+ // Also set up additional fallback timers
+ setTimeout(updatePosition, 100);
+ setTimeout(updatePosition, 300);
+ });
+}
+
+// If you want to update currency symbols live when storage changes (e.g. settings page open in another tab):
+window.addEventListener('storage', function(e) {
+ const prefix = getPreferenceKeyPrefix();
+ // Only update if the main preferences object for the current user type changed
+ if (e.key === `${prefix}preferences`) {
+ console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
+ updateCurrencySymbols();
+ }
+ // Also update when currency position changes
+ if (e.key === `${prefix}currencyPosition`) {
+ console.log(`Storage event detected for ${prefix}currencyPosition. Re-rendering warranties to update currency position.`);
+ // Update forms immediately
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+ // Re-render warranties to apply new currency position
+ if (typeof processAllWarranties === 'function') {
+ processAllWarranties();
+ }
+ }
+});
+
+// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++
+async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthenticated parameter
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix; // <<< CHANGED const to let
+ if (!prefix) {
+ console.error('[Prefs Loader] Cannot load preferences: User preference prefix not set yet. Defaulting to user_');
+ // Setting a default might be risky if the user *is* admin but prefix wasn't set in time.
+ // Consider how authStateReady ensures prefix is set before this runs.
+ // For now, let's try defaulting, but this might need review.
+ prefix = 'user_';
+ }
+ console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}, isAuthenticated: ${isAuthenticated}`);
+
+ if (isAuthenticated && window.auth) { // Use passed isAuthenticated and check if window.auth exists
+ const token = window.auth.getToken(); // Still need token for the API call
+ if (!token) {
+ console.error('[Prefs Loader] Cannot load preferences: No auth token found, even though isAuthenticated was true.');
+ return; // Exit if no token
+ }
+
+ try {
+ console.log('[Prefs Loader] Fetching /api/auth/preferences with token.');
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+
+ if (response.ok) {
+ const apiPrefs = await response.json();
+ console.log('[Prefs Loader] Preferences loaded from API:', apiPrefs);
+
+ // Save relevant prefs to localStorage
+ if (apiPrefs.currency_symbol) {
+ localStorage.setItem(`${prefix}currencySymbol`, apiPrefs.currency_symbol);
+ console.log(`[Prefs Loader] Saved ${prefix}currencySymbol: ${apiPrefs.currency_symbol}`);
+ }
+ if (apiPrefs.currency_position) {
+ localStorage.setItem(`${prefix}currencyPosition`, apiPrefs.currency_position);
+ console.log(`[Prefs Loader] Saved ${prefix}currencyPosition: ${apiPrefs.currency_position}`);
+ }
+ if (apiPrefs.default_view) {
+ localStorage.setItem(`${prefix}defaultView`, apiPrefs.default_view);
+ console.log(`[Prefs Loader] Saved ${prefix}defaultView: ${apiPrefs.default_view}`);
+ }
+ // Apply theme from API and sync to localStorage
+ if (apiPrefs.theme) {
+ const isDark = apiPrefs.theme === 'dark';
+ // Apply without triggering API save to avoid loops
+ await saveThemePreference(isDark, false);
+ console.log(`[Prefs Loader] Applied theme from API: ${apiPrefs.theme}`);
+ }
+ // Save filter preferences from API to localStorage
+ if (apiPrefs.saved_filters) {
+ localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(apiPrefs.saved_filters));
+ console.log(`[Prefs Loader] Saved ${prefix}warrantyFilters:`, apiPrefs.saved_filters);
+ }
+ if (apiPrefs.expiring_soon_days !== undefined) {
+ localStorage.setItem(`${prefix}expiringSoonDays`, apiPrefs.expiring_soon_days);
+ // Also update the global variable used by processWarrantyData
+ expiringSoonDays = apiPrefs.expiring_soon_days;
+ console.log(`[Prefs Loader] Saved ${prefix}expiringSoonDays: ${apiPrefs.expiring_soon_days}`);
+ console.log(`[Prefs Loader] Updated global expiringSoonDays variable to: ${expiringSoonDays}`);
+ }
+ if (apiPrefs.date_format) {
+ localStorage.setItem('dateFormat', apiPrefs.date_format);
+ console.log(`[Prefs Loader] Saved dateFormat: ${apiPrefs.date_format}`);
+ }
+
+ // Optionally trigger immediate UI updates if needed, although renderWarranties will use these new values
+ // updateCurrencySymbols();
+
+ } else {
+ const errorData = await response.json().catch(() => ({}));
+ console.warn(`[Prefs Loader] Failed to load preferences from API: ${response.status}`, errorData.message || '');
+ // Set defaults in localStorage maybe?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+ } catch (error) {
+ console.error('[Prefs Loader] Error fetching/applying preferences from API:', error);
+ // Set defaults in localStorage on error?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+ } else {
+ console.warn('[Prefs Loader] Cannot load preferences: User not authenticated or auth module not available.');
+ // Apply defaults if not authenticated?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+}
+// +++ END NEW FUNCTION +++
+
+// Warranty method change handlers
+function handleWarrantyMethodChange() {
+ console.log('[DEBUG] handleWarrantyMethodChange called');
+ const isLifetime = isLifetimeCheckbox && isLifetimeCheckbox.checked;
+ const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
+
+ console.log('[DEBUG] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG] Elements found:', {
+ warrantyDurationFields: !!warrantyDurationFields,
+ exactExpirationField: !!exactExpirationField,
+ exactExpirationDateInput: !!exactExpirationDateInput
+ });
+
+ if (isLifetime) {
+ // Hide both methods when lifetime is selected
+ console.log('[DEBUG] Lifetime selected, hiding both methods');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+ return;
+ }
+
+ if (isDurationMethod) {
+ console.log('[DEBUG] Duration method selected');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'block';
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+ // Clear exact date when switching to duration
+ if (exactExpirationDateInput) exactExpirationDateInput.value = '';
+ } else {
+ console.log('[DEBUG] Exact date method selected');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
+ if (exactExpirationField) exactExpirationField.style.display = 'block';
+ // Clear duration fields when switching to exact date
+ if (warrantyDurationYearsInput) warrantyDurationYearsInput.value = '';
+ if (warrantyDurationMonthsInput) warrantyDurationMonthsInput.value = '';
+ if (warrantyDurationDaysInput) warrantyDurationDaysInput.value = '';
+ }
+}
+
+function handleEditWarrantyMethodChange() {
+ console.log('[DEBUG] handleEditWarrantyMethodChange called');
+ const isLifetime = editIsLifetimeCheckbox && editIsLifetimeCheckbox.checked;
+ const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
+
+ console.log('[DEBUG Edit] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG Edit] Radio button states:', {
+ editDurationMethodRadio: editDurationMethodRadio ? editDurationMethodRadio.checked : 'element not found',
+ editExactDateMethodRadio: editExactDateMethodRadio ? editExactDateMethodRadio.checked : 'element not found'
+ });
+ console.log('[DEBUG Edit] Elements found:', {
+ editWarrantyDurationFields: !!editWarrantyDurationFields,
+ editExactExpirationField: !!editExactExpirationField,
+ editExactExpirationDateInput: !!editExactExpirationDateInput
+ });
+
+ if (isLifetime) {
+ // Hide both methods when lifetime is selected
+ console.log('[DEBUG Edit] Lifetime selected, hiding both methods');
+ if (editWarrantyDurationFields) editWarrantyDurationFields.style.display = 'none';
+ if (editExactExpirationField) editExactExpirationField.style.display = 'none';
+ return;
+ }
+
+ if (isDurationMethod) {
+ console.log('[DEBUG Edit] Duration method selected');
+ if (editWarrantyDurationFields) {
+ editWarrantyDurationFields.style.display = 'block';
+ console.log('[DEBUG Edit] Set duration fields to block');
+ }
+ if (editExactExpirationField) {
+ editExactExpirationField.style.display = 'none';
+ console.log('[DEBUG Edit] Set exact date field to none');
+ }
+ // Clear exact date when switching to duration
+ if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
+ } else {
+ console.log('[DEBUG Edit] Exact date method selected');
+ if (editWarrantyDurationFields) {
+ editWarrantyDurationFields.style.display = 'none';
+ console.log('[DEBUG Edit] Set duration fields to none');
+ }
+ if (editExactExpirationField) {
+ editExactExpirationField.style.display = 'block';
+ console.log('[DEBUG Edit] Set exact date field to block');
+ }
+ // Clear duration fields when switching to exact date
+ if (editWarrantyDurationYearsInput) editWarrantyDurationYearsInput.value = '';
+ if (editWarrantyDurationMonthsInput) editWarrantyDurationMonthsInput.value = '';
+ if (editWarrantyDurationDaysInput) editWarrantyDurationDaysInput.value = '';
+ }
+}
+
+// Function to calculate duration between two dates
+function calculateDurationFromDates(startDate, endDate) {
+ if (!startDate || !endDate) return null;
+
+ try {
+ const start = new Date(startDate);
+ const end = new Date(endDate);
+
+ if (isNaN(start.getTime()) || isNaN(end.getTime())) return null;
+
+ let years = end.getFullYear() - start.getFullYear();
+ let months = end.getMonth() - start.getMonth();
+ let days = end.getDate() - start.getDate();
+
+ // Adjust for negative days
+ if (days < 0) {
+ months--;
+ const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);
+ days += prevMonth.getDate();
+ }
+
+ // Adjust for negative months
+ if (months < 0) {
+ years--;
+ months += 12;
+ }
+
+ return { years, months, days };
+ } catch (error) {
+ console.error('Error calculating duration:', error);
+ return null;
+ }
+}
+
+/**
+ * Load secure images with authentication
+ */
+async function loadSecureImages() {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.log('[DEBUG] No auth token available for secure image loading');
+ return;
+ }
+
+ // Also find images that may already have src but need to be refreshed
+ const secureImages = document.querySelectorAll('img.secure-image[data-secure-src]');
+ console.log(`[DEBUG] Found ${secureImages.length} secure images to load/refresh`);
+
+ for (const img of secureImages) {
+ try {
+ const secureUrl = img.getAttribute('data-secure-src');
+ console.log(`[DEBUG] Loading secure image: ${secureUrl}`);
+
+ // Clean up existing blob URL if present
+ const existingBlobUrl = img.getAttribute('data-blob-url');
+ if (existingBlobUrl) {
+ URL.revokeObjectURL(existingBlobUrl);
+ img.removeAttribute('data-blob-url');
+ }
+
+ const response = await fetch(secureUrl, {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+
+ if (response.ok) {
+ const blob = await response.blob();
+ const blobUrl = URL.createObjectURL(blob);
+ img.src = blobUrl;
+
+ // Clean up blob URL when image is removed from DOM
+ img.addEventListener('load', () => {
+ console.log(`[DEBUG] Secure image loaded successfully: ${secureUrl}`);
+ }, { once: true });
+
+ // Store blob URL for cleanup
+ img.setAttribute('data-blob-url', blobUrl);
+ } else {
+ console.error(`[DEBUG] Failed to load secure image: ${secureUrl}, status: ${response.status}`);
+ img.style.display = 'none';
+ }
+ } catch (error) {
+ console.error(`[DEBUG] Error loading secure image:`, error);
+ img.style.display = 'none';
+ }
+ }
+}
+
+// ============================================================================
+// Paperless-ngx Integration Functions
+// ============================================================================
+
+// Global variable to store Paperless-ngx enabled state
+let paperlessNgxEnabled = false;
+
+/**
+ * Check if Paperless-ngx integration is enabled
+ */
+async function checkPaperlessNgxStatus() {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) return false;
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const settings = await response.json();
+ paperlessNgxEnabled = settings.paperless_enabled === 'true';
+ window.paperlessNgxEnabled = paperlessNgxEnabled; // Set global variable
+ console.log('[Paperless-ngx] Integration status:', paperlessNgxEnabled);
+ return paperlessNgxEnabled;
+ }
+ } catch (error) {
+ console.error('[Paperless-ngx] Error checking status:', error);
+ }
+ return false;
+}
+
+/**
+ * Initialize Paperless-ngx integration UI
+ */
+async function initPaperlessNgxIntegration() {
+ // Check if Paperless-ngx is enabled
+ const isEnabled = await checkPaperlessNgxStatus();
+
+ if (isEnabled) {
+ // Show the info alert
+ const infoAlert = document.getElementById('paperlessInfoAlert');
+ if (infoAlert) {
+ infoAlert.style.display = 'block';
+ }
+
+ // Show storage selection options for add modal (only invoice and manual)
+ const storageSelections = [
+ 'invoiceStorageSelection',
+ 'manualStorageSelection'
+ ];
+
+ storageSelections.forEach(id => {
+ const element = document.getElementById(id);
+ if (element) {
+ element.style.display = 'block';
+ }
+ });
+
+ // Show storage selection options for edit modal (only invoice and manual)
+ const editStorageSelections = [
+ 'editInvoiceStorageSelection',
+ 'editManualStorageSelection'
+ ];
+
+ editStorageSelections.forEach(id => {
+ const element = document.getElementById(id);
+ if (element) {
+ element.style.display = 'block';
+ }
+ });
+
+ // Show Paperless browse sections
+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections...');
+ togglePaperlessBrowseSections();
+
+ console.log('[Paperless-ngx] UI elements initialized and shown');
+ } else {
+ console.log('[Paperless-ngx] Integration disabled, hiding UI elements');
+
+ // Hide Paperless browse sections
+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections (disabled)...');
+ togglePaperlessBrowseSections();
+ }
+}
+
+/**
+ * Get selected storage option for a document type
+ * @param {string} documentType - The document type (productPhoto, invoice, manual, otherDocument)
+ * @param {boolean} isEdit - Whether this is for the edit modal
+ * @returns {string} - 'local' or 'paperless'
+ */
+function getStorageOption(documentType, isEdit = false) {
+ // Only allow Paperless-ngx storage for invoices and manuals
+ const paperlessAllowedTypes = ['invoice', 'manual'];
+
+ if (!paperlessAllowedTypes.includes(documentType)) {
+ return 'local'; // Force local storage for productPhoto and otherDocument
+ }
+
+ const prefix = isEdit ? 'edit' : '';
+ const capitalizedType = documentType.charAt(0).toUpperCase() + documentType.slice(1);
+ const name = `${prefix}${capitalizedType}Storage`;
+ const radio = document.querySelector(`input[name="${name}"]:checked`);
+ return radio ? radio.value : 'local';
+}
+
+/**
+ * Upload file to Paperless-ngx
+ * @param {File} file - The file to upload
+ * @param {string} documentType - The type of document for tagging
+ * @returns {Promise<Object>} - Upload result with document ID
+ */
+async function uploadToPaperlessNgx(file, documentType) {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ throw new Error('Authentication token not available');
+ }
+
+ // Show upload loading screen
+ showPaperlessUploadLoading(documentType);
+
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('document_type', documentType);
+ formData.append('title', `Warracker ${documentType} - ${file.name}`);
+
+ // Add tags for organization
+ const tags = ['warracker', documentType];
+ formData.append('tags', tags.join(','));
+
+ console.log('[Paperless-ngx] Upload FormData contents:');
+ console.log(' - file:', file.name, '(' + file.size + ' bytes, ' + file.type + ')');
+ console.log(' - document_type:', documentType);
+ console.log(' - title:', `Warracker ${documentType} - ${file.name}`);
+ console.log(' - tags:', tags.join(','));
+
+ updatePaperlessUploadStatus('Uploading file to Paperless-ngx...');
+
+ const response = await fetch('/api/paperless/upload', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ },
+ body: formData
+ });
+
+ if (!response.ok) {
+ let errorMessage = 'Failed to upload to Paperless-ngx';
+ try {
+ const errorData = await response.json();
+ errorMessage = errorData.error || errorData.message || errorMessage;
+ console.error('[Paperless-ngx] Server error details:', errorData);
+ } catch (parseError) {
+ console.error('[Paperless-ngx] Could not parse error response:', parseError);
+ errorMessage = `HTTP ${response.status}: ${response.statusText}`;
+ }
+ hidePaperlessUploadLoading();
+ throw new Error(errorMessage);
+ }
+
+ const result = await response.json();
+ console.log('[Paperless-ngx] Upload successful:', result);
+
+ // Update status based on result
+ if (result.document_id) {
+ updatePaperlessUploadStatus('Document uploaded and ready!');
+ } else {
+ updatePaperlessUploadStatus('Document uploaded, processing...', true);
+ }
+
+ return {
+ success: true,
+ document_id: result.document_id,
+ message: result.message,
+ error: result.error // Add this
+ };
+
+ } catch (error) {
+ console.error('[Paperless-ngx] Upload error:', error);
+ hidePaperlessUploadLoading();
+ return {
+ success: false,
+ error: error.message
+ };
+ }
+}
+
+/**
+ * Handle warranty form submission with Paperless-ngx integration
+ * This extends the existing saveWarranty function
+ */
+async function processPaperlessNgxUploads(formData) {
+ if (!paperlessNgxEnabled) {
+ return {}; // Return empty object if not enabled
+ }
+
+ const uploads = {};
+ // Only process invoice and manual for Paperless-ngx uploads
+ const documentTypes = ['invoice', 'manual'];
+
+ for (const docType of documentTypes) {
+ // Use storage option from formData, not DOM
+ const storageKey = docType + 'Storage';
+ const storageOption = formData.get(storageKey) || 'local';
+ const fileInput = document.getElementById(docType);
+ const file = fileInput?.files[0];
+ console.log(`[DEBUG][processPaperlessNgxUploads] docType:`, docType, '| storageOption (from formData):', storageOption, '| file:', file);
+ if (storageOption === 'paperless') {
+ if (file) {
+ console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx`);
+ // Upload to Paperless-ngx
+ const uploadResult = await uploadToPaperlessNgx(file, docType);
+ console.log(`[DEBUG][processPaperlessNgxUploads] uploadResult for ${docType}:`, uploadResult);
+ if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
+ // Map frontend document types to database column names
+ const fieldMapping = {
+ 'productPhoto': 'paperless_photo_id',
+ 'invoice': 'paperless_invoice_id',
+ 'manual': 'paperless_manual_id',
+ 'otherDocument': 'paperless_other_id'
+ };
+ const dbField = fieldMapping[docType];
+ if (dbField && uploadResult.document_id) {
+ uploads[dbField] = uploadResult.document_id;
+ console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully, ID: ${uploadResult.document_id}, stored as: ${dbField}`);
+ // Hide loading screen immediately for direct uploads
+ hidePaperlessUploadLoading();
+ if (uploadResult.error && uploadResult.error.includes("duplicate")) {
+ showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
+ }
+ } else if (dbField && !uploadResult.document_id) {
+ console.log(`[Paperless-ngx] ${docType} uploaded successfully but no document ID received (async processing). Not storing reference.`);
+ // Don't hide loading screen yet - auto-link will handle it
+ updatePaperlessUploadStatus('Document processing, searching for link...', true);
+ }
+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
+ // This prevents the backend from also saving it locally
+ if (formData.has(docType)) {
+ formData.delete(docType);
+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
+ }
+ } else {
+ console.error(`[Paperless-ngx] Failed to upload ${docType} to Paperless-ngx:`, uploadResult.error);
+ throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
+ }
+ } else {
+ console.log(`[DEBUG][processPaperlessNgxUploads] No file found for ${docType} with paperless storage option.`);
+ }
+ } else {
+ console.log(`[DEBUG][processPaperlessNgxUploads] Skipping ${docType}, storageOption is not paperless.`);
+ }
+ }
+
+ return uploads;
+}
+
+/**
+ * Handle warranty edit form submission with Paperless-ngx integration
+ * This extends the existing edit warranty functionality
+ */
+async function processEditPaperlessNgxUploads(formData) {
+ if (!paperlessNgxEnabled) {
+ return {}; // Return empty object if not enabled
+ }
+
+ const uploads = {};
+ // Only process invoice and manual for Paperless-ngx uploads
+ const documentTypes = ['invoice', 'manual'];
+
+ for (const docType of documentTypes) {
+ const storageOption = getStorageOption(docType, true); // true for edit modal
+
+ if (storageOption === 'paperless') {
+ const fileInput = document.getElementById(`edit${docType.charAt(0).toUpperCase() + docType.slice(1)}`);
+ const file = fileInput?.files[0];
+
+ if (file) {
+ console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx (edit mode)`);
+
+ // Upload to Paperless-ngx
+ const uploadResult = await uploadToPaperlessNgx(file, docType);
+
+ if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
+ // Map frontend document types to database column names
+ const fieldMapping = {
+ 'productPhoto': 'paperless_photo_id',
+ 'invoice': 'paperless_invoice_id',
+ 'manual': 'paperless_manual_id',
+ 'otherDocument': 'paperless_other_id'
+ };
+
+ const dbField = fieldMapping[docType];
+ if (dbField && uploadResult.document_id) {
+ uploads[dbField] = uploadResult.document_id;
+ console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully (edit), ID: ${uploadResult.document_id}, stored as: ${dbField}`);
+ // Hide loading screen immediately for direct uploads
+ hidePaperlessUploadLoading();
+ if (uploadResult.error && uploadResult.error.includes("duplicate")) {
+ showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
+ }
+ } else if (dbField && !uploadResult.document_id) {
+ console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit) but no document ID received (async processing). Not storing reference.`);
+ // Don't hide loading screen yet - auto-link will handle it
+ updatePaperlessUploadStatus('Document processing, searching for link...', true);
+ }
+
+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
+ // This prevents the backend from also saving it locally
+ // Note: In edit mode, the form field names don't have 'edit' prefix in FormData
+ if (formData.has(docType)) {
+ formData.delete(docType);
+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
+ }
+ } else {
+ throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
+ }
+ }
+ }
+ }
+
+ return uploads;
+}
+
+// Initialize Paperless-ngx integration when the page loads
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize after a short delay to ensure other components are loaded
+ setTimeout(() => {
+ initPaperlessNgxIntegration();
+ }, 1000);
+});
+
+/**
+ * Debug Paperless-ngx configuration
+ */
+async function debugPaperlessConfiguration() {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('[Paperless Debug] No auth token found');
+ return null;
+ }
+
+ console.log('[Paperless Debug] Checking configuration...');
+
+ const response = await fetch('/api/paperless/debug', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error('[Paperless Debug] Debug endpoint failed:', response.status, response.statusText);
+ const errorText = await response.text();
+ console.error('[Paperless Debug] Error response:', errorText);
+ return null;
+ }
+
+ const result = await response.json();
+ console.log('[Paperless Debug] Configuration:', result);
+
+ return result;
+ } catch (error) {
+ console.error('[Paperless Debug] Error:', error);
+ return null;
+ }
+}
+
+/**
+ * Open a Paperless-ngx document either in Warracker interface or in Paperless-ngx directly
+ */
+async function openPaperlessDocument(paperlessId, warrantyContext = null) {
+ console.log(`[openPaperlessDocument] Opening Paperless document: ${paperlessId}`, warrantyContext);
+
+ // First, debug the Paperless configuration
+ const debugInfo = await debugPaperlessConfiguration();
+ if (debugInfo) {
+ console.log('[openPaperlessDocument] Debug info:', debugInfo);
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ showToast('Paperless-ngx integration is not enabled', 'error');
+ return;
+ }
+
+ if (!debugInfo.paperless_handler_available) {
+ showToast('Paperless-ngx is not properly configured. Please check the settings.', 'error');
+ console.error('[openPaperlessDocument] Paperless handler not available');
+ if (debugInfo.paperless_handler_error) {
+ console.error('[openPaperlessDocument] Handler error:', debugInfo.paperless_handler_error);
+ }
+ return;
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ showToast(`Paperless-ngx connection failed: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`, 'error');
+ return;
+ }
+ }
+
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('[openPaperlessDocument] No auth token available');
+ showToast('Authentication required', 'error');
+ return;
+ }
+
+ // Check user preference for viewing documents, considering Global View context
+ const viewInApp = await getUserPaperlessViewPreference(warrantyContext);
+ console.log(`[openPaperlessDocument] User preference view in app: ${viewInApp}`);
+
+ if (viewInApp) {
+ // Open document in Warracker interface
+ console.log(`[openPaperlessDocument] Opening document ${paperlessId} in Warracker interface`);
+ const documentUrl = `/api/paperless-file/${paperlessId}?token=${encodeURIComponent(token)}`;
+
+ const newTab = window.open(documentUrl, '_blank');
+ if (!newTab) {
+ showToast('Please allow popups to view documents', 'warning');
+ } else {
+ showToast('Opening document in Warracker...', 'info');
+ }
+ return;
+ }
+
+ // Default behavior: open in Paperless-ngx interface
+ try {
+ // Get the Paperless-ngx base URL
+ const response = await fetch('/api/paperless/url', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error('[openPaperlessDocument] URL endpoint failed:', response.status, errorText);
+ throw new Error(`Failed to get Paperless-ngx URL: ${response.status}`);
+ }
+
+ const result = await response.json();
+ if (!result.success) {
+ throw new Error(result.message || 'Failed to get Paperless-ngx URL');
+ }
+
+ // Construct the direct link to the document in Paperless-ngx
+ const paperlessUrl = result.url.replace(/\/$/, ''); // Remove trailing slash
+ const documentUrl = `${paperlessUrl}/documents/${paperlessId}/details`;
+
+ console.log(`[openPaperlessDocument] Opening Paperless-ngx document at: ${documentUrl}`);
+
+ // Open the document directly in Paperless-ngx interface
+ const newTab = window.open(documentUrl, '_blank');
+ if (!newTab) {
+ showToast('Please allow popups to view documents in Paperless-ngx', 'warning');
+ } else {
+ showToast('Opening document in Paperless-ngx...', 'info');
+ }
+
+ } catch (error) {
+ console.error('Error opening Paperless document:', error);
+ showToast(`Error opening document: ${error.message}`, 'error');
+
+ // Try to determine the base URL from debug info for fallback
+ if (debugInfo && debugInfo.paperless_url) {
+ const fallbackUrl = `${debugInfo.paperless_url.replace(/\/$/, '')}/documents/${paperlessId}/details`;
+ console.log(`[openPaperlessDocument] Trying fallback URL: ${fallbackUrl}`);
+
+ const fallbackTab = window.open(fallbackUrl, '_blank');
+ if (fallbackTab) {
+ showToast('Opened with fallback URL - please check if Paperless-ngx is accessible', 'warning');
+ }
+ } else {
+ // Last resort fallback
+ const genericFallbackUrl = `${window.location.protocol}//${window.location.hostname}:8000/documents/${paperlessId}/details`;
+ console.log(`[openPaperlessDocument] Trying generic fallback URL: ${genericFallbackUrl}`);
+
+ const genericTab = window.open(genericFallbackUrl, '_blank');
+ if (genericTab) {
+ showToast('Opened with generic fallback URL', 'warning');
+ }
+ }
+ }
+}
+
+/**
+ * Get user preference for viewing Paperless documents in app
+ */
+async function getUserPaperlessViewPreference(warrantyContext = null) {
+ // Special handling for Global View: default to view in app for other users' documents
+ if (warrantyContext && isGlobalView) {
+ const currentUserId = (() => {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.id;
+ } catch (e) {
+ return null;
+ }
+ })();
+
+ // If viewing another user's document in Global View, default to view in app
+ if (currentUserId && warrantyContext.user_id && warrantyContext.user_id !== currentUserId) {
+ console.log(`[getUserPaperlessViewPreference] Global View: Defaulting to view in app for other user's document (warranty user: ${warrantyContext.user_id}, current user: ${currentUserId})`);
+ return true;
+ }
+ }
+
+ // First check localStorage
+ const prefix = getPreferenceKeyPrefix();
+ const localPreference = localStorage.getItem(`${prefix}paperlessViewInApp`);
+ if (localPreference !== null) {
+ return localPreference === 'true';
+ }
+
+ // If not in localStorage, check API
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ const response = await fetch('/api/auth/preferences', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+ if (response.ok) {
+ const prefs = await response.json();
+ return prefs.paperless_view_in_app || false;
+ }
+ } catch (e) {
+ console.warn('Failed to load preferences from API:', e);
+ }
+ }
+
+ // Default to false (open in Paperless-ngx)
+ return false;
+}
+
+/**
+ * Debug function to test Paperless document status
+ */
+async function debugPaperlessDocument(paperlessId) {
+ console.log(`[debugPaperlessDocument] Debugging Paperless document: ${paperlessId}`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[debugPaperlessDocument] No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/paperless/debug-document/${paperlessId}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(`[debugPaperlessDocument] HTTP ${response.status}: ${errorText}`);
+ return;
+ }
+
+ const debugInfo = await response.json();
+ console.log(`[debugPaperlessDocument] Debug info for document ${paperlessId}:`, debugInfo);
+
+ // Show debug info in a more readable format
+ let debugMessage = `Debug info for Paperless document ${paperlessId}:\n\n`;
+ debugMessage += `Document exists: ${debugInfo.document_exists}\n`;
+ debugMessage += `Database references: ${debugInfo.database_references?.length || 0}\n\n`;
+
+ debugMessage += 'Endpoint test results:\n';
+ for (const [endpoint, result] of Object.entries(debugInfo.endpoints_tested || {})) {
+ debugMessage += `- ${endpoint}: ${result.success ? 'SUCCESS' : 'FAILED'} (${result.status_code || result.error})\n`;
+ }
+
+ if (debugInfo.recent_documents && Array.isArray(debugInfo.recent_documents)) {
+ debugMessage += `\nDocument in recent list: ${debugInfo.document_in_recent}\n`;
+ debugMessage += `Recent documents: ${debugInfo.recent_documents.map(d => `${d.id}: ${d.title}`).join(', ')}\n`;
+ }
+
+ alert(debugMessage);
+
+ } catch (error) {
+ console.error('Error debugging Paperless document:', error);
+ alert(`Debug failed: ${error.message}`);
+ }
+}
+
+/**
+ * Clean up invalid Paperless-ngx document references
+ */
+async function cleanupInvalidPaperlessDocuments() {
+ console.log('[cleanupInvalidPaperlessDocuments] Starting cleanup...');
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[cleanupInvalidPaperlessDocuments] No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch('/api/paperless/cleanup-invalid', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(`[cleanupInvalidPaperlessDocuments] HTTP ${response.status}: ${errorText}`);
+ return;
+ }
+
+ const result = await response.json();
+ console.log('[cleanupInvalidPaperlessDocuments] Cleanup result:', result);
+
+ // Show result to user
+ let message = result.message || 'Cleanup completed';
+ if (result.details) {
+ message += `\n\nDetails:\n`;
+ message += `- Documents checked: ${result.details.checked}\n`;
+ message += `- Invalid documents found: ${result.details.invalid_found}\n`;
+ message += `- References cleaned up: ${result.details.cleaned_up}\n`;
+
+ if (result.details.errors && result.details.errors.length > 0) {
+ message += `\nErrors:\n${result.details.errors.join('\n')}`;
+ }
+ }
+
+ alert(message);
+
+ // Reload warranties to reflect changes
+ if (result.details && result.details.cleaned_up > 0) {
+ console.log('[cleanupInvalidPaperlessDocuments] Reloading warranties after cleanup...');
+ await loadWarranties(true);
+ }
+
+ } catch (error) {
+ console.error('Error cleaning up Paperless documents:', error);
+ alert(`Cleanup failed: ${error.message}`);
+ }
+}
+
+/**
+ * Search for and link a Paperless document by title
+ * Used when documents were uploaded with async processing and we lost the document ID
+ */
+async function searchAndLinkPaperlessDocument(warrantyId, documentType, searchTitle) {
+ try {
+ console.log(`[Paperless-ngx] Searching for document: ${searchTitle}`);
+
+ const response = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: documentType,
+ search_title: searchTitle
+ })
+ });
+
+ const result = await response.json();
+
+ if (result.success) {
+ console.log(`[Paperless-ngx] Document linked successfully: ID ${result.document_id}`);
+ showToast('Document linked successfully! Refreshing...', 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 [Search&Link] Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ [Search&Link] Warranties reloaded and UI updated');
+ }, 1000);
+
+ return { success: true, document_id: result.document_id };
+ } else {
+ console.error(`[Paperless-ngx] Failed to link document: ${result.message}`);
+ showToast(`Failed to link document: ${result.message}`, 'error');
+ return { success: false, message: result.message };
+ }
+ } catch (error) {
+ console.error(`[Paperless-ngx] Error searching for document:`, error);
+ showToast('Error searching for document', 'error');
+ return { success: false, message: error.message };
+ }
+}
+
+/**
+ * Automatically search for and link recently uploaded documents
+ * This handles the case where Paperless-ngx async processing returns task_id instead of document_id
+ */
+async function autoLinkRecentDocuments(warrantyId, documentTypes = ['invoice', 'manual'], maxRetries = 10, retryDelay = 10000, fileInfo = {}) {
+ console.log(`[Auto-Link] Starting automatic document linking for warranty ${warrantyId}`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[Auto-Link] No auth token available');
+ return;
+ }
+
+ let attempt = 0;
+ let linkedDocuments = [];
+
+ const tryLinking = async () => {
+ attempt++;
+ console.log(`[Auto-Link] Attempt ${attempt}/${maxRetries} for warranty ${warrantyId}`);
+
+ try {
+ // First check if Paperless-ngx is properly configured
+ const debugInfo = await debugPaperlessConfiguration();
+ if (!debugInfo) {
+ console.error('[Auto-Link] Could not get Paperless debug info');
+ return;
+ }
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ console.log('[Auto-Link] Paperless-ngx integration is not enabled, skipping auto-link');
+ return;
+ }
+
+ if (!debugInfo.paperless_handler_available) {
+ console.error('[Auto-Link] Paperless handler not available:', debugInfo.paperless_handler_error || 'Unknown error');
+ return;
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ console.error('[Auto-Link] Paperless connection test failed:', debugInfo.test_connection_result.message || debugInfo.test_connection_result.error);
+ return;
+ }
+
+ console.log(`[Auto-Link] Using intelligent filename-based search. File info:`, fileInfo);
+
+ // Strategy 1: Search by exact filename (most reliable)
+ let candidateDocuments = [];
+
+ for (const [docType, filename] of Object.entries(fileInfo)) {
+ if (!documentTypes.includes(docType)) continue;
+
+ console.log(`[Auto-Link] Searching for ${docType} with filename: "${filename}"`);
+
+ // Remove file extension for searching
+ const baseFilename = filename.replace(/\.[^/.]+$/, '');
+
+ // Try multiple search strategies
+ const searchQueries = [
+ filename, // Exact filename with extension
+ baseFilename, // Filename without extension
+ `"${filename}"`, // Quoted exact match
+ `"${baseFilename}"`, // Quoted base filename
+ `Warracker ${docType} - ${baseFilename}` // Warracker format
+ ];
+
+ for (const query of searchQueries) {
+ try {
+ console.log(`[Auto-Link] Trying search query: "${query}"`);
+
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(query)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`[Auto-Link] Query "${query}" found ${docs.length} documents`);
+
+ if (docs.length > 0) {
+ // Filter for recent documents (last 24 hours)
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
+ const recentDocs = docs.filter(doc => {
+ try {
+ const docDate = new Date(doc.created);
+ return docDate > oneDayAgo;
+ } catch {
+ return true; // Include if we can't parse the date
+ }
+ });
+
+ if (recentDocs.length > 0) {
+ console.log(`[Auto-Link] Found ${recentDocs.length} recent documents for ${docType}`);
+ candidateDocuments.push({
+ docType,
+ filename,
+ documents: recentDocs,
+ searchQuery: query
+ });
+ break; // Found documents, no need to try other queries for this file
+ } else if (docs.length > 0) {
+ // If no recent docs but we found some documents, include them anyway
+ console.log(`[Auto-Link] Found ${docs.length} older documents for ${docType}, including them anyway`);
+ candidateDocuments.push({
+ docType,
+ filename,
+ documents: docs.slice(0, 3), // Take up to 3 most recent
+ searchQuery: query
+ });
+ break;
+ }
+ }
+ }
+ } catch (error) {
+ console.error(`[Auto-Link] Error searching with query "${query}":`, error);
+ }
+ }
+ }
+
+ // Strategy 2: Fallback to Warracker tag search if filename search fails
+ if (candidateDocuments.length === 0) {
+ console.log('[Auto-Link] No documents found by filename, trying Warracker tag search...');
+
+ const response = await fetch('/api/paperless/search?ordering=-created&created__gte=' +
+ new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const searchResult = await response.json();
+ let recentDocs = searchResult.results || [];
+
+ // Filter for Warracker documents
+ const warrackerDocs = recentDocs.filter(doc =>
+ doc.title && doc.title.includes('Warracker')
+ );
+
+ console.log(`[Auto-Link] Found ${warrackerDocs.length} Warracker documents from last 2 hours`);
+
+ // Group by document type
+ for (const docType of documentTypes) {
+ const typeDocs = warrackerDocs.filter(doc =>
+ doc.title && doc.title.includes(docType)
+ );
+
+ if (typeDocs.length > 0) {
+ candidateDocuments.push({
+ docType,
+ filename: fileInfo[docType] || `${docType} document`,
+ documents: typeDocs,
+ searchQuery: `Warracker ${docType}`
+ });
+ }
+ }
+ }
+ }
+
+ // Debug: Show what candidate documents we found
+ if (candidateDocuments.length > 0) {
+ console.log('[Auto-Link] Candidate documents found:');
+ candidateDocuments.forEach(candidate => {
+ console.log(` ${candidate.docType}: ${candidate.documents.length} documents found with query "${candidate.searchQuery}"`);
+ candidate.documents.forEach((doc, i) => {
+ console.log(` ${i+1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+ });
+ }
+
+ // Try to link the best candidate for each document type
+ for (const candidate of candidateDocuments) {
+ // Use the most recent document (first in the ordered list)
+ const doc = candidate.documents[0];
+
+ console.log(`[Auto-Link] Attempting to link ${candidate.docType}: ${doc.title} (ID: ${doc.id})`);
+
+ try {
+ const linkResponse = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: candidate.docType,
+ search_title: doc.title.replace('Warracker ' + candidate.docType + ' - ', '')
+ })
+ });
+
+ const linkResult = await linkResponse.json();
+
+ if (linkResult.success) {
+ console.log(`[Auto-Link] Successfully linked ${candidate.docType}: ${doc.title}`);
+ linkedDocuments.push({
+ type: candidate.docType,
+ title: doc.title,
+ id: doc.id,
+ filename: candidate.filename
+ });
+ } else {
+ console.log(`[Auto-Link] Failed to link ${candidate.docType}: ${linkResult.message}`);
+ }
+ } catch (error) {
+ console.error(`[Auto-Link] Error linking ${candidate.docType}:`, error);
+ }
+ }
+
+ // If we found and linked documents, we're done
+ if (linkedDocuments.length > 0) {
+ console.log(`[Auto-Link] Successfully linked ${linkedDocuments.length} documents:`, linkedDocuments);
+
+ // Update loading screen to show success
+ updatePaperlessUploadStatus('Documents linked successfully!');
+
+ // Show success message with filenames
+ const docInfo = linkedDocuments.map(d => `${d.type} (${d.filename || d.title})`).join(', ');
+ showToast(`Automatically linked ${linkedDocuments.length} document(s): ${docInfo}`, 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 [Auto-Link] Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ [Auto-Link] Warranties reloaded and UI updated');
+
+ // Hide loading screen after successful completion
+ hidePaperlessUploadLoading();
+ }, 1000);
+
+ return true;
+ }
+
+ // If no documents found and we have retries left, try again
+ if (attempt < maxRetries) {
+ console.log(`[Auto-Link] No documents found, retrying in ${retryDelay}ms...`);
+ updatePaperlessUploadStatus(`Searching for documents (attempt ${attempt + 1}/${maxRetries})...`, true);
+ setTimeout(tryLinking, retryDelay);
+ } else {
+ console.log(`[Auto-Link] No documents found after ${maxRetries} attempts`);
+ updatePaperlessUploadStatus('Document uploaded but could not auto-link');
+ showToast('Document uploaded to Paperless-ngx but could not be automatically linked. You can manually link it later.', 'warning');
+ // Hide loading screen after failed auto-link
+ setTimeout(() => {
+ hidePaperlessUploadLoading();
+ }, 2000);
+ }
+
+ } catch (error) {
+ console.error(`[Auto-Link] Error in attempt ${attempt}:`, error);
+
+ if (attempt < maxRetries) {
+ console.log(`[Auto-Link] Retrying in ${retryDelay}ms...`);
+ updatePaperlessUploadStatus(`Error occurred, retrying (${attempt + 1}/${maxRetries})...`, true);
+ setTimeout(tryLinking, retryDelay);
+ } else {
+ updatePaperlessUploadStatus('Upload completed with errors');
+ showToast('Document uploaded but auto-linking failed due to errors. You can manually link it later.', 'warning');
+ // Hide loading screen after final error
+ setTimeout(() => {
+ hidePaperlessUploadLoading();
+ }, 2000);
+ }
+ }
+ };
+
+ // Start the linking process
+ tryLinking();
+}
+
+// Make debug and cleanup functions available globally for console testing
+window.debugPaperlessDocument = debugPaperlessDocument;
+window.cleanupInvalidPaperlessDocuments = cleanupInvalidPaperlessDocuments;
+window.searchAndLinkPaperlessDocument = searchAndLinkPaperlessDocument;
+window.autoLinkRecentDocuments = autoLinkRecentDocuments;
+
+// Helper function to manually link a specific document by title
+window.manualLinkDocument = async function(warrantyId, documentType, titleSearchTerm) {
+ console.log(`🔗 Manually linking document for warranty ${warrantyId}`);
+ console.log(` Document type: ${documentType}`);
+ console.log(` Searching for title containing: "${titleSearchTerm}"`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('❌ No auth token available');
+ return;
+ }
+
+ try {
+ // Search for documents containing the search term
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(titleSearchTerm)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error(`❌ Search failed: ${response.status}`);
+ return;
+ }
+
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`📄 Found ${docs.length} documents matching "${titleSearchTerm}"`);
+
+ if (docs.length === 0) {
+ console.log('❌ No documents found. The document might still be processing in Paperless-ngx.');
+ return;
+ }
+
+ // Show all matching documents
+ docs.forEach((doc, index) => {
+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+
+ // Try to link the first matching document
+ const docToLink = docs[0];
+ console.log(`🔗 Attempting to link document ID ${docToLink.id}: "${docToLink.title}"`);
+
+ const linkResponse = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${token}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: documentType,
+ search_title: docToLink.title.replace('Warracker ' + documentType + ' - ', '')
+ })
+ });
+
+ const linkResult = await linkResponse.json();
+
+ if (linkResult.success) {
+ console.log(`✅ Successfully linked ${documentType}: ${docToLink.title}`);
+ showToast(`Document linked successfully: ${documentType}`, 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ Warranties reloaded and UI updated');
+ }, 1000);
+ } else {
+ console.error(`❌ Failed to link ${documentType}: ${linkResult.message}`);
+ }
+
+ return docToLink;
+
+ } catch (error) {
+ console.error('❌ Error in manual linking:', error);
+ }
+};
+
+// Helper function to search for documents in Paperless-ngx (debug function)
+window.debugSearchPaperlessDocuments = async function(searchTerm = 'Warracker', limit = 10) {
+ console.log(`🔍 Searching for documents containing: "${searchTerm}"`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('❌ No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(searchTerm)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error(`❌ Search failed: ${response.status}`);
+ return;
+ }
+
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`📄 Found ${docs.length} documents:`);
+ docs.slice(0, limit).forEach((doc, index) => {
+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+
+ if (docs.length > limit) {
+ console.log(` ... and ${docs.length - limit} more documents`);
+ }
+
+ return docs;
+ } catch (error) {
+ console.error('❌ Error searching documents:', error);
+ }
+};
+
+// Helper function for users to debug Paperless-ngx configuration
+window.debugPaperlessSetup = async function() {
+ console.log('🔍 Debugging Paperless-ngx setup...');
+
+ const debugInfo = await debugPaperlessConfiguration();
+ if (!debugInfo) {
+ console.error('❌ Could not get debug information');
+ return;
+ }
+
+ console.log('📋 Paperless-ngx Configuration:');
+ console.log(` Enabled: ${debugInfo.paperless_enabled}`);
+ console.log(` URL: ${debugInfo.paperless_url || 'Not set'}`);
+ console.log(` API Token Set: ${debugInfo.paperless_api_token_set}`);
+ console.log(` Handler Available: ${debugInfo.paperless_handler_available}`);
+
+ if (debugInfo.paperless_handler_error) {
+ console.error(` Handler Error: ${debugInfo.paperless_handler_error}`);
+ }
+
+ if (debugInfo.test_connection_result) {
+ console.log(` Connection Test: ${debugInfo.test_connection_result.success ? '✅ Success' : '❌ Failed'}`);
+ console.log(` Message: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`);
+ }
+
+ // Provide recommendations
+ console.log('\n💡 Recommendations:');
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ console.log(' - Enable Paperless-ngx integration in Settings');
+ }
+
+ if (!debugInfo.paperless_url) {
+ console.log(' - Set Paperless-ngx URL in Settings (e.g., http://paperless:8000)');
+ }
+
+ if (!debugInfo.paperless_api_token_set) {
+ console.log(' - Set API token in Settings (generate from Paperless-ngx → Settings → API Tokens)');
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ console.log(' - Check if Paperless-ngx is running and accessible');
+ console.log(' - Verify URL and API token are correct');
+ console.log(' - Check network connectivity between Warracker and Paperless-ngx');
+ }
+
+ return debugInfo;
+};
+
+// ===== PAPERLESS DOCUMENT BROWSER FUNCTIONALITY =====
+
+// Global variables for paperless browser
+let currentPaperlessDocuments = [];
+let selectedPaperlessDocument = null;
+let currentPaperlessPage = 1;
+let totalPaperlessPages = 1;
+let currentDocumentType = '';
+let paperlessSearchQuery = '';
+
+/**
+ * Open the Paperless document browser modal
+ * @param {string} documentType - Type of document being selected (invoice, manual, product_photo, other_document)
+ */
+function openPaperlessBrowser(documentType) {
+ currentDocumentType = documentType;
+ selectedPaperlessDocument = null;
+
+ // Reset pagination state
+ currentPaperlessPage = 1;
+ totalPaperlessPages = 1;
+ paperlessSearchQuery = '';
+
+ // Show the modal
+ const modal = document.getElementById('paperlessBrowserModal');
+ modal.classList.add('active');
+
+ // Reset search and filters
+ document.getElementById('paperlessSearchInput').value = '';
+ document.getElementById('paperlessTypeFilter').value = '';
+ document.getElementById('paperlessTagFilter').value = '';
+
+ // Load documents
+ loadAllPaperlessDocuments();
+
+ // Load tags for filter
+ loadPaperlessTags();
+
+ // Hide select button initially
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ if (selectBtn) {
+ selectBtn.style.display = 'none';
+ }
+}
+
+/**
+ * Load all Paperless documents
+ */
+async function loadAllPaperlessDocuments() {
+ try {
+ showPaperlessLoading();
+
+ const params = new URLSearchParams();
+ const offset = (currentPaperlessPage - 1) * 25;
+ params.append('limit', '25');
+ params.append('offset', offset.toString());
+
+ const response = await fetch(`/api/paperless/search?${params.toString()}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ currentPaperlessDocuments = data.results || [];
+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;
+
+ renderPaperlessDocuments();
+ updatePaperlessPagination();
+
+ } catch (error) {
+ console.error('Error loading Paperless documents:', error);
+ showPaperlessError('Failed to load documents from Paperless-ngx');
+ }
+}
+
+/**
+ * Search Paperless documents
+ */
+async function searchPaperlessDocuments() {
+ const searchInput = document.getElementById('paperlessSearchInput');
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ paperlessSearchQuery = searchInput.value.trim();
+
+ try {
+ showPaperlessLoading();
+
+ const params = new URLSearchParams();
+ if (paperlessSearchQuery) {
+ params.append('query', paperlessSearchQuery);
+ }
+ if (typeFilter.value) {
+ params.append('document_type', typeFilter.value);
+ }
+ if (tagFilter.value) {
+ params.append('tags__id__in', tagFilter.value);
+ }
+
+ // Add pagination
+ const offset = (currentPaperlessPage - 1) * 25;
+ params.append('limit', '25');
+ params.append('offset', offset.toString());
+
+ const response = await fetch(`/api/paperless/search?${params.toString()}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ currentPaperlessDocuments = data.results || [];
+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;
+
+ renderPaperlessDocuments();
+ updatePaperlessPagination();
+
+ } catch (error) {
+ console.error('Error searching Paperless documents:', error);
+ showPaperlessError('Failed to search documents');
+ }
+}
+
+/**
+ * Load Paperless tags for filter dropdown
+ */
+async function loadPaperlessTags() {
+ try {
+ const response = await fetch('/api/paperless/tags', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ // Clear existing options except the first one
+ tagFilter.innerHTML = '<option value="">All Tags</option>';
+
+ // Add tag options
+ if (data.results) {
+ data.results.forEach(tag => {
+ const option = document.createElement('option');
+ option.value = tag.id;
+ option.textContent = tag.name;
+ tagFilter.appendChild(option);
+ });
+ }
+ }
+ } catch (error) {
+ console.error('Error loading Paperless tags:', error);
+ }
+}
+
+/**
+ * Render the list of Paperless documents
+ */
+function renderPaperlessDocuments() {
+ const container = document.getElementById('paperlessDocumentsList');
+
+ if (window.components && window.components.paperless && window.components.paperless.renderDocumentsList) {
+ window.components.paperless.renderDocumentsList(container, currentPaperlessDocuments);
+ return;
+ }
+ // Fallback to existing HTML assembly
+ if (currentPaperlessDocuments.length === 0) {
+ container.innerHTML = `
+ <div class="no-documents-message">
+ <i class="fas fa-file-alt"></i>
+ <h4>No documents found</h4>
+ <p>Try adjusting your search terms or filters.</p>
+ </div>
+ `;
+ return;
+ }
+ const documentsHtml = currentPaperlessDocuments.map(doc => {
+ const createdDate = new Date(doc.created).toLocaleDateString();
+ const fileType = doc.mime_type || 'Unknown';
+ const tags = doc.tags || [];
+ return `
+ <div class="paperless-document-item" data-id="${doc.id}" onclick="selectPaperlessDocument(${doc.id})">
+ <div class="document-title">${escapeHtml(doc.title)}</div>
+ <div class="document-meta">
+ <span><i class="fas fa-calendar"></i> ${createdDate}</span>
+ <span><i class="fas fa-file"></i> ${fileType}</span>
+ ${doc.correspondent ? `<span><i class=\"fas fa-user\"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}
+ </div>
+ ${tags.length > 0 ? `
+ <div class="document-tags">
+ ${tags.map(tag => `<span class=\"document-tag\">${escapeHtml(tag)}</span>`).join('')}
+ </div>
+ ` : ''}
+ </div>
+ `;
+ }).join('');
+ container.innerHTML = documentsHtml;
+}
+
+/**
+ * Select a Paperless document
+ * @param {number} documentId - ID of the document to select
+ */
+function selectPaperlessDocument(documentId) {
+ // Remove previous selection
+ document.querySelectorAll('.paperless-document-item').forEach(item => {
+ item.classList.remove('selected');
+ });
+
+ // Add selection to clicked item
+ const selectedItem = document.querySelector(`[data-id="${documentId}"]`);
+ if (selectedItem) {
+ selectedItem.classList.add('selected');
+ selectedPaperlessDocument = currentPaperlessDocuments.find(doc => doc.id === documentId);
+
+ // Show select button
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ selectBtn.style.display = 'inline-block';
+ selectBtn.onclick = () => confirmPaperlessSelection();
+ }
+}
+
+/**
+ * Confirm the selection of a Paperless document
+ */
+function confirmPaperlessSelection() {
+ if (!selectedPaperlessDocument) return;
+
+ // Update the UI to show the selected document
+ updatePaperlessSelectionUI();
+
+ // Close the modal
+ closePaperlessBrowser();
+}
+
+/**
+ * Update the UI to show the selected Paperless document
+ */
+function updatePaperlessSelectionUI() {
+ if (!selectedPaperlessDocument || !currentDocumentType) return;
+
+ const docName = selectedPaperlessDocument.title;
+ const docId = selectedPaperlessDocument.id;
+
+ // Map document types to their UI elements (only for invoice and manual)
+ const typeMapping = {
+ 'invoice': {
+ selectedDiv: 'selectedInvoiceFromPaperless',
+ hiddenInput: 'selectedPaperlessInvoice'
+ },
+ 'manual': {
+ selectedDiv: 'selectedManualFromPaperless',
+ hiddenInput: 'selectedPaperlessManual'
+ },
+ // Edit modal versions
+ 'edit_invoice': {
+ selectedDiv: 'selectedEditInvoiceFromPaperless',
+ hiddenInput: 'selectedEditPaperlessInvoice'
+ },
+ 'edit_manual': {
+ selectedDiv: 'selectedEditManualFromPaperless',
+ hiddenInput: 'selectedEditPaperlessManual'
+ }
+ };
+
+ const mapping = typeMapping[currentDocumentType];
+ if (!mapping) return;
+
+ // Show the selected document
+ const selectedDiv = document.getElementById(mapping.selectedDiv);
+ if (selectedDiv) {
+ selectedDiv.style.display = 'flex';
+ selectedDiv.querySelector('.selected-doc-name').textContent = docName;
+ }
+
+ // Create or update hidden input to store the document ID
+ let hiddenInput = document.getElementById(mapping.hiddenInput);
+ if (!hiddenInput) {
+ hiddenInput = document.createElement('input');
+ hiddenInput.type = 'hidden';
+ hiddenInput.id = mapping.hiddenInput;
+ hiddenInput.name = mapping.hiddenInput;
+ document.body.appendChild(hiddenInput);
+ }
+ hiddenInput.value = docId;
+}
+
+/**
+ * Clear the Paperless document selection
+ * @param {string} documentType - Type of document to clear
+ */
+function clearPaperlessSelection(documentType) {
+ const typeMapping = {
+ 'invoice': {
+ selectedDiv: 'selectedInvoiceFromPaperless',
+ hiddenInput: 'selectedPaperlessInvoice'
+ },
+ 'manual': {
+ selectedDiv: 'selectedManualFromPaperless',
+ hiddenInput: 'selectedPaperlessManual'
+ },
+ // Edit modal versions
+ 'edit_invoice': {
+ selectedDiv: 'selectedEditInvoiceFromPaperless',
+ hiddenInput: 'selectedEditPaperlessInvoice'
+ },
+ 'edit_manual': {
+ selectedDiv: 'selectedEditManualFromPaperless',
+ hiddenInput: 'selectedEditPaperlessManual'
+ }
+ };
+
+ const mapping = typeMapping[documentType];
+ if (!mapping) return;
+
+ // Hide the selected document display
+ const selectedDiv = document.getElementById(mapping.selectedDiv);
+ if (selectedDiv) {
+ selectedDiv.style.display = 'none';
+ }
+
+ // Clear the hidden input
+ const hiddenInput = document.getElementById(mapping.hiddenInput);
+ if (hiddenInput) {
+ hiddenInput.value = '';
+ }
+}
+
+/**
+ * Close the Paperless browser modal
+ */
+function closePaperlessBrowser() {
+ const modal = document.getElementById('paperlessBrowserModal');
+ modal.classList.remove('active');
+
+ // Reset state
+ selectedPaperlessDocument = null;
+ currentDocumentType = '';
+
+ // Hide select button
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ selectBtn.style.display = 'none';
+}
+
+/**
+ * Change page in Paperless document browser
+ * @param {number} direction - Direction to change page (-1 for previous, 1 for next)
+ */
+function changePage(direction) {
+ const newPage = currentPaperlessPage + direction;
+ if (newPage < 1 || newPage > totalPaperlessPages) return;
+
+ currentPaperlessPage = newPage;
+
+ // Check if we have any active filters
+ const searchInput = document.getElementById('paperlessSearchInput');
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ const hasFilters = (searchInput && searchInput.value.trim()) ||
+ (typeFilter && typeFilter.value) ||
+ (tagFilter && tagFilter.value);
+
+ if (hasFilters) {
+ searchPaperlessDocuments();
+ } else {
+ loadAllPaperlessDocuments();
+ }
+}
+
+/**
+ * Update pagination controls
+ */
+function updatePaperlessPagination() {
+ const paginationDiv = document.getElementById('paperlessPagination');
+ const prevBtn = document.getElementById('prevPageBtn');
+ const nextBtn = document.getElementById('nextPageBtn');
+ const pageInfo = document.getElementById('pageInfo');
+
+ if (totalPaperlessPages <= 1) {
+ paginationDiv.style.display = 'none';
+ return;
+ }
+
+ paginationDiv.style.display = 'flex';
+ prevBtn.disabled = currentPaperlessPage <= 1;
+ nextBtn.disabled = currentPaperlessPage >= totalPaperlessPages;
+ pageInfo.textContent = `Page ${currentPaperlessPage} of ${totalPaperlessPages}`;
+}
+
+/**
+ * Show loading state in Paperless browser
+ */
+function showPaperlessLoading() {
+ const container = document.getElementById('paperlessDocumentsList');
+ if (window.components && window.components.paperless && window.components.paperless.renderLoading) {
+ window.components.paperless.renderLoading(container);
+ return;
+ }
+ container.innerHTML = `
+ <div class="loading-message" style="text-align: center; padding: 40px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading documents...
+ </div>
+ `;
+}
+
+/**
+ * Show error message in Paperless browser
+ * @param {string} message - Error message to display
+ */
+function showPaperlessError(message) {
+ const container = document.getElementById('paperlessDocumentsList');
+ if (window.components && window.components.paperless && window.components.paperless.renderError) {
+ window.components.paperless.renderError(container, message);
+ return;
+ }
+ container.innerHTML = `
+ <div class="no-documents-message">
+ <i class="fas fa-exclamation-triangle"></i>
+ <h4>Error</h4>
+ <p>${escapeHtml(message)}</p>
+ </div>
+ `;
+}
+
+/**
+ * Show/hide Paperless browse sections based on Paperless-ngx availability
+ */
+function togglePaperlessBrowseSections() {
+ const paperlessEnabled = window.paperlessNgxEnabled || false;
+ console.log('[togglePaperlessBrowseSections] Paperless enabled:', paperlessEnabled);
+
+ // List of paperless browse section IDs (only for invoice and manual)
+ const browseSectionIds = [
+ 'invoicePaperlessBrowse',
+ 'manualPaperlessBrowse',
+ 'editInvoicePaperlessBrowse',
+ 'editManualPaperlessBrowse'
+ ];
+
+ let foundSections = 0;
+ browseSectionIds.forEach(id => {
+ const section = document.getElementById(id);
+ if (section) {
+ foundSections++;
+ section.style.display = paperlessEnabled ? 'block' : 'none';
+ console.log(`[togglePaperlessBrowseSections] ${id}: ${paperlessEnabled ? 'shown' : 'hidden'}`);
+ } else {
+ console.warn(`[togglePaperlessBrowseSections] Section not found: ${id}`);
+ }
+ });
+
+ console.log(`[togglePaperlessBrowseSections] Found ${foundSections} of ${browseSectionIds.length} sections`);
+}
+
+// Initialize Paperless browser functionality when DOM is loaded
+document.addEventListener('DOMContentLoaded', function() {
+ // Add event listeners for modal close buttons
+ const paperlessModal = document.getElementById('paperlessBrowserModal');
+ if (paperlessModal) {
+ // Close on backdrop click
+ paperlessModal.addEventListener('click', function(e) {
+ if (e.target === paperlessModal) {
+ closePaperlessBrowser();
+ }
+ });
+
+ // Close on close button click
+ const closeBtn = paperlessModal.querySelector('.close-btn');
+ if (closeBtn) {
+ closeBtn.addEventListener('click', closePaperlessBrowser);
+ }
+
+ // Close on cancel button click - but only the Cancel button, not all secondary buttons
+ const cancelBtn = paperlessModal.querySelector('.modal-footer .btn-secondary');
+ if (cancelBtn) {
+ cancelBtn.addEventListener('click', closePaperlessBrowser);
+ }
+ }
+
+ // Add event listeners for search and filters
+ const searchInput = document.getElementById('paperlessSearchInput');
+ if (searchInput) {
+ // Search on Enter key
+ searchInput.addEventListener('keypress', function(e) {
+ if (e.key === 'Enter') {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ }
+ });
+
+ // Search on input change (with debounce)
+ let searchTimeout;
+ searchInput.addEventListener('input', function() {
+ clearTimeout(searchTimeout);
+ searchTimeout = setTimeout(() => {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ }, 500);
+ });
+ }
+
+ // Add event listeners for filter dropdowns
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ if (typeFilter) {
+ typeFilter.addEventListener('change', function() {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ const tagFilter = document.getElementById('paperlessTagFilter');
+ if (tagFilter) {
+ tagFilter.addEventListener('change', function() {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ // Add event listener for search button
+ const searchBtn = document.getElementById('paperlessSearchBtn');
+ if (searchBtn) {
+ searchBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ // Add event listener for "Show All" button
+ const showAllBtn = document.getElementById('paperlessShowAllBtn');
+ if (showAllBtn) {
+ showAllBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Clear all filters
+ if (searchInput) searchInput.value = '';
+ if (typeFilter) typeFilter.value = '';
+ if (tagFilter) tagFilter.value = '';
+
+ // Reset page and load all documents
+ currentPaperlessPage = 1;
+ paperlessSearchQuery = '';
+ loadAllPaperlessDocuments();
+ });
+ }
+
+ // Toggle browse sections will be handled by initPaperlessNgxIntegration()
+ // togglePaperlessBrowseSections();
+});
+
+// Make functions available globally
+window.openPaperlessBrowser = openPaperlessBrowser;
+window.loadAllPaperlessDocuments = loadAllPaperlessDocuments;
+window.selectPaperlessDocument = selectPaperlessDocument;
+window.clearPaperlessSelection = clearPaperlessSelection;
+window.changePage = changePage;
+window.openPaperlessDocument = openPaperlessDocument;
+window.openSecureFile = openSecureFile;
+
+// ===== END PAPERLESS BROWSER FUNCTIONALITY =====
diff --git a/frontend/settings-new.html b/frontend/src/settings-new.html
similarity index 98%
rename from frontend/settings-new.html
rename to frontend/src/settings-new.html
index 04a4f1a..b2dac88 100644
--- a/frontend/settings-new.html
+++ b/frontend/src/settings-new.html
@@ -2,48 +2,50 @@
<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
+ <script src="/auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js?v=20250119001"></script>
+
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings - Warracker</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
<!-- Load the main site styles first -->
- <link rel="stylesheet" href="style.css?v=20250119004">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Then load settings-specific styles -->
- <link rel="stylesheet" href="settings-styles.css?v=20250119001">
+ <link rel="stylesheet" href="/settings-styles.css?v=20250119001">
<!-- Apply theme immediately -->
- <script src="theme-loader.js?v=20250119001"></script>
+ <script src="/theme-loader.js?v=20250119001"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<!-- Load header fix styles last to override any conflicting styles -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
+
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n Configuration -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Temporary debug script -->
- <script src="js/i18n-debug.js?v=20250119001"></script>
+ <script src="/js/i18n-debug.js?v=20250119001"></script>
<!-- Mobile menu logic isolated to avoid collisions on settings -->
- <script src="mobile-menu.js?v=20250119002" defer></script>
+ <script src="/mobile-menu.js?v=20250119002" defer></script>
<!-- Immediate authentication check script -->
<script>
@@ -1172,14 +1174,14 @@
<div id="toastContainer" class="toast-container"></div>
<!-- Scripts -->
- <script src="auth.js?v=20250119001"></script>
- <script src="settings-new.js?v=20250119001"></script>
+
+ <script src="/settings-new.js?v=20250119001"></script>
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/src/settings-new.js b/frontend/src/settings-new.js
new file mode 100644
index 0000000..f9feb43
--- /dev/null
+++ b/frontend/src/settings-new.js
@@ -0,0 +1,5202 @@
+// DOM Elements
+const darkModeToggle = document.getElementById('darkModeToggle');
+const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
+const languageSelect = document.getElementById('languageSelect');
+const defaultViewSelect = document.getElementById('defaultView');
+const expiringSoonDaysInput = document.getElementById('expiringSoonDays');
+const notificationChannel = document.getElementById('notificationChannel');
+const notificationFrequencySelect = document.getElementById('notificationFrequency');
+const notificationTimeInput = document.getElementById('notificationTime');
+const timezoneSelect = document.getElementById('timezone');
+const saveProfileBtn = document.getElementById('saveProfileBtn');
+const savePreferencesBtn = document.getElementById('savePreferencesBtn');
+const saveNotificationSettingsBtn = document.getElementById('saveNotificationSettingsBtn');
+const changePasswordBtn = document.getElementById('changePasswordBtn');
+const emailSettingsContainer = document.getElementById('emailSettingsContainer');
+const appriseSettingsContainer = document.getElementById('appriseSettingsContainer');
+const userAppriseSettingsContainer = document.getElementById('userAppriseSettingsContainer');
+const passwordChangeForm = document.getElementById('passwordChangeForm');
+const savePasswordBtn = document.getElementById('savePasswordBtn');
+const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
+const deleteAccountBtn = document.getElementById('deleteAccountBtn');
+const deleteAccountModal = document.getElementById('deleteAccountModal');
+const deleteConfirmInput = document.getElementById('deleteConfirmInput');
+const confirmDeleteAccountBtn = document.getElementById('confirmDeleteAccountBtn');
+const passwordSuccessModal = document.getElementById('passwordSuccessModal');
+const loadingContainer = document.getElementById('loadingContainer');
+const toastContainer = document.getElementById('toastContainer');
+const settingsBtn = document.getElementById('settingsBtn');
+const settingsMenu = document.getElementById('settingsMenu');
+const usersTableBody = document.getElementById('usersTableBody');
+
+// Edit User Modal Elements
+const editUserModal = document.getElementById('editUserModal');
+const editUserId = document.getElementById('editUserId');
+const editUsername = document.getElementById('editUsername');
+const editEmail = document.getElementById('editEmail');
+const editUserActive = document.getElementById('editUserActive');
+const editUserAdmin = document.getElementById('editUserAdmin');
+
+// Form fields
+const firstNameInput = document.getElementById('firstName');
+const lastNameInput = document.getElementById('lastName');
+const emailInput = document.getElementById('email');
+const currentPasswordInput = document.getElementById('currentPassword');
+const newPasswordInput = document.getElementById('newPassword');
+const confirmPasswordInput = document.getElementById('confirmPassword');
+
+// DOM Elements for admin section
+const adminSection = document.getElementById('adminSection');
+const refreshUsersBtn = document.getElementById('refreshUsersBtn');
+const checkAdminBtn = document.getElementById('checkAdminBtn');
+const showUsersBtn = document.getElementById('showUsersBtn');
+const testApiBtn = document.getElementById('testApiBtn');
+const triggerNotificationsBtn = document.getElementById('triggerNotificationsBtn');
+const schedulerStatusBtn = document.getElementById('schedulerStatusBtn');
+const registrationEnabled = document.getElementById('registrationEnabled');
+const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
+const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for email base URL
+
+// OIDC Settings DOM Elements
+const oidcEnabledToggle = document.getElementById('oidcEnabled');
+const oidcOnlyModeToggle = document.getElementById('oidcOnlyMode');
+const oidcProviderNameInput = document.getElementById('oidcProviderName');
+const oidcClientIdInput = document.getElementById('oidcClientId');
+const oidcClientSecretInput = document.getElementById('oidcClientSecret');
+const oidcIssuerUrlInput = document.getElementById('oidcIssuerUrl');
+const oidcScopeInput = document.getElementById('oidcScope');
+const oidcAdminGroupInput = document.getElementById('oidcAdminGroup');
+const saveOidcSettingsBtn = document.getElementById('saveOidcSettingsBtn');
+const oidcRestartMessage = document.getElementById('oidcRestartMessage');
+
+// Apprise Settings DOM Elements
+const appriseEnabledToggle = document.getElementById('appriseEnabled');
+const appriseNotificationModeSelect = document.getElementById('appriseNotificationMode');
+const appriseModeDescription = document.getElementById('appriseModeDescription');
+const appriseWarrantyScopeSelect = document.getElementById('appriseWarrantyScope');
+const appriseScopeDescription = document.getElementById('appriseScopeDescription');
+const appriseUrlsTextarea = document.getElementById('appriseUrls');
+const appriseExpirationDaysInput = document.getElementById('appriseExpirationDays');
+const appriseNotificationFrequency = document.getElementById('appriseNotificationFrequency');
+
+// User-specific Apprise settings (in notification settings section)
+const userAppriseNotificationTimeInput = document.getElementById('userAppriseNotificationTime');
+const userAppriseTimezoneSelect = document.getElementById('userAppriseTimezone');
+const userAppriseNotificationFrequency = document.getElementById('userAppriseNotificationFrequency');
+const appriseTitlePrefixInput = document.getElementById('appriseTitlePrefix');
+const appriseTestUrlInput = document.getElementById('appriseTestUrl');
+const saveAppriseSettingsBtn = document.getElementById('saveAppriseSettingsBtn');
+const testAppriseBtn = document.getElementById('testAppriseBtn');
+const validateAppriseUrlBtn = document.getElementById('validateAppriseUrlBtn');
+const triggerAppriseNotificationsBtn = document.getElementById('triggerAppriseNotificationsBtn');
+const appriseStatusBadge = document.getElementById('appriseStatusBadge');
+const appriseUrlsCount = document.getElementById('appriseUrlsCount');
+const currentAppriseExpirationDays = document.getElementById('currentAppriseExpirationDays');
+
+const viewSupportedServicesBtn = document.getElementById('viewSupportedServicesBtn');
+const appriseNotAvailable = document.getElementById('appriseNotAvailable');
+
+const currencySymbolInput = document.getElementById('currencySymbol');
+const currencySymbolSelect = document.getElementById('currencySymbolSelect');
+const currencySymbolCustom = document.getElementById('currencySymbolCustom');
+const currencyPositionSelect = document.getElementById('currencyPositionSelect');
+
+// Add dateFormatSelect near other DOM element declarations if not already there
+const dateFormatSelect = document.getElementById('dateFormat');
+
+// Paperless-ngx Settings DOM Elements
+const paperlessEnabledToggle = document.getElementById('paperlessEnabled');
+const paperlessUrlInput = document.getElementById('paperlessUrl');
+const paperlessApiTokenInput = document.getElementById('paperlessApiToken');
+const paperlessViewInAppToggle = document.getElementById('paperlessViewInApp');
+const paperlessSettingsContainer = document.getElementById('paperlessSettingsContainer');
+const testPaperlessConnectionBtn = document.getElementById('testPaperlessConnectionBtn');
+const savePaperlessSettingsBtn = document.getElementById('savePaperlessSettingsBtn');
+const paperlessConnectionStatus = document.getElementById('paperlessConnectionStatus');
+
+// Global variable to store currencies data for currency code lookup
+let globalCurrenciesData = [];
+
+/**
+ * Load currencies from the API and populate the currency dropdown
+ */
+async function loadCurrenciesForSettings() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ const response = await fetch('/api/currencies', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Store currencies data globally for currency code lookup
+ globalCurrenciesData = currencies;
+
+ // Populate currency symbol dropdown
+ if (currencySymbolSelect) {
+ // Clear existing options
+ currencySymbolSelect.innerHTML = '';
+
+ // Add currencies from API
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.symbol;
+ option.textContent = `${currency.symbol} (${currency.code} - ${currency.name})`;
+ currencySymbolSelect.appendChild(option);
+ });
+
+ // Add "Other..." option at the end
+ const otherOption = document.createElement('option');
+ otherOption.value = 'other';
+ otherOption.textContent = 'Other...';
+ currencySymbolSelect.appendChild(otherOption);
+ }
+
+ console.log('Currencies loaded successfully for settings page');
+ } catch (error) {
+ console.error('Error loading currencies for settings:', error);
+ // Fallback to default currencies if loading fails
+ if (currencySymbolSelect) {
+ currencySymbolSelect.innerHTML = `
+ <option value="$">$ (USD - US Dollar)</option>
+ <option value="€">€ (EUR - Euro)</option>
+ <option value="£">£ (GBP - British Pound)</option>
+ <option value="¥">¥ (JPY - Japanese Yen)</option>
+ <option value="other">Other...</option>
+ `;
+ }
+ }
+}
+
+/**
+ * Initialize language selector
+ */
+function initLanguageSelector() {
+ console.log('initLanguageSelector called');
+ console.log('languageSelect element exists:', !!languageSelect);
+
+ if (!languageSelect) {
+ console.error('Language select element not found!');
+ return;
+ }
+
+ // Check if already initialized
+ if (languageSelect.hasAttribute('data-initialized')) {
+ console.log('Language selector already initialized, skipping');
+ return;
+ }
+
+ // Get current language
+ const currentLang = window.i18n?.getCurrentLanguage() || 'en';
+ console.log('Setting language selector to current language:', currentLang);
+ languageSelect.value = currentLang;
+
+ // Mark as initialized
+ languageSelect.setAttribute('data-initialized', 'true');
+
+ // Add event listener for language changes
+ languageSelect.addEventListener('change', async function() {
+ const selectedLanguage = this.value;
+ console.log('Language changed to:', selectedLanguage);
+
+ if (window.i18n?.changeLanguage) {
+ try {
+ showToast('Changing language...', 'info');
+ await window.i18n.changeLanguage(selectedLanguage);
+ showToast(window.t('messages.saved') || 'Language changed successfully', 'success');
+
+ // Reload page after a short delay to apply all translations
+ setTimeout(() => {
+ window.location.reload();
+ }, 1000);
+ } catch (error) {
+ console.error('Failed to change language:', error);
+ showToast(window.t('messages.error') || 'Failed to change language', 'error');
+ }
+ } else {
+ console.warn('i18n changeLanguage function not available');
+ showToast('Language system not ready. Please try again.', 'error');
+ }
+ });
+
+ console.log('Language selector initialized successfully with current language:', currentLang);
+}
+
+/**
+ * Initialize language selector after i18n is ready
+ */
+function initLanguageSelectorWhenReady() {
+ console.log('initLanguageSelectorWhenReady called');
+ console.log('window.i18n available:', !!window.i18n);
+ console.log('window.i18n.getCurrentLanguage available:', !!(window.i18n && window.i18n.getCurrentLanguage));
+
+ if (window.i18n && window.i18n.getCurrentLanguage) {
+ // i18n is already ready
+ console.log('i18n already ready, initializing language selector');
+ initLanguageSelector();
+ } else {
+ // Wait for i18n to be ready
+ console.log('Waiting for i18n to be ready...');
+ window.addEventListener('i18nReady', function(event) {
+ console.log('i18n is now ready, initializing language selector');
+ initLanguageSelector();
+ }, { once: true }); // Use once: true to ensure this only runs once
+
+ // Also try again after a short delay as backup
+ setTimeout(() => {
+ if (window.i18n && window.i18n.getCurrentLanguage && !languageSelect.hasAttribute('data-initialized')) {
+ console.log('Backup initialization: i18n ready, initializing language selector');
+ initLanguageSelector();
+ }
+ }, 2000);
+ }
+}
+
+/**
+ * Set theme (dark/light) - Unified and persistent
+ * @param {boolean} isDark - Whether to use dark mode
+ */
+function setTheme(isDark) {
+ const theme = isDark ? 'dark' : 'light';
+ // Apply theme to document
+ document.documentElement.setAttribute('data-theme', theme);
+ if (isDark) {
+ document.body.classList.add('dark-mode');
+ } else {
+ document.body.classList.remove('dark-mode');
+ }
+ // Save to localStorage (single source of truth)
+ localStorage.setItem('darkMode', isDark);
+ // Sync both toggles if present
+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
+ darkModeToggle.checked = isDark;
+ }
+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDark;
+ }
+ // Also update user_preferences.theme for backward compatibility
+ try {
+ let userPrefs = {};
+ const storedPrefs = localStorage.getItem('user_preferences');
+ if (storedPrefs) {
+ userPrefs = JSON.parse(storedPrefs);
+ }
+ userPrefs.theme = theme;
+ localStorage.setItem('user_preferences', JSON.stringify(userPrefs));
+ } catch (e) {
+ console.error('Error updating theme in user_preferences:', e);
+ }
+}
+
+/**
+ * Initialize dark mode toggle and synchronize state
+ */
+function initDarkModeToggle() {
+ // Always check the single source of truth in localStorage (fallback)
+ const isDarkMode = localStorage.getItem('darkMode') === 'true';
+ // Apply theme to DOM if not already set
+ document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');
+ document.body.classList.toggle('dark-mode', isDarkMode);
+ // Sync both toggles and add unified handler
+ const syncToggles = (val) => {
+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) darkModeToggle.checked = val;
+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) darkModeToggleSetting.checked = val;
+ };
+ syncToggles(isDarkMode);
+ // Handler to update theme, localStorage, backend
+ const handleToggle = async function(checked) {
+ setTheme(checked);
+ syncToggles(checked);
+ // Save to backend if authenticated
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ let prefs = {};
+ const storedPrefs = localStorage.getItem('user_preferences');
+ if (storedPrefs) prefs = JSON.parse(storedPrefs);
+ prefs.theme = checked ? 'dark' : 'light';
+ await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(prefs)
+ });
+ } catch (e) {
+ console.warn('Failed to save dark mode to backend:', e);
+ }
+ }
+ };
+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
+ darkModeToggle.onchange = function() { handleToggle(this.checked); };
+ }
+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
+ darkModeToggleSetting.onchange = function() { handleToggle(this.checked); };
+ }
+}
+
+// Initialize settings page
+document.addEventListener('DOMContentLoaded', function() {
+ console.log('DOM fully loaded, initializing settings page');
+
+ // DEBUG: Check current user data
+ const debugCurrentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ console.log('DEBUG: Current user data:', debugCurrentUser);
+
+ // Also listen for i18nReady event to ensure language selector gets initialized
+ console.log('Setting up i18nReady event listener from DOMContentLoaded');
+ window.addEventListener('i18nReady', function(event) {
+ console.log('i18nReady event received in DOMContentLoaded listener, initializing language selector');
+ // Small delay to ensure all DOM elements are ready
+ setTimeout(() => {
+ if (!document.getElementById('languageSelect').hasAttribute('data-initialized')) {
+ console.log('Language selector not yet initialized, doing it now');
+ initLanguageSelector();
+ } else {
+ console.log('Language selector already initialized');
+ }
+ }, 100);
+ }, { once: true });
+ if (debugCurrentUser) {
+ console.log('DEBUG: User has is_owner field:', 'is_owner' in debugCurrentUser, 'Value:', debugCurrentUser.is_owner);
+ }
+
+ // Set up event listeners
+ setupEventListeners(); // Ensure this doesn't also try to init settings menu
+
+ // Set up direct event listeners for critical elements
+ setupCriticalEventListeners();
+
+ // Make functions globally accessible if needed
+ window.deleteUser = deleteUser;
+ window.directDeleteUserAPI = directDeleteUserAPI;
+
+ // Add global click handlers if needed
+ // ... (existing delete button handler logic) ...
+
+ // Initialize dark mode toggle
+ initDarkModeToggle();
+ // Clear dark mode preference on logout for privacy
+ if (window.auth && window.auth.onLogout) {
+ window.auth.onLogout(() => {
+ localStorage.removeItem('darkMode');
+ });
+ }
+
+ // REMOVED initSettingsMenu() call - Handled by auth.js
+
+ // Load initial data for the settings page
+ loadUserData();
+ loadTimezones().then(() => loadPreferences()).catch(err => {
+ console.error('Error loading timezones/prefs:', err);
+ loadPreferences(); // Try loading prefs anyway
+ });
+
+ // --- ADD THIS LINE TO INITIALIZE MODALS ---
+ initModals();
+
+ // Initialize collapsible cards
+ initCollapsibleCards();
+
+ // Load admin-only settings if user is admin
+ // Note: These will also be loaded later in loadUserData() with proper checks
+ // This is a redundant call that should be conditional
+ const currentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ if (currentUser && currentUser.is_admin) {
+ // Load site settings (for admins) - includes OIDC settings
+ loadSiteSettings();
+
+ // Load Apprise settings
+ loadAppriseSettings();
+
+ // Load Apprise site settings (also loads overall Apprise settings)
+ loadAppriseSiteSettings();
+
+ // Initialize ownership management if user is owner
+ if (currentUser.is_owner) {
+ console.log('DEBUG: User is owner, initializing ownership management');
+ setTimeout(() => {
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ console.log('DEBUG: Ownership section made visible');
+ }
+ // Don't load users here - wait for modal to open
+ console.log('DEBUG: Ownership management initialized, users will load when modal opens');
+ }, 500); // Wait for DOM to be ready
+ }
+ } else {
+ console.log('User is not admin, skipping admin-only settings load during initialization');
+ }
+
+ // Setup Apprise event listeners
+ setupAppriseEventListeners();
+
+ // Audit Trail button handler (admin section)
+ const viewAuditTrailBtn = document.getElementById('viewAuditTrailBtn');
+ if (viewAuditTrailBtn) {
+ viewAuditTrailBtn.addEventListener('click', loadAndDisplayAuditTrail);
+ }
+
+ // Initialize delete button handling
+ setupDeleteButton();
+});
+
+/**
+ * Initialize the settings page
+ */
+function initPage() {
+ console.log('Initializing settings page');
+
+ // Initialize language selector when i18n is ready
+ initLanguageSelectorWhenReady();
+
+ // Check authentication
+ if (window.auth) {
+ window.auth.checkAuthState();
+
+ // Redirect to login if not authenticated
+ if (!window.auth.isAuthenticated()) {
+ console.log('User not authenticated, redirecting to login');
+ window.location.href = 'login.html';
+ return;
+ }
+ } else {
+ // Auth module not loaded
+ console.error('Auth module not loaded');
+ window.location.href = 'login.html';
+ return;
+ }
+
+ // Load user data and preferences with error handling
+ try {
+ // First load timezones, then load preferences to ensure correct order
+ loadTimezones().then(() => {
+ console.log('Timezones loaded, now loading preferences');
+ loadPreferences();
+ }).catch(err => {
+ console.error('Error loading timezones:', err);
+ // Still try to load preferences even if timezones fail
+ loadPreferences();
+ });
+
+ loadUserData().catch(err => {
+ console.error('Error loading user data:', err);
+ // Continue with page initialization even if user data fails
+ });
+ } catch (err) {
+ console.error('Error during page initialization:', err);
+ // Continue despite errors to allow basic functionality
+ }
+
+ // Fix for settings button - not needed anymore as we've removed it
+ if (settingsBtn) {
+ console.log('Settings button found, adding event listener');
+ settingsBtn.addEventListener('click', function(e) {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ console.log('Settings button clicked, menu toggled');
+ });
+
+ // Close settings menu when clicking outside
+ document.addEventListener('click', function(e) {
+ if (settingsMenu.classList.contains('active') &&
+ !settingsMenu.contains(e.target) &&
+ !settingsBtn.contains(e.target)) {
+ settingsMenu.classList.remove('active');
+ }
+ });
+ } else {
+ console.log('Settings button not found - this is expected after UI update');
+ }
+
+ console.log('Settings page initialization complete');
+}
+
+// ============================
+// Audit Trail functions
+// ============================
+
+async function loadAndDisplayAuditTrail() {
+ const displayArea = document.getElementById('auditTrailDisplay');
+ const loadingIndicator = document.getElementById('auditTrailLoading');
+ const table = document.getElementById('auditTrailTable');
+ const tableBody = document.getElementById('auditTrailTableBody');
+
+ if (!displayArea || !loadingIndicator || !table || !tableBody) return;
+
+ displayArea.style.display = 'block';
+ loadingIndicator.style.display = 'block';
+ table.style.display = 'none';
+ tableBody.innerHTML = '';
+
+ try {
+ const token = window.auth && window.auth.getToken ? window.auth.getToken() : localStorage.getItem('auth_token');
+ const response = await fetch('/api/admin/audit-trail?limit=200', {
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to fetch audit log');
+ }
+
+ const logs = await response.json();
+ renderAuditTrail(logs);
+
+ } catch (error) {
+ console.error('Error loading audit trail:', error);
+ loadingIndicator.textContent = 'Error loading audit trail.';
+ }
+}
+
+function renderAuditTrail(logs) {
+ const loadingIndicator = document.getElementById('auditTrailLoading');
+ const table = document.getElementById('auditTrailTable');
+ const tableBody = document.getElementById('auditTrailTableBody');
+
+ loadingIndicator.style.display = 'none';
+
+ if (!Array.isArray(logs) || logs.length === 0) {
+ tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No audit records found.</td></tr>';
+ } else {
+ logs.forEach(log => {
+ const row = tableBody.insertRow();
+ const timestamp = log.timestamp ? new Date(log.timestamp).toLocaleString() : '';
+ const username = (log.username || 'System');
+ const action = (log.action || '');
+ const details = log.details ? escapeHtmlSafe(log.details) : 'N/A';
+
+ row.innerHTML = `
+ <td title='${log.ip_address || ''}'>${timestamp}</td>
+ <td>${escapeHtmlSafe(username)}</td>
+ <td><span class='badge'>${escapeHtmlSafe(action)}</span></td>
+ <td style='white-space: pre-wrap; word-break: break-word;'>${details}</td>
+ `;
+ });
+ }
+ table.style.display = 'table';
+}
+
+function escapeHtmlSafe(text) {
+ if (typeof text !== 'string') return text;
+ const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
+ return text.replace(/[&<>"']/g, m => map[m]);
+}
+
+/**
+ * Setup critical event listeners that must work for core functionality
+ */
+function setupCriticalEventListeners() {
+ console.log('Setting up critical event listeners');
+
+ // Set up delete user modal close buttons
+ const closeModalButtons = document.querySelectorAll('.close-modal');
+ closeModalButtons.forEach(button => {
+ button.addEventListener('click', function() {
+ closeAllModals();
+ });
+ });
+
+ // Set up delete user button in the modal
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (confirmDeleteUserBtn) {
+ console.log('Setting up confirmDeleteUserBtn');
+
+ // Add multiple event handlers for redundancy
+ confirmDeleteUserBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via addEventListener in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+
+ confirmDeleteUserBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via onclick in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ };
+ }
+
+ // Set up direct delete link
+ const directDeleteLink = document.getElementById('directDeleteLink');
+ if (directDeleteLink) {
+ directDeleteLink.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct delete link clicked in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+ }
+
+ // Set up direct API link
+ const directAPILink = document.getElementById('directAPILink');
+ if (directAPILink) {
+ directAPILink.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct API link clicked in setupCriticalEventListeners');
+ const userId = window.currentDeleteUserId ||
+ (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null);
+ directDeleteUserAPI(userId);
+ return false;
+ });
+ }
+
+ // Set up delete user form
+ const deleteUserForm = document.getElementById('deleteUserForm');
+ if (deleteUserForm) {
+ deleteUserForm.addEventListener('submit', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete user form submitted in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+ }
+}
+
+/**
+ * Load user data from localStorage and API
+ */
+async function loadUserData() {
+ showLoading();
+ // Get the new display elements
+ const userNameDisplay = document.getElementById('currentUserNameDisplay');
+ const userEmailDisplay = document.getElementById('currentUserEmailDisplay');
+
+ try {
+ // Get user from localStorage first
+ const currentUser = window.auth.getCurrentUser();
+
+ if (currentUser) {
+ // Populate form fields
+ if (firstNameInput) firstNameInput.value = currentUser.first_name || ''; // Add null checks
+ if (lastNameInput) lastNameInput.value = currentUser.last_name || ''; // Add null checks
+ if (emailInput) emailInput.value = currentUser.email || ''; // Add null checks
+
+ // --- UPDATE DISPLAY ELEMENT (Initial Load) ---
+ let displayName;
+ if (currentUser.first_name && currentUser.last_name) {
+ displayName = `${currentUser.first_name} ${currentUser.last_name}`;
+ } else {
+ displayName = currentUser.username || 'User';
+ }
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ if (userEmailDisplay) userEmailDisplay.textContent = currentUser.email || 'N/A';
+
+ if (currentUser.oidc_managed) {
+ if (firstNameInput) firstNameInput.disabled = true;
+ if (lastNameInput) lastNameInput.disabled = true;
+ if (emailInput) emailInput.disabled = true;
+ if (saveProfileBtn) saveProfileBtn.style.display = 'none';
+ userEditDesc = document.querySelector('#currentUserInfoDisplay > p > strong')
+ if (userEditDesc) {
+ userEditDesc.setAttribute('data-i18n', 'settings.current_user_oidc')
+ userEditDesc.textContent = 'OIDC managed profile for:'
+ }
+ securitySection = document.getElementById('securitySection');
+ if (securitySection) securitySection.style.display = 'none';
+ }
+ // --- END UPDATE ---
+
+ // Admin section visibility will be determined after API call
+ }
+
+ // Fetch fresh user data from API
+ try {
+ const response = await fetch('/api/auth/user', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ const userData = await response.json();
+
+ // Update form fields with fresh data
+ if (firstNameInput) firstNameInput.value = userData.first_name || ''; // Add null checks
+ if (lastNameInput) lastNameInput.value = userData.last_name || ''; // Add null checks
+ if (emailInput) emailInput.value = userData.email || ''; // Add null checks
+
+ // --- UPDATE DISPLAY ELEMENT (After API Load) ---
+ let displayName;
+ if (userData.first_name && userData.last_name) {
+ displayName = `${userData.first_name} ${userData.last_name}`;
+ } else {
+ displayName = userData.username || 'User';
+ }
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ if (userEmailDisplay) userEmailDisplay.textContent = userData.email || 'N/A';
+ // --- END UPDATE ---
+
+ // Show admin section if user is admin and load admin-specific data
+ if (userData.is_admin) {
+ if (adminSection) {
+ adminSection.style.display = 'block';
+ // Ensure admin-specific data is loaded AFTER section is visible
+ if (usersTableBody) loadUsers();
+ // Check for site settings elements directly to avoid cache timing issues
+ const hasRegistrationToggle = document.getElementById('registrationEnabled');
+ const hasOidcToggle = document.getElementById('oidcEnabled');
+ if (hasRegistrationToggle || hasOidcToggle) {
+ console.log('Admin settings elements found, loading site settings...');
+ loadSiteSettings();
+ } else {
+ console.warn('Admin settings elements not found - this might be a timing/cache issue');
+ }
+ }
+ } else {
+ if (adminSection) adminSection.style.display = 'none';
+ }
+
+ // Update localStorage ONLY if data has changed
+ const currentUser = window.auth.getCurrentUser();
+ let first_name = userData.first_name;
+ let last_name = userData.last_name;
+ if (!last_name) first_name = ''; // Reset first name if last name is empty
+
+ const updatedUser = {
+ ...(currentUser || {}), // Preserve existing fields
+ first_name, // Update first name
+ last_name, // Update last name
+ // Preserve other essential fields from fetched data if currentUser was null
+ email: currentUser ? currentUser.email : userData.email,
+ username: currentUser ? currentUser.username : userData.username,
+ is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
+ id: currentUser ? currentUser.id : userData.id
+ };
+
+ // Convert both to JSON strings for reliable comparison
+ const currentUserString = JSON.stringify(currentUser);
+ const updatedUserString = JSON.stringify(updatedUser);
+
+ if (currentUserString !== updatedUserString) {
+ console.log('User data changed, updating localStorage.');
+ localStorage.setItem('user_info', updatedUserString);
+ } else {
+ console.log('User data from API matches localStorage, skipping update.');
+ }
+ // localStorage.setItem('user_info', JSON.stringify(updatedUser)); // OLD LINE
+ } else {
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+ console.warn('API error fetching user data:', errorData.message);
+ if (!currentUser) {
+ showToast(errorData.message || 'Failed to load fresh user data', 'warning');
+ }
+ }
+ } catch (apiError) {
+ console.warn('API error, using localStorage data:', apiError);
+ if (!currentUser) {
+ showToast('Could not connect to fetch user data. Displaying cached info.', 'warning');
+ }
+ }
+ } catch (error) {
+ console.error('Error loading user data:', error);
+ showToast('Failed to load user data. Please try again.', 'error');
+ if (userNameDisplay) userNameDisplay.textContent = 'Error';
+ if (userEmailDisplay) userEmailDisplay.textContent = 'Error';
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Get current user type (admin or user)
+ * @returns {string} 'admin' or 'user'
+ */
+function getUserType() {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.is_admin === true ? 'admin' : 'user';
+ } catch (e) {
+ console.error('Error determining user type:', e);
+ return 'user'; // Default to user if we can't determine
+ }
+}
+
+/**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+}
+
+// Prevent multiple simultaneous preference loads
+let isLoadingPreferences = false;
+
+/**
+ * Load user preferences
+ */
+async function loadPreferences() {
+ // Prevent multiple simultaneous loads
+ if (isLoadingPreferences) {
+ console.log('Preferences already loading, skipping duplicate call');
+ return;
+ }
+
+ isLoadingPreferences = true;
+ console.log('Loading preferences...');
+ const prefix = getPreferenceKeyPrefix();
+ console.log('Loading preferences with prefix:', prefix);
+
+ let apiPrefs = null;
+
+ // FIXED: Load all preferences from API first, then apply to UI
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+ if (response.ok) {
+ apiPrefs = await response.json();
+ console.log('API preferences loaded:', apiPrefs);
+
+ // Apply theme from API immediately (highest priority)
+ if (apiPrefs && apiPrefs.theme) {
+ const isDark = apiPrefs.theme === 'dark';
+ console.log('Applying theme from API:', apiPrefs.theme, 'isDark:', isDark);
+ setTheme(isDark);
+ // Sync localStorage to match API
+ localStorage.setItem('darkMode', isDark);
+ // Ensure the dark mode toggle reflects the API setting
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDark;
+ console.log('Synced dark mode toggle to API value:', isDark);
+ }
+ } else {
+ console.log('No theme in API preferences, using localStorage fallback');
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = storedDarkMode;
+ }
+ }
+ } else {
+ console.warn('API preferences request failed, using localStorage');
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ }
+ } catch (e) {
+ console.warn('Failed to load preferences from backend:', e);
+ // Fallback to localStorage
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ }
+ } else {
+ console.log('Not authenticated, using localStorage for theme');
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ }
+ // --- Load Date Format --- Add this section
+ const storedDateFormat = localStorage.getItem('dateFormat');
+ if (storedDateFormat && dateFormatSelect) {
+ dateFormatSelect.value = storedDateFormat;
+ console.log(`Loaded dateFormat from localStorage: ${storedDateFormat}`);
+ } else if (dateFormatSelect) {
+ dateFormatSelect.value = 'MDY'; // Default if not found
+ console.log('dateFormat not found in localStorage, defaulting to MDY');
+ }
+ // --- End Date Format Section ---
+
+ // Default View
+ const storedView = localStorage.getItem(`${prefix}defaultView`);
+ if (storedView && defaultViewSelect) {
+ defaultViewSelect.value = storedView;
+ console.log(`Loaded default view from ${prefix}defaultView: ${storedView}`);
+ } else if (defaultViewSelect) {
+ defaultViewSelect.value = 'grid'; // Default
+ console.log(`${prefix}defaultView not found, defaulting view to grid`);
+ }
+
+ // Currency Symbol - Load stored preference first
+ const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`);
+
+ // Load currencies from API and set the saved preference
+ await loadCurrenciesForSettings();
+
+ if (storedCurrency) {
+ if (currencySymbolSelect) {
+ // Check if the stored symbol is a standard option
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === storedCurrency);
+ if (standardOption) {
+ currencySymbolSelect.value = storedCurrency;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log(`Set currency dropdown to stored value: ${storedCurrency}`);
+ } else {
+ // It's a custom symbol
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = storedCurrency;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ console.log(`Set currency to custom value: ${storedCurrency}`);
+ }
+ console.log(`Loaded currency symbol from ${prefix}currencySymbol: ${storedCurrency}`);
+ }
+ } else {
+ // Default to '$' if nothing stored
+ if (currencySymbolSelect) currencySymbolSelect.value = '$';
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log(`${prefix}currencySymbol not found, defaulting to $`);
+ }
+
+ // Currency Position
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (storedCurrencyPosition && currencyPositionSelect) {
+ currencyPositionSelect.value = storedCurrencyPosition;
+ console.log(`Loaded currency position from ${prefix}currencyPosition: ${storedCurrencyPosition}`);
+ } else if (currencyPositionSelect) {
+ currencyPositionSelect.value = 'left'; // Default
+ console.log(`${prefix}currencyPosition not found, defaulting to left`);
+ }
+
+ // Expiring Soon Days
+ const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`);
+ if (storedExpiringDays && expiringSoonDaysInput) {
+ expiringSoonDaysInput.value = storedExpiringDays;
+ console.log(`Loaded expiring soon days from ${prefix}expiringSoonDays: ${storedExpiringDays}`);
+ } else if (expiringSoonDaysInput) {
+ expiringSoonDaysInput.value = 30; // Default
+ console.log(`${prefix}expiringSoonDays not found, defaulting to 30`);
+ }
+
+ // Paperless View in App
+ const storedPaperlessViewInApp = localStorage.getItem(`${prefix}paperlessViewInApp`);
+ if (storedPaperlessViewInApp !== null && paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = storedPaperlessViewInApp === 'true';
+ console.log(`Loaded Paperless view in app from ${prefix}paperlessViewInApp: ${storedPaperlessViewInApp}`);
+ } else if (paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = false; // Default
+ console.log(`${prefix}paperlessViewInApp not found, defaulting to false`);
+ }
+
+ // Apply API preferences to form elements (apiPrefs already loaded above)
+ if (apiPrefs) {
+ console.log('Applying API preferences to form elements:', apiPrefs);
+
+ // Update UI elements with API data where available
+ if (apiPrefs.default_view && defaultViewSelect) {
+ // Only update if different from localStorage value (or if localStorage was empty)
+ const storedView = localStorage.getItem(`${prefix}defaultView`) || 'grid'; // Default if null
+ if (apiPrefs.default_view !== storedView) {
+ console.log(`API default_view (${apiPrefs.default_view}) differs from localStorage (${storedView}). Updating UI.`);
+ defaultViewSelect.value = apiPrefs.default_view;
+ }
+ }
+ // --- MODIFIED CURRENCY SYMBOL HANDLING ---
+ const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`); // Get localStorage value again for comparison
+ if (apiPrefs.currency_symbol && currencySymbolSelect) {
+ // Only update UI from API if the API value is different from what was in localStorage
+ // Or if localStorage didn't have a value initially
+ if (!storedCurrency || apiPrefs.currency_symbol !== storedCurrency) {
+ console.log(`API currency_symbol (${apiPrefs.currency_symbol}) differs from localStorage (${storedCurrency}). Updating UI.`);
+ // Logic to handle standard vs custom symbol from API
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === apiPrefs.currency_symbol);
+ if (standardOption) {
+ currencySymbolSelect.value = apiPrefs.currency_symbol;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ } else {
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = apiPrefs.currency_symbol;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ }
+ } else {
+ console.log(`API currency_symbol (${apiPrefs.currency_symbol}) matches localStorage (${storedCurrency}). Skipping UI update.`);
+ }
+ }
+ // --- END MODIFIED CURRENCY SYMBOL HANDLING ---
+
+ // --- CURRENCY POSITION HANDLING ---
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (apiPrefs.currency_position && currencyPositionSelect) {
+ if (!storedCurrencyPosition || apiPrefs.currency_position !== storedCurrencyPosition) {
+ console.log(`API currency_position (${apiPrefs.currency_position}) differs from localStorage (${storedCurrencyPosition}). Updating UI.`);
+ currencyPositionSelect.value = apiPrefs.currency_position;
+ } else {
+ console.log(`API currency_position (${apiPrefs.currency_position}) matches localStorage (${storedCurrencyPosition}). Skipping UI update.`);
+ }
+ }
+ // --- END CURRENCY POSITION HANDLING ---
+ if (apiPrefs.expiring_soon_days && expiringSoonDaysInput) {
+ // Only update if different from localStorage value (or if localStorage was empty)
+ const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`) || '30'; // Default if null
+ if (String(apiPrefs.expiring_soon_days) !== storedExpiringDays) {
+ console.log(`API expiring_soon_days (${apiPrefs.expiring_soon_days}) differs from localStorage (${storedExpiringDays}). Updating UI.`);
+ expiringSoonDaysInput.value = apiPrefs.expiring_soon_days;
+ }
+ }
+
+ // --- Update Date Format from API Prefs --- Add this check
+ const storedDateFormat = localStorage.getItem('dateFormat') || 'MDY'; // Default if null
+ if (apiPrefs.date_format && dateFormatSelect) {
+ if (apiPrefs.date_format !== storedDateFormat) {
+ console.log(`API date_format (${apiPrefs.date_format}) differs from localStorage (${storedDateFormat}). Updating UI.`);
+ dateFormatSelect.value = apiPrefs.date_format;
+ }
+ }
+ // --- End Date Format Check ---
+
+ // --- Update Paperless View in App from API Prefs ---
+ if (apiPrefs.paperless_view_in_app !== undefined && paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = apiPrefs.paperless_view_in_app;
+ console.log(`Set Paperless view in app from API: ${apiPrefs.paperless_view_in_app}`);
+ }
+ // --- End Paperless View in App from API Prefs ---
+
+ // Update Email Settings from API
+ if (notificationChannel) {
+ const channelValue = apiPrefs.notification_channel || 'email'; // Default to email if not present
+ notificationChannel.value = channelValue;
+ toggleNotificationSettings(channelValue);
+ console.log('Set notification channel to:', channelValue);
+ }
+ if (notificationFrequencySelect && apiPrefs.notification_frequency) {
+ notificationFrequencySelect.value = apiPrefs.notification_frequency;
+ }
+ if (notificationTimeInput && apiPrefs.notification_time) {
+ notificationTimeInput.value = apiPrefs.notification_time.substring(0, 5); // HH:MM format
+ }
+ // Admin Apprise settings (in Apprise card)
+ if (appriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ appriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
+
+ // User-specific Apprise settings (in notification settings section)
+ if (userAppriseNotificationTimeInput && apiPrefs.apprise_notification_time) {
+ userAppriseNotificationTimeInput.value = apiPrefs.apprise_notification_time.substring(0, 5);
+ }
+ if (userAppriseTimezoneSelect && apiPrefs.apprise_timezone) {
+ if (Array.from(userAppriseTimezoneSelect.options).some(option => option.value === apiPrefs.apprise_timezone)) {
+ userAppriseTimezoneSelect.value = apiPrefs.apprise_timezone;
+ } else {
+ console.warn(`User Apprise timezone '${apiPrefs.apprise_timezone}' from API not found in dropdown.`);
+ }
+ }
+ if (userAppriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ userAppriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
+
+ // Update Apprise timezone display
+ updateAppriseTimezoneDisplay(apiPrefs.timezone);
+ // Load and set timezone from API
+ if (timezoneSelect && apiPrefs.timezone) {
+ console.log('API provided timezone:', apiPrefs.timezone);
+ // Ensure the option exists before setting
+ if (Array.from(timezoneSelect.options).some(option => option.value === apiPrefs.timezone)) {
+ timezoneSelect.value = apiPrefs.timezone;
+ console.log('Applied timezone from API:', timezoneSelect.value, 'Current select value:', timezoneSelect.value);
+
+ // Update Apprise timezone display when timezone is loaded
+ updateAppriseTimezoneDisplay(apiPrefs.timezone);
+ } else {
+ console.warn(`Timezone '${apiPrefs.timezone}' from API not found in dropdown.`);
+ }
+ } else {
+ console.log('No timezone preference found in API or timezone select element missing.');
+ }
+
+ // Load and set language preference
+ if (apiPrefs.preferred_language && languageSelect) {
+ console.log('API provided language:', apiPrefs.preferred_language);
+ // Ensure the option exists before setting
+ if (Array.from(languageSelect.options).some(option => option.value === apiPrefs.preferred_language)) {
+ languageSelect.value = apiPrefs.preferred_language;
+ console.log('Applied language from API:', languageSelect.value);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (apiPrefs.preferred_language !== currentLang) {
+ console.log(`Language preference (${apiPrefs.preferred_language}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(apiPrefs.preferred_language).catch(error => {
+ console.error('Failed to change language from API preference:', error);
+ });
+ }
+ }
+ } else {
+ console.warn(`Language '${apiPrefs.preferred_language}' from API not found in dropdown.`);
+ }
+ } else {
+ // Load from localStorage if no API preference
+ const storedLanguage = localStorage.getItem('preferred_language') || 'en';
+ if (languageSelect) {
+ languageSelect.value = storedLanguage;
+ console.log('Applied language from localStorage:', storedLanguage);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (storedLanguage !== currentLang) {
+ console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(storedLanguage).catch(error => {
+ console.error('Failed to change language from localStorage:', error);
+ });
+ }
+ }
+ }
+ }
+ } else {
+ // No API preferences, load language from localStorage
+ const storedLanguage = localStorage.getItem('preferred_language') || 'en';
+ if (languageSelect) {
+ languageSelect.value = storedLanguage;
+ console.log('Applied language from localStorage (no API):', storedLanguage);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (storedLanguage !== currentLang) {
+ console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(storedLanguage).catch(error => {
+ console.error('Failed to change language from localStorage (no API):', error);
+ });
+ }
+ }
+ }
+ }
+
+ // Reset the loading flag
+ isLoadingPreferences = false;
+ console.log('Preferences loading completed');
+}
+
+/**
+ * Update the Apprise timezone display to show which timezone will be used
+ */
+function updateAppriseTimezoneDisplay(timezone) {
+ const appriseTimezoneDisplay = document.getElementById('appriseTimezoneDisplay');
+ if (appriseTimezoneDisplay) {
+ if (timezone) {
+ appriseTimezoneDisplay.textContent = `(using timezone: ${timezone})`;
+ appriseTimezoneDisplay.style.display = 'inline';
+ } else {
+ appriseTimezoneDisplay.textContent = '(timezone not set)';
+ appriseTimezoneDisplay.style.display = 'inline';
+ }
+ }
+}
+
+/**
+ * Setup event listeners for the settings page
+ */
+function setupEventListeners() {
+ console.log('Setting up event listeners');
+
+ // Set up user menu button click handler
+ // const userMenuBtn = document.getElementById('userMenuBtn'); // REMOVE/COMMENT OUT
+ // const userMenuDropdown = document.getElementById('userMenuDropdown'); // REMOVE/COMMENT OUT
+
+ // if (userMenuBtn && userMenuDropdown) { // REMOVE/COMMENT OUT THIS ENTIRE BLOCK
+ // console.log('Setting up user menu button click handler');
+ // userMenuBtn.addEventListener('click', function(e) {
+ // e.stopPropagation();
+ // userMenuDropdown.classList.toggle('active');
+ // });
+ // document.addEventListener('click', function(e) {
+ // if (userMenuDropdown.classList.contains('active') &&
+ // !userMenuDropdown.contains(e.target) &&
+ // !userMenuBtn.contains(e.target)) {
+ // userMenuDropdown.classList.remove('active');
+ // }
+ // });
+ // }
+
+ // Dark mode toggle in header (no longer exists)
+ if (darkModeToggle) {
+ darkModeToggle.addEventListener('change', function() {
+ setTheme(this.checked);
+
+ // Also update the settings page toggle
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = this.checked;
+ }
+ });
+ }
+
+ // Dark mode toggle in settings
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.addEventListener('change', function() {
+ setTheme(this.checked);
+
+ // Also update the header toggle if it exists
+ if (darkModeToggle) {
+ darkModeToggle.checked = this.checked;
+ }
+ });
+ }
+
+ // Save profile button
+ if (saveProfileBtn) {
+ saveProfileBtn.addEventListener('click', saveProfile);
+ }
+
+ // Save preferences button
+ if (savePreferencesBtn) {
+ savePreferencesBtn.addEventListener('click', savePreferences);
+ }
+
+ // Change password button
+ if (changePasswordBtn) {
+ changePasswordBtn.addEventListener('click', function() {
+ passwordChangeForm.style.display = 'block';
+ this.style.display = 'none';
+ });
+ }
+
+ // Save password button
+ if (savePasswordBtn) {
+ savePasswordBtn.addEventListener('click', changePassword);
+ }
+
+ // Cancel password button
+ if (cancelPasswordBtn) {
+ cancelPasswordBtn.addEventListener('click', function() {
+ resetPasswordForm();
+ passwordChangeForm.style.display = 'none';
+ changePasswordBtn.style.display = 'block';
+ });
+ }
+
+ // Delete account button
+ if (deleteAccountBtn) {
+ deleteAccountBtn.addEventListener('click', function() {
+ openModal(deleteAccountModal);
+ });
+ }
+
+ // Delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.addEventListener('input', function() {
+ confirmDeleteAccountBtn.disabled = this.value !== 'DELETE';
+ });
+ }
+
+ // Confirm delete account button
+ if (confirmDeleteAccountBtn) {
+ confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
+ }
+
+ // Add event listener for logout menu item
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+ if (logoutMenuItem) {
+ logoutMenuItem.addEventListener('click', function() {
+ if (window.auth && window.auth.logout) {
+ window.auth.logout();
+ }
+ });
+ }
+
+ // Admin section buttons
+ if (refreshUsersBtn) {
+ refreshUsersBtn.addEventListener('click', function() {
+ loadUsers();
+ });
+ }
+
+ if (checkAdminBtn) {
+ checkAdminBtn.addEventListener('click', function() {
+ checkAdminPermissions();
+ });
+ }
+
+ if (showUsersBtn) {
+ showUsersBtn.addEventListener('click', function() {
+ console.log('Show Users List button clicked');
+ // Open the proper users modal that has crown icons and ownership management
+ const usersModal = document.getElementById('usersModal');
+ if (usersModal) {
+ openModal(usersModal);
+ loadUsers(); // This will populate the table with crown icons
+ } else {
+ console.error('usersModal not found, falling back to showUsersList');
+ showUsersList();
+ }
+ });
+ }
+
+ if (testApiBtn) {
+ testApiBtn.addEventListener('click', function() {
+ checkApiEndpoint();
+ });
+ }
+
+ if (triggerNotificationsBtn) {
+ triggerNotificationsBtn.addEventListener('click', function() {
+ triggerWarrantyNotifications();
+ });
+ }
+
+ if (schedulerStatusBtn) {
+ schedulerStatusBtn.addEventListener('click', function() {
+ checkSchedulerStatus();
+ });
+ }
+
+ // Site settings save button
+ if (saveSiteSettingsBtn) {
+ saveSiteSettingsBtn.addEventListener('click', function() {
+ saveSiteSettings(); // This will now also handle non-OIDC site settings
+ });
+ }
+
+ // Save OIDC settings button
+ if (saveOidcSettingsBtn) {
+ saveOidcSettingsBtn.addEventListener('click', function() {
+ saveOidcSettings();
+ });
+ }
+
+ // Save email settings button
+ if (saveNotificationSettingsBtn) {
+ saveNotificationSettingsBtn.addEventListener('click', saveNotificationSettings);
+ }
+
+ // Save user changes button (Edit User Modal)
+ const saveUserBtn = document.getElementById('saveUserBtn');
+ if (saveUserBtn) {
+ saveUserBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ console.log('Save User button clicked');
+ saveUserChanges();
+ });
+ }
+
+ // Add timezone change listener to update Apprise timezone display
+ const timezoneSelect = document.getElementById('timezone');
+ if (timezoneSelect) {
+ timezoneSelect.addEventListener('change', function() {
+ updateAppriseTimezoneDisplay(this.value);
+ });
+ }
+
+
+
+ if (userAppriseTimezoneSelect) {
+ loadTimezonesIntoSelect(userAppriseTimezoneSelect);
+ }
+
+ if (notificationChannel) {
+ notificationChannel.addEventListener('change', (e) => {
+ toggleNotificationSettings(e.target.value);
+ });
+ }
+
+ // Paperless-ngx event listeners
+ if (paperlessEnabledToggle) {
+ paperlessEnabledToggle.addEventListener('change', function() {
+ togglePaperlessSettings(this.checked);
+ });
+ }
+
+ if (testPaperlessConnectionBtn) {
+ testPaperlessConnectionBtn.addEventListener('click', testPaperlessConnection);
+ }
+
+ if (savePaperlessSettingsBtn) {
+ savePaperlessSettingsBtn.addEventListener('click', savePaperlessSettings);
+ }
+
+ // Add debug button event listener
+ const debugPaperlessBtn = document.getElementById('debugPaperlessBtn');
+ if (debugPaperlessBtn) {
+ debugPaperlessBtn.addEventListener('click', debugPaperlessConfiguration);
+ }
+
+ // Add test upload button event listener
+ const testFileUploadBtn = document.getElementById('testFileUploadBtn');
+ if (testFileUploadBtn) {
+ testFileUploadBtn.addEventListener('click', testFileUpload);
+ }
+
+ // Clear status message when inputs are changed
+ if (paperlessUrlInput) {
+ paperlessUrlInput.addEventListener('input', function() {
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ paperlessConnectionStatus.innerHTML = '';
+ }
+ });
+ }
+
+ if (paperlessApiTokenInput) {
+ paperlessApiTokenInput.addEventListener('input', function() {
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ paperlessConnectionStatus.innerHTML = '';
+ }
+ });
+ }
+
+ console.log('Event listeners setup complete');
+}
+
+/**
+ * Initialize modals
+ */
+function initModals() {
+ // Helper to close all modals and reset forms
+ function closeModalHandler(e) {
+ if (e) e.preventDefault();
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.style.display = 'none';
+ });
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+ // Reset password form
+ resetPasswordForm();
+ }
+
+ // Close modal when clicking on X or outside
+ document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', closeModalHandler);
+ closeBtn.addEventListener('touchend', closeModalHandler);
+ });
+
+ // Close modal when clicking outside (backdrop)
+ function backdropHandler(event) {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ if (event.target === modal) {
+ closeModalHandler(event);
+ }
+ });
+ }
+ window.addEventListener('click', backdropHandler);
+ window.addEventListener('touchend', backdropHandler);
+
+ // Add direct click handler to delete user modal
+ if (deleteUserModal) {
+ console.log('Adding click handler to deleteUserModal');
+ deleteUserModal.addEventListener('click', function(event) {
+ // Check if the click was on the confirm delete button
+ if (event.target && event.target.id === 'confirmDeleteUserBtn') {
+ event.preventDefault();
+ console.log('Confirm delete button clicked through modal event delegation');
+ deleteUser();
+ }
+ });
+ } else {
+ console.error('deleteUserModal not found in initModals');
+ }
+
+ // Set up transfer ownership modal close handlers
+ const transferOwnershipModal = document.getElementById('transferOwnershipModal');
+ if (transferOwnershipModal) {
+ const transferConfirmInput = document.getElementById('transferConfirmInput');
+ const confirmTransferBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (transferConfirmInput && confirmTransferBtn) {
+ transferConfirmInput.addEventListener('input', function() {
+ confirmTransferBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+ }
+ }
+}
+
+/**
+ * Initialize collapsible cards functionality
+ */
+function initCollapsibleCards() {
+ console.log('Initializing collapsible cards...');
+
+ // Get all collapsible headers
+ const collapsibleHeaders = document.querySelectorAll('.collapsible-header');
+
+ // Retrieve saved states from localStorage
+ const savedStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
+
+ collapsibleHeaders.forEach(header => {
+ const targetId = header.getAttribute('data-target');
+ const card = header.closest('.collapsible-card');
+
+ // Apply saved state or default to expanded
+ const isCollapsed = savedStates[targetId] === true;
+ if (isCollapsed) {
+ card.classList.add('collapsed');
+ }
+
+ // Add click event listener
+ header.addEventListener('click', function() {
+ const targetId = this.getAttribute('data-target');
+ const card = this.closest('.collapsible-card');
+
+ // Toggle collapsed state
+ card.classList.toggle('collapsed');
+
+ // Save state to localStorage
+ const currentStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
+ currentStates[targetId] = card.classList.contains('collapsed');
+ localStorage.setItem('collapsibleStates', JSON.stringify(currentStates));
+
+ console.log(`Toggled ${targetId}: ${card.classList.contains('collapsed') ? 'collapsed' : 'expanded'}`);
+ });
+ });
+
+ console.log('Collapsible cards initialized');
+}
+
+/**
+ * Open a modal
+ * @param {HTMLElement} modal - The modal to open
+ */
+function openModal(modal) {
+ console.log('Opening modal:', modal.id, 'Current display:', modal.style.display);
+
+ // First close all modals
+ closeAllModals();
+
+ // Then open this modal
+ modal.style.display = 'flex';
+ console.log('Modal display after opening:', modal.style.display);
+
+ // If this is the delete user modal, set up the delete button
+ if (modal.id === 'deleteUserModal') {
+ console.log('This is the delete user modal, setting up delete button');
+ // Use setTimeout to ensure the DOM is fully updated
+ setTimeout(() => {
+ setupDeleteButton();
+ }, 100);
+ }
+}
+
+/**
+ * Reset password form
+ */
+function resetPasswordForm() {
+ currentPasswordInput.value = '';
+ newPasswordInput.value = '';
+ confirmPasswordInput.value = '';
+}
+
+/**
+ * Save user profile
+ */
+async function saveProfile() {
+ // Validate form
+ if (!firstNameInput || !lastNameInput || !firstNameInput.value.trim() || !lastNameInput.value.trim()) {
+ showToast('Please fill in First Name and Last Name', 'error');
+ return;
+ }
+
+ // Get the new email value
+ const newEmail = emailInput.value.trim();
+ if (!newEmail) {
+ showToast('Email address cannot be empty.', 'error');
+ return;
+ }
+ // Basic email format validation
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(newEmail)) {
+ showToast('Please enter a valid email address.', 'error');
+ return;
+ }
+
+ showLoading();
+ const userNameDisplay = document.getElementById('currentUserNameDisplay');
+
+ try {
+ const response = await fetch('/api/auth/profile', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ first_name: firstNameInput.value.trim(),
+ last_name: lastNameInput.value.trim(),
+ email: newEmail
+ })
+ });
+
+ if (response.ok) {
+ const userData = await response.json();
+ // Update localStorage
+ const currentUser = window.auth.getCurrentUser();
+ let first_name = userData.first_name;
+ let last_name = userData.last_name;
+ if (!last_name) first_name = '';
+ const updatedUser = {
+ ...(currentUser || {}),
+ first_name,
+ last_name,
+ email: userData.email, // Use the email returned from the backend
+ username: currentUser ? currentUser.username : userData.username,
+ is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
+ id: currentUser ? currentUser.id : userData.id
+ };
+ // Update the email input field with the (potentially new) email from the backend
+ if (emailInput) emailInput.value = userData.email || '';
+ localStorage.setItem('user_info', JSON.stringify(updatedUser));
+
+ // --- UPDATE DISPLAY ELEMENT IMMEDIATELY ---
+ let displayName;
+ if (userData.first_name && userData.last_name) {
+ displayName = `${userData.first_name} ${userData.last_name}`;
+ } else {
+ displayName = updatedUser.username || 'User';
+ }
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ // --- END UPDATE ---
+
+ // Update UI (Header, etc.) - Ensure auth module is loaded
+ if (window.auth && window.auth.checkAuthState) {
+ window.auth.checkAuthState();
+ } else {
+ console.warn("Auth module or checkAuthState not found, header might not update immediately.");
+ }
+
+ showToast('Profile updated successfully', 'success');
+ } else {
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+ throw new Error(errorData.message || 'Failed to update profile');
+ }
+ } catch (error) {
+ console.error('Error updating profile:', error);
+ showToast(`Failed to update profile: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Save user preferences
+ */
+async function savePreferences() {
+ console.log('Saving preferences...');
+ const prefix = getPreferenceKeyPrefix();
+
+ // Get current UI state FIRST (before building preferencesToSave)
+ const isDark = darkModeToggleSetting ? darkModeToggleSetting.checked : false;
+ console.log(`Current dark mode UI state: ${isDark}`);
+
+ // --- Prepare data to save --- Add dateFormat and dark mode
+ const preferencesToSave = {
+ default_view: defaultViewSelect ? defaultViewSelect.value : 'grid',
+ expiring_soon_days: expiringSoonDaysInput ? parseInt(expiringSoonDaysInput.value) : 30,
+ date_format: dateFormatSelect ? dateFormatSelect.value : 'MDY',
+ theme: isDark ? 'dark' : 'light', // Use current UI state, not old localStorage
+ paperless_view_in_app: paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false,
+ preferred_language: languageSelect ? languageSelect.value : 'en', // Include language preference
+ };
+
+ // Handle currency symbol (standard or custom)
+ let currencySymbol = '$'; // Default
+ let currencyCode = 'USD'; // Default
+ if (currencySymbolSelect) {
+ if (currencySymbolSelect.value === 'other' && currencySymbolCustom) {
+ currencySymbol = currencySymbolCustom.value.trim() || '$'; // Use custom or default to $ if empty
+ // For custom symbols, try to derive currency code or default to USD
+ currencyCode = 'USD'; // Default for custom symbols
+ } else {
+ currencySymbol = currencySymbolSelect.value;
+ // Find the currency code for the selected symbol
+ const selectedCurrency = globalCurrenciesData.find(currency => currency.symbol === currencySymbol);
+ if (selectedCurrency) {
+ currencyCode = selectedCurrency.code;
+ }
+ }
+ }
+ preferencesToSave.currency_symbol = currencySymbol;
+
+ // Handle currency position
+ let currencyPosition = 'left'; // Default
+ if (currencyPositionSelect) {
+ currencyPosition = currencyPositionSelect.value;
+ }
+ preferencesToSave.currency_position = currencyPosition;
+ // --- End data preparation ---
+
+ // +++ ADDED DEBUG LOGGING +++
+ console.log(`[SavePrefs Debug] Currency Select Value: ${currencySymbolSelect ? currencySymbolSelect.value : 'N/A'}`);
+ console.log(`[SavePrefs Debug] Custom Input Value: ${currencySymbolCustom ? currencySymbolCustom.value : 'N/A'}`);
+ console.log(`[SavePrefs Debug] Final currencySymbol value determined: ${currencySymbol}`);
+ console.log(`[SavePrefs Debug] Final currencyCode value determined: ${currencyCode}`);
+ console.log(`[SavePrefs Debug] Currency Position Value: ${currencyPosition}`);
+ console.log(`[SavePrefs Debug] Theme being saved: ${preferencesToSave.theme} (from isDark: ${isDark})`);
+ console.log(`[SavePrefs Debug] Language being saved: ${preferencesToSave.preferred_language}`);
+ // +++ END DEBUG LOGGING +++
+
+ // Apply the theme to the UI (this updates localStorage too)
+ setTheme(isDark);
+ console.log(`Saved dark mode: ${isDark}`);
+
+ // Save simple preferences to localStorage immediately
+ localStorage.setItem('dateFormat', preferencesToSave.date_format); // Added
+ localStorage.setItem(`${prefix}defaultView`, preferencesToSave.default_view);
+ localStorage.setItem(`${prefix}currencySymbol`, preferencesToSave.currency_symbol);
+ localStorage.setItem(`${prefix}currencyCode`, currencyCode); // Save currency code
+ localStorage.setItem(`${prefix}currencyPosition`, preferencesToSave.currency_position);
+ localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);
+ localStorage.setItem(`${prefix}paperlessViewInApp`, preferencesToSave.paperless_view_in_app);
+ localStorage.setItem('preferred_language', preferencesToSave.preferred_language); // Save language preference
+
+ console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);
+ console.log(`Value of dateFormat in localStorage: ${localStorage.getItem('dateFormat')}`);
+
+ // Try saving to API
+ if (window.auth && window.auth.isAuthenticated()) {
+ try {
+ showLoading();
+ const token = window.auth.getToken();
+ console.log('Saving preferences with token:', token ? 'present' : 'missing');
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferencesToSave)
+ });
+
+ hideLoading();
+ if (response.ok) {
+ showToast('Preferences saved successfully.', 'success');
+ console.log('Preferences successfully saved to API.');
+
+ // If language was changed, trigger the actual language change
+ if (preferencesToSave.preferred_language && window.i18n?.changeLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage ? window.i18n.getCurrentLanguage() : 'en';
+ if (preferencesToSave.preferred_language !== currentLang) {
+ console.log(`Language changed from ${currentLang} to ${preferencesToSave.preferred_language}, triggering page translation`);
+ try {
+ await window.i18n.changeLanguage(preferencesToSave.preferred_language);
+ // Reload page after a short delay to apply all translations
+ setTimeout(() => {
+ window.location.reload();
+ }, 1000);
+ } catch (error) {
+ console.error('Failed to change language after saving preferences:', error);
+ showToast('Failed to change language. Please try again.', 'error');
+ }
+ }
+ } else if (preferencesToSave.preferred_language) {
+ console.warn('i18n changeLanguage function not available when saving preferences');
+ showToast('Language system not ready. Settings saved but language not changed. Please refresh and try again.', 'warning');
+ }
+ } else {
+ console.error('Preferences save failed. Response status:', response.status);
+ console.error('Response headers:', Object.fromEntries(response.headers.entries()));
+ const errorData = await response.json().catch((e) => {
+ console.error('Failed to parse error response as JSON:', e);
+ return {};
+ });
+ console.error('Error response data:', errorData);
+ throw new Error(errorData.message || `Failed to save preferences to API: ${response.status}`);
+ }
+ } catch (error) {
+ hideLoading();
+ console.error('Error saving preferences to API:', error);
+ showToast(`Preferences saved locally, but failed to sync with server: ${error.message}`, 'warning');
+ }
+ } else {
+ // No auth, just show local save success
+ showToast('Preferences saved locally.', 'success');
+ }
+}
+
+/**
+ * Change user password
+ */
+async function changePassword() {
+ // Validate form
+ if (!currentPasswordInput.value || !newPasswordInput.value || !confirmPasswordInput.value) {
+ showToast('Please fill in all password fields', 'error');
+ return;
+ }
+
+ if (newPasswordInput.value !== confirmPasswordInput.value) {
+ showToast('New passwords do not match', 'error');
+ return;
+ }
+
+ // Validate password strength
+ if (newPasswordInput.value.length < 8) {
+ showToast('Password must be at least 8 characters long', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ const response = await fetch('/api/auth/password/change', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ current_password: currentPasswordInput.value,
+ new_password: newPasswordInput.value
+ })
+ });
+
+ if (response.ok) {
+ // Reset form and hide it
+ resetPasswordForm();
+ passwordChangeForm.style.display = 'none';
+ changePasswordBtn.style.display = 'block';
+
+ // Show success modal
+ openModal(passwordSuccessModal);
+ } else {
+ // Handle error
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+ throw new Error(errorData.message || 'Failed to change password');
+ }
+ } catch (error) {
+ console.error('Error changing password:', error);
+ showToast(`Failed to change password: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Delete user account
+ */
+async function deleteAccount() {
+ if (deleteConfirmInput.value !== 'DELETE') {
+ showToast('Please type DELETE to confirm', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ const response = await fetch('/api/auth/account', {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ // Clear auth data
+ if (window.auth.logout) {
+ window.auth.logout();
+ } else {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ }
+
+ // Show success message
+ showToast('Account deleted successfully', 'success');
+
+ // Redirect to home page after a short delay
+ setTimeout(() => {
+ window.location.href = 'index.html';
+ }, 2000);
+ } else {
+ // Handle error - show the actual error message from the API
+ let errorMessage = 'Failed to delete account';
+ try {
+ const errorData = await response.json();
+ errorMessage = errorData.message || errorMessage;
+ } catch (parseError) {
+ console.warn('Could not parse error response:', parseError);
+ }
+
+ console.error('API error response:', errorMessage);
+ showToast(errorMessage, 'error');
+ }
+ } catch (error) {
+ console.error('Network error deleting account:', error);
+ // Only show offline message for actual network errors
+ if (error.name === 'TypeError' && error.message.includes('fetch')) {
+ showToast('Account cannot be deleted in offline mode', 'warning');
+ } else {
+ showToast('Failed to delete account. Please try again.', 'error');
+ }
+ } finally {
+ hideLoading();
+
+ // Close modal
+ deleteAccountModal.style.display = 'none';
+
+ // Reset delete confirm input
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+}
+
+/**
+ * Show loading spinner
+ */
+function showLoading() {
+ loadingContainer.style.display = 'flex';
+}
+
+/**
+ * Hide loading spinner
+ */
+function hideLoading() {
+ loadingContainer.style.display = 'none';
+}
+
+/**
+ * Show a toast notification
+ * @param {string} message - The message to display
+ * @param {string} type - The type of toast (info, success, error, warning)
+ * @param {number} duration - Duration in milliseconds, 0 for no auto-hide
+ * @returns {HTMLElement} - The toast element
+ */
+function showToast(message, type = 'info', duration = 5000) {
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ const icon = document.createElement('i');
+ switch (type) {
+ case 'success':
+ icon.className = 'fas fa-check-circle';
+ break;
+ case 'error':
+ icon.className = 'fas fa-exclamation-circle';
+ break;
+ case 'warning':
+ icon.className = 'fas fa-exclamation-triangle';
+ break;
+ default:
+ icon.className = 'fas fa-info-circle';
+ }
+
+ const messageSpan = document.createElement('span');
+ messageSpan.textContent = message;
+
+ toast.appendChild(icon);
+ toast.appendChild(messageSpan);
+
+ toastContainer.appendChild(toast);
+
+ // Add a method to remove the toast
+ toast.remove = function() {
+ toast.classList.add('toast-fade-out');
+ setTimeout(() => {
+ if (toast.parentNode) {
+ toast.parentNode.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Auto-hide toast after specified duration (if not 0)
+ if (duration > 0) {
+ setTimeout(() => {
+ toast.remove();
+ }, duration);
+ }
+
+ return toast;
+}
+
+/**
+ * Load users for admin
+ */
+async function loadUsers() {
+ // Exit if usersTableBody doesn't exist
+ if (!usersTableBody) {
+ console.log('usersTableBody element not found, skipping loadUsers');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ const response = await fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ const users = await response.json();
+
+ // DEBUG: Check users data
+ console.log('DEBUG: Users data from API:', users);
+ users.forEach((user, index) => {
+ console.log(`DEBUG: User ${index} (${user.username}):`, {
+ id: user.id,
+ is_owner: user.is_owner,
+ is_admin: user.is_admin
+ });
+ });
+
+ // Clear table
+ usersTableBody.innerHTML = '';
+
+ // Add users to table
+ users.forEach(user => {
+ const row = document.createElement('tr');
+ row.style.borderBottom = '1px solid var(--border-color)';
+ row.style.transition = 'background-color 0.2s ease';
+
+ // Add hover effect
+ row.addEventListener('mouseenter', () => {
+ row.style.backgroundColor = 'var(--hover-bg, rgba(0,0,0,0.05))';
+ });
+ row.addEventListener('mouseleave', () => {
+ row.style.backgroundColor = 'transparent';
+ });
+
+ // ID
+ const idCell = document.createElement('td');
+ idCell.textContent = user.id;
+ idCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
+ row.appendChild(idCell);
+
+ // Username with crown
+ const usernameCell = document.createElement('td');
+ const crownIcon = user.is_owner ? ' <i class="fas fa-crown" title="Application Owner" style="color: #f39c12; margin-left: 5px;"></i>' : '';
+ console.log(`DEBUG: User ${user.username} (ID: ${user.id}) - is_owner: ${user.is_owner}, adding crown: ${!!user.is_owner}`);
+ usernameCell.innerHTML = user.username + crownIcon;
+ usernameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
+ row.appendChild(usernameCell);
+
+ // Email
+ const emailCell = document.createElement('td');
+ emailCell.textContent = user.email;
+ emailCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-size: 0.9em;';
+ row.appendChild(emailCell);
+
+ // Name
+ const nameCell = document.createElement('td');
+ const fullName = `${user.first_name || ''} ${user.last_name || ''}`.trim();
+ nameCell.textContent = fullName || '-';
+ nameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color);';
+ row.appendChild(nameCell);
+
+ // Admin
+ const adminCell = document.createElement('td');
+ const adminBadge = document.createElement('span');
+ adminBadge.className = `badge ${user.is_admin ? 'badge-success' : 'badge-secondary'}`;
+ adminBadge.textContent = user.is_admin ? 'Yes' : 'No';
+ adminBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
+ adminCell.appendChild(adminBadge);
+ adminCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
+ row.appendChild(adminCell);
+
+ // Active Status
+ const statusCell = document.createElement('td');
+ const statusBadge = document.createElement('span');
+ statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
+ statusBadge.textContent = user.is_active ? 'Yes' : 'No';
+ statusBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
+ statusCell.appendChild(statusBadge);
+ statusCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
+ row.appendChild(statusCell);
+
+ // Actions
+ const actionsCell = document.createElement('td');
+ actionsCell.style.cssText = 'padding: 12px 8px; text-align: center;';
+
+ // Create button container for better spacing
+ const buttonContainer = document.createElement('div');
+ buttonContainer.style.cssText = 'display: flex; gap: 6px; justify-content: center; align-items: center;';
+
+ // Edit button
+ const editBtn = document.createElement('button');
+ editBtn.className = 'btn btn-sm';
+ editBtn.innerHTML = '<i class="fas fa-edit"></i>';
+ editBtn.title = 'Edit User';
+ editBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--primary-color, #007bff);
+ background-color: transparent;
+ color: var(--primary-color, #007bff);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Edit button hover effects
+ editBtn.addEventListener('mouseenter', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'var(--primary-color, #007bff)';
+ editBtn.style.color = 'white';
+ editBtn.style.transform = 'translateY(-1px)';
+ editBtn.style.boxShadow = '0 2px 4px rgba(0,123,255,0.3)';
+ }
+ });
+ editBtn.addEventListener('mouseleave', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'transparent';
+ editBtn.style.color = 'var(--primary-color, #007bff)';
+ editBtn.style.transform = 'translateY(0)';
+ editBtn.style.boxShadow = 'none';
+ }
+ });
+ editBtn.addEventListener('click', () => openEditUserModal(user));
+
+ // Delete button
+ const deleteBtn = document.createElement('button');
+ deleteBtn.className = 'btn btn-sm';
+ deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
+ deleteBtn.title = 'Delete User';
+ deleteBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--danger-color, #dc3545);
+ background-color: transparent;
+ color: var(--danger-color, #dc3545);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Delete button hover effects
+ deleteBtn.addEventListener('mouseenter', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.color = 'white';
+ deleteBtn.style.transform = 'translateY(-1px)';
+ deleteBtn.style.boxShadow = '0 2px 4px rgba(220,53,69,0.3)';
+ }
+ });
+ deleteBtn.addEventListener('mouseleave', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'transparent';
+ deleteBtn.style.color = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.transform = 'translateY(0)';
+ deleteBtn.style.boxShadow = 'none';
+ }
+ });
+
+ // Add multiple event handlers for redundancy
+ deleteBtn.addEventListener('click', (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ console.log('Delete button clicked for user:', user);
+ openDeleteUserModal(user);
+ });
+
+ // Also set onclick property
+ deleteBtn.onclick = function(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ console.log('Delete button onclick property triggered for user:', user);
+ openDeleteUserModal(user);
+ return false;
+ };
+
+ // Don't allow editing or deleting self, and disable actions for the owner
+ const currentUser = window.auth.getCurrentUser();
+ const isOwner = user.is_owner;
+ const isCurrentUser = (user.id === currentUser.id);
+
+ console.log(`DEBUG: Button logic for ${user.username} - isOwner: ${isOwner}, isCurrentUser: ${isCurrentUser}, currentUser.id: ${currentUser?.id}, user.id: ${user.id}`);
+
+ if (isOwner || isCurrentUser) {
+ editBtn.disabled = true;
+ deleteBtn.disabled = true;
+ editBtn.title = isOwner ? 'Cannot edit the application owner' : 'Cannot edit yourself';
+ deleteBtn.title = isOwner ? 'Cannot delete the application owner' : 'Cannot delete yourself';
+
+ // Enhanced disabled styling
+ editBtn.style.opacity = '0.4';
+ editBtn.style.cursor = 'not-allowed';
+ editBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ editBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ deleteBtn.style.opacity = '0.4';
+ deleteBtn.style.cursor = 'not-allowed';
+ deleteBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ deleteBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ console.log('DEBUG: Disabled edit/delete for', isOwner ? 'owner' : 'current user', ':', user.id);
+ } else {
+ console.log('DEBUG: Buttons enabled for user:', user.id);
+ }
+
+ // Add buttons to container
+ buttonContainer.appendChild(editBtn);
+ buttonContainer.appendChild(deleteBtn);
+
+ // Add container to cell
+ actionsCell.appendChild(buttonContainer);
+ row.appendChild(actionsCell);
+
+ usersTableBody.appendChild(row);
+ });
+
+ console.log('Users loaded successfully:', users.length);
+
+ // Set up ownership management after loading users
+ setupOwnershipManagement(users);
+ } else {
+ console.error('Failed to load users:', response.status);
+ showToast('Failed to load users', 'error');
+ }
+ } catch (error) {
+ console.error('Error loading users:', error);
+ showToast('Error loading users', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Open edit user modal
+ * @param {Object} user - The user to edit
+ */
+function openEditUserModal(user) {
+ editUserId.value = user.id;
+ editUsername.value = user.username;
+ editEmail.value = user.email;
+ editUserActive.checked = user.is_active;
+ editUserAdmin.checked = user.is_admin;
+
+ openModal(editUserModal);
+}
+
+/**
+ * Save user changes
+ */
+async function saveUserChanges() {
+ const userId = editUserId.value;
+
+ if (!userId) {
+ showToast('User ID is missing', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ const response = await fetch(`/api/admin/users/${userId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ is_active: editUserActive.checked,
+ is_admin: editUserAdmin.checked
+ })
+ });
+
+ if (response.ok) {
+ showToast('User updated successfully', 'success');
+ closeAllModals();
+ loadUsers();
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to update user', 'error');
+ }
+ } catch (error) {
+ console.error('Error updating user:', error);
+ showToast('Failed to update user. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Open delete user modal
+ * @param {Object} user - User object
+ */
+function openDeleteUserModal(user) {
+ console.log('Opening delete modal for user:', user);
+
+ // Store the user ID in a global variable for easier access
+ window.currentDeleteUserId = user.id;
+ console.log('Set global currentDeleteUserId to:', user.id);
+
+ // Set the user ID in the form
+ const deleteUserIdField = document.getElementById('deleteUserId');
+ if (deleteUserIdField) {
+ deleteUserIdField.value = user.id;
+ console.log('Set deleteUserId field to:', user.id);
+ } else {
+ console.error('deleteUserId field not found in the DOM');
+ }
+
+ // Display user ID for debugging
+ const displayUserIdField = document.getElementById('displayUserId');
+ if (displayUserIdField) {
+ displayUserIdField.textContent = user.id;
+ console.log('Set displayUserId field to:', user.id);
+ }
+
+ // Also set in editUserId for backward compatibility
+ if (editUserId) {
+ editUserId.value = user.id;
+ console.log('Set editUserId.value to:', user.id);
+ }
+
+ // Set the username in the modal
+ const deleteUserNameElement = document.getElementById('deleteUserName');
+ if (deleteUserNameElement) {
+ deleteUserNameElement.textContent = user.username;
+ console.log('Set deleteUserName to:', user.username);
+ } else {
+ console.error('deleteUserName element not found in the DOM');
+ }
+
+ // Make sure the modal is visible
+ const deleteUserModal = document.getElementById('deleteUserModal');
+ if (deleteUserModal) {
+ // First ensure all modals are closed
+ closeAllModals();
+
+ // Then open this modal
+ deleteUserModal.style.display = 'flex';
+ console.log('Delete user modal opened');
+
+ // Ensure the delete button has the correct click handler
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (confirmDeleteUserBtn) {
+ // Remove existing event listeners by cloning
+ const newBtn = confirmDeleteUserBtn.cloneNode(true);
+ confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
+
+ // Add the click event listener
+ newBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ });
+
+ // Also set the direct onclick attribute as a simple function call
+ newBtn.setAttribute('onclick', 'console.log("Direct onclick attribute clicked"); deleteUser(); return false;');
+ console.log('Added click event listener to delete button');
+
+ // Add a direct click handler
+ newBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct onclick property handler clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ } else {
+ console.error('confirmDeleteUserBtn not found in the DOM');
+ }
+
+ // Set up the direct delete link
+ const directDeleteLink = document.getElementById('directDeleteLink');
+ if (directDeleteLink) {
+ directDeleteLink.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct delete link clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ console.log('Added onclick handler to direct delete link');
+ }
+
+ // Set up the direct API link
+ const directAPILink = document.getElementById('directAPILink');
+ if (directAPILink) {
+ directAPILink.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct API link clicked for user ID:', user.id);
+ directDeleteUserAPI(user.id);
+ return false;
+ };
+ console.log('Added onclick handler to direct API link');
+ }
+
+ // Also set up form submit handler
+ const deleteUserForm = document.getElementById('deleteUserForm');
+ if (deleteUserForm) {
+ deleteUserForm.onsubmit = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete user form submitted for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ console.log('Added onsubmit handler to delete user form');
+ }
+
+ // Add a direct click handler to the modal for event delegation
+ deleteUserModal.addEventListener('click', function(e) {
+ if (e.target && e.target.id === 'confirmDeleteUserBtn') {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked through modal event delegation for user ID:', user.id);
+ deleteUser();
+ return false;
+ }
+ });
+ } else {
+ console.error('deleteUserModal not found in the DOM');
+ }
+}
+
+/**
+ * Delete user
+ */
+function deleteUser() {
+ console.log('=== DELETE USER FUNCTION STARTED ===');
+ console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
+
+ try {
+ // Get the user ID from various possible sources
+ const userId = window.currentDeleteUserId ||
+ (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null) ||
+ (document.getElementById('editUserId') ? document.getElementById('editUserId').value : null) ||
+ (document.getElementById('displayUserId') ? document.getElementById('displayUserId').textContent : null);
+
+ console.log('Final User ID to delete:', userId);
+
+ if (!userId) {
+ showToast('User ID is missing', 'error');
+ console.error('Delete user failed: User ID is missing');
+ return;
+ }
+
+ console.log('Starting user deletion process for ID:', userId);
+ showLoading();
+
+ // Use our improved deletion function
+ superEmergencyDelete(userId)
+ .then(success => {
+ if (success) {
+ console.log('User deletion successful');
+ showToast('User deleted successfully', 'success');
+ closeAllModals();
+ loadUsers(); // Refresh the user list
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ showUsersList();
+ }
+ } else {
+ console.error('User deletion failed');
+ showToast('Failed to delete user. Check console for details.', 'error');
+ }
+ hideLoading();
+ })
+ .catch(error => {
+ console.error('Error during user deletion:', error);
+ showToast(window.t('messages.error_during_user_deletion', { error: error.message }), 'error');
+ hideLoading();
+
+ // Try the direct API call as a fallback
+ if (confirm('Would you like to try a direct API call to delete the user?')) {
+ const directToast = showToast(`Trying direct API call for user ID ${userId}...`, 'info', 0);
+
+ directDeleteUserAPI(userId)
+ .then(directSuccess => {
+ directToast.remove();
+
+ if (directSuccess) {
+ showToast(`User ID ${userId} deleted successfully with direct API call!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ showToast(window.t('messages.failed_to_delete_user_with_direct_api_call', { username: user.username }), 'error');
+ }
+ })
+ .catch(error => {
+ directToast.remove();
+ console.error('Error with direct API call:', error);
+ showToast('Error with direct API call: ' + error.message, 'error');
+ });
+ }
+ })
+ .catch(error => {
+ console.error('Error checking if user exists:', error);
+ showToast('Error checking if user exists: ' + error.message, 'error');
+ });
+ } catch (error) {
+ console.error('Error in deleteUser function:', error);
+ console.error('Error details:', error.message, error.stack);
+ showToast('Failed to delete user. Please try again.', 'error');
+ hideLoading();
+ }
+
+ console.log('=== DELETE USER FUNCTION COMPLETED ===');
+}
+
+/**
+ * Set up ownership management functionality
+ * @param {Array} users - List of all users
+ */
+function setupOwnershipManagement(users) {
+ const currentUser = window.auth.getCurrentUser();
+ const ownershipCard = document.getElementById('ownershipCard');
+ const newOwnerSelect = document.getElementById('newOwnerSelect');
+ const transferOwnershipBtn = document.getElementById('transferOwnershipBtn');
+
+ // DEBUG: Check ownership management setup
+ console.log('DEBUG: setupOwnershipManagement called');
+ console.log('DEBUG: currentUser:', currentUser);
+ console.log('DEBUG: currentUser.is_owner:', currentUser ? currentUser.is_owner : 'no currentUser');
+ console.log('DEBUG: ownershipCard element:', ownershipCard);
+
+ if (!currentUser || !currentUser.is_owner) {
+ // Hide ownership section if user is not the owner
+ console.log('DEBUG: Hiding ownership section - user is not owner');
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'none';
+ }
+ return;
+ }
+
+ // Show ownership section for the owner
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ }
+
+ // Populate the select dropdown with admin users (excluding current owner)
+ if (newOwnerSelect) {
+ newOwnerSelect.innerHTML = '<option value="">Select an admin user...</option>';
+
+ users.forEach(user => {
+ if (user.is_admin && user.id !== currentUser.id && user.is_active && !user.is_owner) {
+ const option = document.createElement('option');
+ option.value = user.id;
+ option.textContent = `${user.username} (${user.email})`;
+ newOwnerSelect.appendChild(option);
+ }
+ });
+
+ // Enable/disable transfer button based on selection
+ newOwnerSelect.addEventListener('change', function() {
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.disabled = !this.value;
+ }
+ });
+ }
+
+ // Set up transfer button click handler
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.addEventListener('click', function() {
+ const selectedUserId = newOwnerSelect.value;
+ if (!selectedUserId) {
+ showToast('Please select a user to transfer ownership to', 'error');
+ return;
+ }
+
+ const selectedUser = users.find(u => u.id == selectedUserId);
+ if (selectedUser) {
+ openTransferOwnershipModal(selectedUser);
+ }
+ });
+ }
+}
+
+/**
+ * Open the transfer ownership confirmation modal
+ * @param {Object} targetUser - The user to transfer ownership to
+ */
+function openTransferOwnershipModal(targetUser) {
+ const modal = document.getElementById('transferOwnershipModal');
+ const targetUsernameSpan = document.getElementById('transferTargetUsername');
+ const confirmInput = document.getElementById('transferConfirmInput');
+ const confirmBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (!modal || !targetUsernameSpan || !confirmInput || !confirmBtn) {
+ showToast('Error: Transfer ownership modal elements not found', 'error');
+ return;
+ }
+
+ // Set target username
+ targetUsernameSpan.textContent = targetUser.username;
+
+ // Clear and set up confirm input
+ confirmInput.value = '';
+ confirmInput.addEventListener('input', function() {
+ confirmBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+
+ // Set up confirm button
+ confirmBtn.disabled = true;
+ confirmBtn.onclick = function() {
+ if (confirmInput.value.toUpperCase() === 'TRANSFER') {
+ performOwnershipTransfer(targetUser.id);
+ }
+ };
+
+ // Show modal
+ modal.style.display = 'flex';
+}
+
+/**
+ * Perform the actual ownership transfer
+ * @param {number} newOwnerId - ID of the user to transfer ownership to
+ */
+async function performOwnershipTransfer(newOwnerId) {
+ const modal = document.getElementById('transferOwnershipModal');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/transfer-ownership', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ new_owner_id: newOwnerId
+ })
+ });
+
+ if (response.ok) {
+ showToast('Ownership transferred successfully! Refreshing page...', 'success');
+
+ // Close modal
+ if (modal) {
+ modal.style.display = 'none';
+ }
+
+ // Refresh the page after a short delay to allow the user to see the success message
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to transfer ownership', 'error');
+ }
+ } catch (error) {
+ console.error('Error transferring ownership:', error);
+ showToast('Failed to transfer ownership. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Super emergency delete function for user deletion
+ * @param {string|number} userId - The user ID or username to delete
+ * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
+ */
+function superEmergencyDelete(userId) {
+ console.log('=== SUPER EMERGENCY DELETE STARTED ===');
+ console.log('User ID or username to delete:', userId);
+
+ return new Promise((resolve, reject) => {
+ if (!userId) {
+ console.error('No user ID provided');
+ reject(new Error('No user ID provided'));
+ return;
+ }
+
+ // Check if the input is a username rather than a numeric ID
+ if (isNaN(userId)) {
+ console.log('Input appears to be a username, not a numeric ID');
+ // Try to find the user ID by username using the Promise-based function
+ findUserIdByUsernameAsync(userId)
+ .then(numericId => {
+ if (numericId) {
+ console.log(`Found numeric ID ${numericId} for username ${userId}`);
+ // Call this function again with the numeric ID
+ return superEmergencyDelete(numericId);
+ } else {
+ throw new Error(`Could not find a user with username "${userId}"`);
+ }
+ })
+ .then(resolve)
+ .catch(reject);
+ return;
+ }
+
+ console.log('Proceeding with numeric user ID:', userId);
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Create a new XMLHttpRequest
+ const xhr = new XMLHttpRequest();
+ xhr.open('DELETE', `/api/admin/users/${userId}`, true);
+
+ // Set headers
+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);
+ xhr.setRequestHeader('Content-Type', 'application/json');
+ xhr.setRequestHeader('Accept', 'application/json');
+
+ // Set up event handlers
+ xhr.onload = function() {
+ console.log('XHR status:', xhr.status);
+ console.log('XHR response text:', xhr.responseText);
+
+ if (xhr.status >= 200 && xhr.status < 300) {
+ console.log('User deletion successful');
+ resolve(true);
+ } else {
+ console.error('User deletion failed with status:', xhr.status);
+ let errorMessage = 'Unknown error';
+ try {
+ const response = JSON.parse(xhr.responseText);
+ errorMessage = response.message || response.error || 'Unknown error';
+ } catch (e) {
+ errorMessage = xhr.responseText || 'Unknown error';
+ }
+ console.error('Error message:', errorMessage);
+ resolve(false); // Resolve with false instead of rejecting to handle the error in a controlled way
+ }
+ };
+
+ xhr.onerror = function() {
+ console.error('Network error during user deletion');
+ reject(new Error('Network error during user deletion'));
+ };
+
+ xhr.ontimeout = function() {
+ console.error('Request timeout during user deletion');
+ reject(new Error('Request timeout during user deletion'));
+ };
+
+ // Send the request
+ xhr.send();
+ console.log('Delete request sent for user ID:', userId);
+ });
+}
+
+/**
+ * Find a user's numeric ID by their username
+ * @param {string} username - The username to look up
+ * @param {function} callback - Callback function that receives the numeric ID or null if not found
+ */
+function findUserIdByUsername(username, callback) {
+ console.log('=== FIND USER ID BY USERNAME STARTED ===');
+ console.log('Looking up user ID for username:', username);
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ callback(null);
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ callback(null);
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) {
+ callback(null);
+ return;
+ }
+
+ console.log('Fetched users list:', users);
+
+ // Find the user with the matching username
+ const user = users.find(u => u.username === username);
+
+ if (user) {
+ console.log('Found user:', user);
+ callback(user.id);
+ } else {
+ console.error('User not found with username:', username);
+ callback(null);
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching users:', error);
+ callback(null);
+ });
+
+ console.log('=== FIND USER ID BY USERNAME COMPLETED ===');
+}
+
+/**
+ * Check admin permissions
+ */
+function checkAdminPermissions() {
+ console.log('=== CHECK ADMIN PERMISSIONS STARTED ===');
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ alert('Error: Authentication token is missing');
+ return;
+ }
+
+ // Get the current user info
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ console.log('Current user info:', userInfo);
+
+ // Check if the user is an admin
+ if (userInfo.is_admin) {
+ console.log('User is an admin');
+ alert('You are an admin user');
+ } else {
+ console.log('User is not an admin');
+ alert('You are not an admin user');
+ }
+
+ // Make a request to the admin endpoint to verify permissions
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ console.log('Admin check response status:', response.status);
+
+ if (response.ok) {
+ console.log('Admin endpoint access successful');
+ alert('You have access to the admin endpoint');
+ } else {
+ console.error('Admin endpoint access failed');
+ alert('You do not have access to the admin endpoint');
+ }
+
+ return response.text().catch(() => '');
+ })
+ .then(text => {
+ console.log('Admin check response text:', text);
+ })
+ .catch(error => {
+ console.error('Admin check error:', error);
+ alert('Error checking admin permissions: ' + error.message);
+ });
+
+ console.log('=== CHECK ADMIN PERMISSIONS COMPLETED ===');
+}
+
+/**
+ * Show a list of users in the system
+ */
+function showUsersList() {
+ console.log('=== SHOW USERS LIST STARTED ===');
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ alert('Error: Authentication token is missing');
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ alert('Failed to fetch users list. Status: ' + response.status);
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) return;
+
+ console.log('Fetched users list:', users);
+
+ // Check if dark mode is enabled
+ const isDarkMode = document.body.classList.contains('dark-mode');
+
+ // Set colors based on theme
+ const backgroundColor = isDarkMode ? '#333' : 'white';
+ const textColor = isDarkMode ? '#fff' : '#000';
+ const borderColor = isDarkMode ? '#555' : '#ddd';
+
+ // Create a modal to display the users
+ const modal = document.createElement('div');
+ modal.style.position = 'fixed';
+ modal.style.top = '0';
+ modal.style.left = '0';
+ modal.style.width = '100%';
+ modal.style.height = '100%';
+ modal.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
+ modal.style.display = 'flex';
+ modal.style.justifyContent = 'center';
+ modal.style.alignItems = 'center';
+ modal.style.zIndex = '10000';
+
+ // Create the modal content
+ const modalContent = document.createElement('div');
+ modalContent.style.backgroundColor = backgroundColor;
+ modalContent.style.color = textColor;
+ modalContent.style.padding = '20px';
+ modalContent.style.borderRadius = '5px';
+ modalContent.style.maxWidth = '80%';
+ modalContent.style.maxHeight = '80%';
+ modalContent.style.overflow = 'auto';
+
+ // Create the modal header
+ const modalHeader = document.createElement('div');
+ modalHeader.style.display = 'flex';
+ modalHeader.style.justifyContent = 'space-between';
+ modalHeader.style.alignItems = 'center';
+ modalHeader.style.marginBottom = '20px';
+
+ // Create the modal title
+ const modalTitle = document.createElement('h3');
+ modalTitle.textContent = 'Users List';
+ modalTitle.style.color = textColor;
+
+ // Create the close button
+ const closeButton = document.createElement('button');
+ closeButton.textContent = '×';
+ closeButton.style.backgroundColor = 'transparent';
+ closeButton.style.border = 'none';
+ closeButton.style.fontSize = '24px';
+ closeButton.style.cursor = 'pointer';
+ closeButton.style.color = textColor;
+ closeButton.addEventListener('click', function() {
+ document.body.removeChild(modal);
+ });
+
+ // Add the title and close button to the header
+ modalHeader.appendChild(modalTitle);
+ modalHeader.appendChild(closeButton);
+
+ // Create the table
+ const table = document.createElement('table');
+ table.style.width = '100%';
+ table.style.borderCollapse = 'collapse';
+
+ // Create the table header
+ const thead = document.createElement('thead');
+ const headerRow = document.createElement('tr');
+
+ // Create the header cells
+ const headers = ['ID', 'Username', 'Email', 'Name', 'Admin', 'Active', 'Actions'];
+ headers.forEach(headerText => {
+ const th = document.createElement('th');
+ th.textContent = headerText;
+ th.style.padding = '10px';
+ th.style.textAlign = 'left';
+ th.style.borderBottom = `1px solid ${borderColor}`;
+ th.style.color = textColor;
+ headerRow.appendChild(th);
+ });
+
+ thead.appendChild(headerRow);
+ table.appendChild(thead);
+
+ // Create the table body
+ const tbody = document.createElement('tbody');
+
+ // Add a row for each user
+ users.forEach(user => {
+ const row = document.createElement('tr');
+
+ // Create cells for each property
+ const idCell = document.createElement('td');
+ idCell.textContent = user.id;
+ idCell.style.padding = '10px';
+ idCell.style.borderBottom = `1px solid ${borderColor}`;
+ idCell.style.color = textColor;
+
+ const usernameCell = document.createElement('td');
+ usernameCell.textContent = user.username;
+ usernameCell.style.padding = '10px';
+ usernameCell.style.borderBottom = `1px solid ${borderColor}`;
+ usernameCell.style.color = textColor;
+
+ const emailCell = document.createElement('td');
+ emailCell.textContent = user.email;
+ emailCell.style.padding = '10px';
+ emailCell.style.borderBottom = `1px solid ${borderColor}`;
+ emailCell.style.color = textColor;
+
+ const nameCell = document.createElement('td');
+ nameCell.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || '-';
+ nameCell.style.padding = '10px';
+ nameCell.style.borderBottom = `1px solid ${borderColor}`;
+ nameCell.style.color = textColor;
+
+ const adminCell = document.createElement('td');
+ adminCell.textContent = user.is_admin ? 'Yes' : 'No';
+ adminCell.style.padding = '10px';
+ adminCell.style.borderBottom = `1px solid ${borderColor}`;
+ adminCell.style.color = textColor;
+
+ const activeCell = document.createElement('td');
+ activeCell.textContent = user.is_active ? 'Yes' : 'No';
+ activeCell.style.padding = '10px';
+ activeCell.style.borderBottom = `1px solid ${borderColor}`;
+ activeCell.style.color = textColor;
+
+ const actionsCell = document.createElement('td');
+ actionsCell.style.padding = '10px';
+ actionsCell.style.borderBottom = `1px solid ${borderColor}`;
+
+ // Create a delete button
+ const deleteButton = document.createElement('button');
+ deleteButton.textContent = 'Delete';
+ deleteButton.style.backgroundColor = '#dc3545';
+ deleteButton.style.color = 'white';
+ deleteButton.style.border = 'none';
+ deleteButton.style.padding = '5px 10px';
+ deleteButton.style.borderRadius = '3px';
+ deleteButton.style.cursor = 'pointer';
+
+ // Don't allow deleting the current user
+ const currentUser = JSON.parse(localStorage.getItem('user_info') || '{}');
+ if (user.id === currentUser.id) {
+ deleteButton.disabled = true;
+ deleteButton.style.opacity = '0.5';
+ deleteButton.style.cursor = 'not-allowed';
+ deleteButton.title = 'Cannot delete yourself';
+ } else {
+ deleteButton.addEventListener('click', function() {
+ if (confirm(`Are you sure you want to delete user ${user.username} (ID: ${user.id})?`)) {
+ document.body.removeChild(modal);
+
+ // First check if the user still exists
+ const checkingToast = showToast(`Checking if user ${user.username} still exists...`, 'info', 0);
+
+ checkUserExists(user.id)
+ .then(existingUser => {
+ checkingToast.remove();
+
+ if (!existingUser) {
+ showToast(`User ${user.username} no longer exists`, 'warning');
+ showUsersList(); // Refresh the list
+ return;
+ }
+
+ // User exists, proceed with deletion
+ testUserDeletion(user.id);
+ })
+ .catch(error => {
+ checkingToast.remove();
+ console.error('Error checking if user exists:', error);
+ showToast(window.t('messages.error_checking_if_user_exists', { error: error.message }), 'error');
+
+ // Ask if they want to try deletion anyway
+ if (confirm(`Error checking if user ${user.username} exists. Try deletion anyway?`)) {
+ testUserDeletion(user.id);
+ } else {
+ showUsersList(); // Refresh the list
+ }
+ });
+ }
+ });
+ }
+
+ actionsCell.appendChild(deleteButton);
+
+ // Add all cells to the row
+ row.appendChild(idCell);
+ row.appendChild(usernameCell);
+ row.appendChild(emailCell);
+ row.appendChild(nameCell);
+ row.appendChild(adminCell);
+ row.appendChild(activeCell);
+ row.appendChild(actionsCell);
+
+ // Add the row to the table body
+ tbody.appendChild(row);
+ });
+
+ table.appendChild(tbody);
+
+ // Add the header and table to the modal content
+ modalContent.appendChild(modalHeader);
+ modalContent.appendChild(table);
+
+ // Add the modal content to the modal
+ modal.appendChild(modalContent);
+
+ // Add the modal to the page
+ document.body.appendChild(modal);
+
+ console.log('Users list displayed');
+ })
+ .catch(error => {
+ console.error('Error fetching users:', error);
+ alert('Error fetching users: ' + error.message);
+ });
+
+ console.log('=== SHOW USERS LIST COMPLETED ===');
+}
+
+/**
+ * Promise-based version of findUserIdByUsername
+ * @param {string} username - The username to look up
+ * @returns {Promise<number|null>} - Promise that resolves to the user ID or null if not found
+ */
+function findUserIdByUsernameAsync(username) {
+ return new Promise((resolve, reject) => {
+ findUserIdByUsername(username, (err, userId) => {
+ if (err) reject(err);
+ else resolve(userId);
+ });
+ });
+}
+
+/**
+ * Check if a user exists by ID or username
+ * @param {string|number} userIdOrUsername - The user ID or username to check
+ * @returns {Promise<Object|null>} - Promise that resolves to the user object if found, null otherwise
+ */
+function checkUserExists(userIdOrUsername) {
+ console.log('=== CHECK USER EXISTS STARTED ===');
+ console.log('Checking if user exists:', userIdOrUsername);
+
+ return new Promise((resolve, reject) => {
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ reject(new Error(`Failed to fetch users list: ${response.status}`));
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) {
+ resolve(null);
+ return;
+ }
+
+ console.log('Fetched users list for checking existence');
+
+ // Check if the input is a numeric ID
+ if (!isNaN(userIdOrUsername)) {
+ // Convert to number for comparison
+ const userId = Number(userIdOrUsername);
+ const user = users.find(u => u.id === userId);
+
+ if (user) {
+ console.log('Found user by ID:', user);
+ resolve(user);
+ } else {
+ console.log('User not found with ID:', userId);
+ resolve(null);
+ }
+ } else {
+ // Assume it's a username
+ const user = users.find(u => u.username === userIdOrUsername);
+
+ if (user) {
+ console.log('Found user by username:', user);
+ resolve(user);
+ } else {
+ console.log('User not found with username:', userIdOrUsername);
+ resolve(null);
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error checking if user exists:', error);
+ reject(error);
+ });
+ });
+}
+
+/**
+ * Test user deletion functionality
+ * @param {string|number} userId - The user ID or username to delete
+ */
+function testUserDeletion(userId) {
+ console.log('=== TEST USER DELETION STARTED ===');
+ console.log('Attempting to delete user:', userId);
+
+ // Check if we have a valid user ID
+ if (!userId) {
+ console.error('No user ID provided');
+ alert('Error: No user ID provided');
+ return;
+ }
+
+ // Show a loading indicator
+ const loadingToast = showToast('Checking user...', 'info', 0); // 0 means no auto-hide
+
+ // First check if the user exists
+ checkUserExists(userId)
+ .then(user => {
+ if (!user) {
+ loadingToast.remove();
+ showToast(`User with ID/username "${userId}" not found`, 'error');
+ return;
+ }
+
+ // Update the loading toast
+ loadingToast.remove();
+ const deletingToast = showToast(`Deleting user ${user.username} (ID: ${user.id})...`, 'info', 0);
+
+ // Use our improved deletion function with the numeric ID
+ return superEmergencyDelete(user.id)
+ .then(success => {
+ // Hide the loading toast
+ if (deletingToast) {
+ deletingToast.remove();
+ }
+
+ if (success) {
+ console.log('User deletion successful');
+ showToast(`User ${user.username} deleted successfully!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ console.error('User deletion failed');
+ showToast(`Failed to delete user ${user.username}. Check console for details.`, 'error');
+
+ // Offer to try direct API call
+ if (confirm(`Would you like to try a direct API call to delete user ${user.username}?`)) {
+ const directToast = showToast(`Trying direct API call for user ${user.username}...`, 'info', 0);
+
+ directDeleteUserAPI(user.id)
+ .then(directSuccess => {
+ directToast.remove();
+
+ if (directSuccess) {
+ showToast(`User ${user.username} deleted successfully with direct API call!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ showToast(window.t('messages.failed_to_delete_user_with_direct_api_call', { username: user.username }), 'error');
+ }
+ })
+ .catch(error => {
+ directToast.remove();
+ console.error('Error with direct API call:', error);
+ showToast('Error with direct API call: ' + error.message, 'error');
+ });
+ }
+ }
+ })
+ .catch(error => {
+ // Hide the loading toast
+ if (deletingToast) {
+ deletingToast.remove();
+ }
+
+ console.error('Error during user deletion:', error);
+ showToast('Error during user deletion: ' + error.message, 'error');
+ });
+ })
+ .catch(error => {
+ loadingToast.remove();
+ console.error('Error checking if user exists:', error);
+ showToast('Error checking if user exists: ' + error.message, 'error');
+ });
+
+ console.log('=== TEST USER DELETION COMPLETED ===');
+}
+
+/**
+ * Close all modals
+ */
+function closeAllModals() {
+ console.log('Closing all modals');
+
+ // Get all modals
+ const modals = document.querySelectorAll('.modal-backdrop');
+
+ // Close each modal
+ modals.forEach(modal => {
+ console.log('Closing modal:', modal.id);
+ modal.style.display = 'none';
+ });
+
+ // Also reset any form fields
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ if (confirmDeleteAccountBtn) {
+ confirmDeleteAccountBtn.disabled = true;
+ }
+ }
+
+ // Reset password form
+ resetPasswordForm();
+
+ console.log('All modals closed');
+}
+
+/**
+ * Load site settings
+ */
+async function loadSiteSettings() {
+ console.log('Loading site settings...');
+
+ // Enhanced debugging for element availability
+ console.log('[SiteSettings Debug] DOM readiness check:');
+ console.log(' - document.readyState:', document.readyState);
+ console.log(' - adminSection exists:', !!document.getElementById('adminSection'));
+ console.log(' - registrationEnabled exists:', !!document.getElementById('registrationEnabled'));
+ console.log(' - oidcEnabled exists:', !!document.getElementById('oidcEnabled'));
+ console.log(' - oidcProviderName exists:', !!document.getElementById('oidcProviderName'));
+ console.log(' - oidcClientId exists:', !!document.getElementById('oidcClientId'));
+
+ // Query elements locally within this function scope for population
+ const registrationToggleElem = document.getElementById('registrationEnabled');
+ const emailBaseUrlFieldElem = document.getElementById('emailBaseUrl');
+ const globalViewToggleElem = document.getElementById('globalViewEnabled');
+ const globalViewAdminOnlyToggleElem = document.getElementById('globalViewAdminOnly');
+ const oidcEnabledToggleElem = document.getElementById('oidcEnabled');
+ const oidcOnlyModeToggleElem = document.getElementById('oidcOnlyMode');
+ const oidcProviderNameInputElem = document.getElementById('oidcProviderName');
+ const oidcClientIdInputElem = document.getElementById('oidcClientId');
+ const oidcClientSecretInputElem = document.getElementById('oidcClientSecret');
+ const oidcIssuerUrlInputElem = document.getElementById('oidcIssuerUrl');
+ const oidcScopeInputElem = document.getElementById('oidcScope');
+ const oidcAdminGroupInputElem = document.getElementById('oidcAdminGroup');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.status === 403) {
+ // User is not admin, hide admin settings sections
+ console.log('User is not admin, hiding admin settings sections');
+ const adminSection = document.getElementById('adminSection');
+ if (adminSection) {
+ adminSection.style.display = 'none';
+ }
+ return;
+ }
+
+ if (!response.ok) {
+ throw new Error(`Failed to load site settings: ${response.status} ${response.statusText}`);
+ }
+
+ const settings = await response.json();
+ console.log('[SiteSettings] Raw settings received from API:', settings);
+
+ if (registrationToggleElem) {
+ registrationToggleElem.checked = settings.registration_enabled === 'true';
+ } else {
+ console.error('[SiteSettings] registrationEnabled element NOT FOUND locally.');
+ }
+
+ if (emailBaseUrlFieldElem) {
+ emailBaseUrlFieldElem.value = settings.email_base_url || 'http://localhost:8080';
+ } else {
+ console.error('[SiteSettings] emailBaseUrl element NOT FOUND locally.');
+ }
+
+ if (globalViewToggleElem) {
+ globalViewToggleElem.checked = settings.global_view_enabled === 'true';
+ } else {
+ console.error('[SiteSettings] globalViewEnabled element NOT FOUND locally.');
+ }
+
+ if (globalViewAdminOnlyToggleElem) {
+ globalViewAdminOnlyToggleElem.checked = settings.global_view_admin_only === 'true';
+ } else {
+ console.error('[SiteSettings] globalViewAdminOnly element NOT FOUND locally.');
+ }
+
+ // Populate OIDC settings using locally-scoped element variables
+ if (oidcEnabledToggleElem) {
+ console.log('[OIDC Settings] Found oidcEnabledToggleElem. Setting checked to:', settings.oidc_enabled === 'true');
+ oidcEnabledToggleElem.checked = settings.oidc_enabled === 'true';
+ } else {
+ console.error('[OIDC Settings] oidcEnabledToggleElem element NOT FOUND locally.');
+ }
+
+ if (oidcOnlyModeToggleElem) {
+ console.log('[OIDC Settings] Found oidcOnlyModeToggleElem. Setting checked to:', settings.oidc_only_mode === 'true');
+ oidcOnlyModeToggleElem.checked = settings.oidc_only_mode === 'true';
+ } else {
+ console.error('[OIDC Settings] oidcOnlyModeToggleElem element NOT FOUND locally.');
+ }
+
+ if (oidcProviderNameInputElem) {
+ console.log('[OIDC Settings] Found oidcProviderNameInputElem. Setting value to:', settings.oidc_provider_name || 'oidc');
+ oidcProviderNameInputElem.value = settings.oidc_provider_name || 'oidc';
+ } else {
+ console.error('[OIDC Settings] oidcProviderNameInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcClientIdInputElem) {
+ console.log('[OIDC Settings] Found oidcClientIdInputElem. Setting value to:', settings.oidc_client_id || '');
+ oidcClientIdInputElem.value = settings.oidc_client_id || '';
+ } else {
+ console.error('[OIDC Settings] oidcClientIdInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcClientSecretInputElem) {
+ console.log('[OIDC Settings] Found oidcClientSecretInputElem. Setting placeholder based on oidc_client_secret_set:', settings.oidc_client_secret_set);
+ oidcClientSecretInputElem.value = ''; // Always clear on load
+ oidcClientSecretInputElem.placeholder = settings.oidc_client_secret_set ? '******** (Set - Enter new to change)' : 'Enter OIDC Client Secret';
+ } else {
+ console.error('[OIDC Settings] oidcClientSecretInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcIssuerUrlInputElem) {
+ console.log('[OIDC Settings] Found oidcIssuerUrlInputElem. Setting value to:', settings.oidc_issuer_url || '');
+ oidcIssuerUrlInputElem.value = settings.oidc_issuer_url || '';
+ } else {
+ console.error('[OIDC Settings] oidcIssuerUrlInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcScopeInputElem) {
+ console.log('[OIDC Settings] Found oidcScopeInputElem. Setting value to:', settings.oidc_scope || 'openid email profile');
+ oidcScopeInputElem.value = settings.oidc_scope || 'openid email profile';
+ } else {
+ console.error('[OIDC Settings] oidcScopeInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcAdminGroupInputElem) {
+ console.log('[OIDC Settings] Found oidcAdminGroupInputElem. Setting value to:', settings.oidc_admin_group || '');
+ oidcAdminGroupInputElem.value = settings.oidc_admin_group || '';
+ } else {
+ console.error('[OIDC Settings] oidcAdminGroupInputElem element NOT FOUND locally.');
+ }
+
+ console.log('Site and OIDC settings loaded and population attempted using locally queried elements.');
+
+ } catch (error) {
+ console.error('Error loading or populating site settings:', error);
+ showToast('Failed to load site settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Save site settings (non-OIDC part)
+ */
+async function saveSiteSettings() {
+ console.log('Saving site settings (non-OIDC)...');
+ const registrationToggle = document.getElementById('registrationEnabled');
+ const emailBaseUrlField = document.getElementById('emailBaseUrl');
+ const globalViewToggle = document.getElementById('globalViewEnabled');
+ const globalViewAdminOnlyToggle = document.getElementById('globalViewAdminOnly');
+
+ const settingsToSave = {};
+
+ if (registrationToggle) {
+ settingsToSave.registration_enabled = registrationToggle.checked;
+ }
+
+ if (globalViewToggle) {
+ settingsToSave.global_view_enabled = globalViewToggle.checked;
+ }
+
+ if (globalViewAdminOnlyToggle) {
+ settingsToSave.global_view_admin_only = globalViewAdminOnlyToggle.checked;
+ }
+
+ if (emailBaseUrlField) {
+ let baseUrl = emailBaseUrlField.value.trim();
+ if (baseUrl && (baseUrl.startsWith('http://') || baseUrl.startsWith('https://'))) {
+ if (baseUrl.endsWith('/')) {
+ baseUrl = baseUrl.slice(0, -1);
+ }
+ settingsToSave.email_base_url = baseUrl;
+ } else if (baseUrl) {
+ showToast('Invalid Email Base URL format. It should start with http:// or https://', 'error');
+ return;
+ } else {
+ settingsToSave.email_base_url = 'http://localhost:8080';
+ emailBaseUrlField.value = settingsToSave.email_base_url;
+ }
+ }
+
+ if (Object.keys(settingsToSave).length === 0) {
+ showToast('No site settings to save.', 'info');
+ return;
+ }
+
+ try {
+ showLoading();
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving site settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(settingsToSave)
+ });
+
+ const result = await response.json();
+ if (response.ok) {
+ showToast(result.message || 'Site settings saved successfully', 'success');
+ } else {
+ showToast(result.message || window.t('messages.failed_to_save_site_settings'), 'error');
+ }
+ } catch (error) {
+ console.error('Error saving site settings:', error);
+ showToast('Failed to save site settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+
+/**
+ * Save OIDC settings
+ */
+async function saveOidcSettings() {
+ console.log('Saving OIDC settings...');
+ const oidcSettingsPayload = {
+ oidc_enabled: oidcEnabledToggle ? oidcEnabledToggle.checked : false,
+ oidc_only_mode: oidcOnlyModeToggle ? oidcOnlyModeToggle.checked : false,
+ oidc_provider_name: oidcProviderNameInput ? oidcProviderNameInput.value.trim() : 'oidc',
+ oidc_client_id: oidcClientIdInput ? oidcClientIdInput.value.trim() : '',
+ oidc_issuer_url: oidcIssuerUrlInput ? oidcIssuerUrlInput.value.trim() : '',
+ oidc_scope: oidcScopeInput ? oidcScopeInput.value.trim() : 'openid email profile',
+ oidc_admin_group: oidcAdminGroupInput ? oidcAdminGroupInput.value.trim() : ''
+ };
+
+ // Only include client_secret if a new value is entered
+ if (oidcClientSecretInput && oidcClientSecretInput.value) {
+ oidcSettingsPayload.oidc_client_secret = oidcClientSecretInput.value;
+ }
+
+ try {
+ showLoading();
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving OIDC settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(oidcSettingsPayload)
+ });
+
+ const result = await response.json();
+ if (response.ok) {
+ showToast(result.message || 'OIDC settings saved successfully.', 'success');
+ if (result.message && result.message.includes("restart is required")) {
+ if(oidcRestartMessage) oidcRestartMessage.style.display = 'block';
+ } else {
+ if(oidcRestartMessage) oidcRestartMessage.style.display = 'none';
+ }
+ // Clear the secret field after attempting to save
+ if (oidcClientSecretInput) oidcClientSecretInput.value = '';
+ // Reload settings to get the oidc_client_secret_set flag updated
+ loadSiteSettings();
+ } else {
+ showToast(result.message || 'Failed to save OIDC settings.', 'error');
+ }
+ } catch (error) {
+ console.error('Error saving OIDC settings:', error);
+ showToast('Failed to save OIDC settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Set up the delete button for user deletion
+ */
+function setupDeleteButton() {
+ console.log('=== SETUP DELETE BUTTON STARTED ===');
+
+ // Get the confirm delete button
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (!confirmDeleteUserBtn) {
+ console.error('confirmDeleteUserBtn not found in setupDeleteButton');
+ return;
+ }
+
+ try {
+ // Get the user ID from various possible sources
+ let userId = window.currentDeleteUserId || null;
+
+ if (!userId && document.getElementById('deleteUserId')) {
+ userId = document.getElementById('deleteUserId').value;
+ }
+
+ if (!userId && document.getElementById('editUserId')) {
+ userId = document.getElementById('editUserId').value;
+ }
+
+ if (!userId && document.getElementById('displayUserId')) {
+ userId = document.getElementById('displayUserId').textContent;
+ }
+
+ console.log('Setting up delete button for user ID:', userId);
+
+ // Remove existing event listeners by cloning
+ const newBtn = confirmDeleteUserBtn.cloneNode(true);
+ confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
+
+ // Add new event listener
+ newBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked in setupDeleteButton');
+ deleteUser();
+ return false;
+ });
+
+ // Also set onclick for redundancy
+ newBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via onclick in setupDeleteButton');
+ deleteUser();
+ return false;
+ };
+
+ console.log('Delete button set up successfully');
+ } catch (error) {
+ console.error('Error setting up delete button:', error);
+ }
+
+ console.log('=== SETUP DELETE BUTTON COMPLETED ===');
+}
+
+/**
+ * Direct API call for user deletion
+ * @param {string|number} userId - The user ID or username to delete
+ * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
+ */
+function directDeleteUserAPI(userId) {
+ console.log('=== DIRECT DELETE API CALL STARTED ===');
+ console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
+
+ return new Promise((resolve, reject) => {
+ // Try to get the user ID from multiple sources if not provided
+ if (!userId) {
+ const deleteUserIdField = document.getElementById('deleteUserId');
+ const editUserIdField = document.getElementById('editUserId');
+ const displayUserIdField = document.getElementById('displayUserId');
+
+ userId = window.currentDeleteUserId;
+
+ if (!userId && deleteUserIdField && deleteUserIdField.value) {
+ userId = deleteUserIdField.value;
+ } else if (!userId && editUserIdField && editUserIdField.value) {
+ userId = editUserIdField.value;
+ } else if (!userId && displayUserIdField && displayUserIdField.textContent) {
+ userId = displayUserIdField.textContent;
+ }
+ }
+
+ console.log('User ID to delete:', userId);
+
+ if (!userId) {
+ console.error('Direct delete API call failed: User ID is missing');
+ reject(new Error('User ID is missing'));
+ return;
+ }
+
+ // Check if the input is a username rather than a numeric ID
+ if (isNaN(userId)) {
+ console.log('Input appears to be a username, not a numeric ID');
+ // Try to find the user ID by username
+ findUserIdByUsernameAsync(userId)
+ .then(numericId => {
+ if (numericId) {
+ console.log(`Found numeric ID ${numericId} for username ${userId}`);
+ // Call this function again with the numeric ID
+ return directDeleteUserAPI(numericId);
+ } else {
+ throw new Error(`Could not find a user with username "${userId}"`);
+ }
+ })
+ .then(resolve)
+ .catch(reject);
+ return;
+ }
+
+ console.log('Proceeding with numeric user ID:', userId);
+
+ // Get the token with detailed logging
+ const token = localStorage.getItem('auth_token');
+ console.log('Token exists:', !!token);
+ console.log('Token length:', token ? token.length : 0);
+
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Log the API endpoint
+ const apiEndpoint = `/api/admin/users/${userId}`;
+ console.log('Direct API endpoint:', apiEndpoint);
+
+ // Create headers with detailed logging
+ const headers = {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ };
+ console.log('Direct API request headers:', Object.keys(headers));
+
+ // Make the fetch request with detailed logging
+ console.log('Direct API fetch request configuration:', {
+ method: 'DELETE',
+ headers: Object.keys(headers),
+ credentials: 'same-origin'
+ });
+
+ // Make a fetch API call
+ fetch(apiEndpoint, {
+ method: 'DELETE',
+ headers: headers,
+ credentials: 'same-origin' // Include cookies
+ })
+ .then(response => {
+ console.log('Direct API response received');
+ console.log('Direct API response status:', response.status);
+ console.log('Direct API response status text:', response.statusText);
+ console.log('Direct API response headers:', [...response.headers.entries()]);
+ console.log('Direct API response type:', response.type);
+ console.log('Direct API response URL:', response.url);
+
+ // Get the raw text first
+ return response.text().then(text => {
+ console.log('Direct API raw response text:', text);
+ try {
+ const data = text ? JSON.parse(text) : {};
+ return {
+ status: response.status,
+ data: data
+ };
+ } catch (err) {
+ console.log('Error parsing Direct API JSON response:', err);
+ return {
+ status: response.status,
+ data: { message: text || 'No response data or invalid JSON' }
+ };
+ }
+ });
+ })
+ .then(result => {
+ console.log('Direct API response data:', result);
+
+ if (result.status >= 200 && result.status < 300) {
+ console.log('Direct API call successful');
+ resolve(true);
+ } else {
+ const errorMessage = result.data && result.data.message ? result.data.message : 'Failed to delete user';
+ console.error('Direct API call failed:', errorMessage);
+ resolve(false); // Resolve with false instead of rejecting
+ }
+ })
+ .catch(error => {
+ console.error('Direct API call error:', error);
+ console.error('Direct API call error details:', error.message, error.stack);
+ reject(error);
+ });
+ });
+}
+
+/**
+ * Check if the API endpoint is accessible
+ */
+function checkApiEndpoint() {
+ console.log('Checking API endpoint accessibility...');
+
+ // Try to access a simple API endpoint
+ fetch('/api/auth/validate-token', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ })
+ .then(response => {
+ console.log('API endpoint check response status:', response.status);
+ if (response.ok) {
+ console.log('API endpoint is accessible');
+ showToast('API endpoint is accessible', 'success');
+ } else {
+ console.error('API endpoint is not accessible');
+ showToast('API endpoint is not accessible. Status: ' + response.status, 'error');
+ }
+ return response.json().catch(() => ({}));
+ })
+ .then(data => {
+ console.log('API endpoint check response data:', data);
+ })
+ .catch(error => {
+ console.error('Error checking API endpoint:', error);
+ showToast('Error checking API endpoint: ' + error.message, 'error');
+ });
+}
+
+/**
+ * Trigger warranty expiration notifications (admin only)
+ */
+async function triggerWarrantyNotifications() {
+ console.log('Trigger warranty notifications requested');
+
+ // Check if admin
+ try {
+ const response = await fetch('/api/auth/user', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to check user status');
+ }
+
+ const userData = await response.json();
+
+ if (!userData.is_admin) {
+ showToast('Only administrators can send warranty notifications', 'error');
+ return;
+ }
+
+ // Show confirmation dialog
+ if (!confirm('Are you sure you want to send warranty expiration notifications to all eligible users? This will immediately email users with warranties expiring soon.')) {
+ return;
+ }
+
+ showLoading();
+
+ // Call the API endpoint to trigger notifications
+ const notificationResponse = await fetch('/api/admin/send-notifications', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!notificationResponse.ok) {
+ const errorData = await notificationResponse.json();
+ throw new Error(errorData.message || 'Failed to send notifications');
+ }
+
+ const result = await notificationResponse.json();
+ showToast(result.message || 'Notifications triggered successfully', 'success');
+
+ } catch (error) {
+ console.error('Error triggering notifications:', error);
+ showToast('Error: ' + error.message, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Check scheduler status (admin only)
+ */
+async function checkSchedulerStatus() {
+ console.log('Checking scheduler status...');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/scheduler-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: 'Unknown error occurred' }));
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const status = await response.json();
+ console.log('Scheduler status:', status);
+
+ // Format the status information for display
+ let message = '📊 Scheduler Status Report\n\n';
+ message += `🚀 Initialized: ${status.scheduler_initialized ? '✅ Yes' : '❌ No'}\n`;
+ message += `🔄 Running: ${status.scheduler_running ? '✅ Yes' : '❌ No'}\n`;
+ message += `📋 Active Jobs: ${status.scheduler_jobs.length}\n`;
+
+ if (status.scheduler_jobs.length > 0) {
+ message += '\n📅 Scheduled Jobs:\n';
+ status.scheduler_jobs.forEach(job => {
+ const nextRun = job.next_run_time ?
+ new Date(job.next_run_time).toLocaleString() :
+ 'Not scheduled';
+ message += `• ${job.id}: ${nextRun}\n`;
+ message += ` Trigger: ${job.trigger}\n`;
+ });
+ }
+
+ message += `\n🔧 Worker Information:\n`;
+ message += `• Worker ID: ${status.worker_info.worker_id}\n`;
+ message += `• Worker Name: ${status.worker_info.worker_name}\n`;
+ message += `• Worker Class: ${status.worker_info.worker_class}\n`;
+ message += `• Should Run Scheduler: ${status.worker_info.should_run_scheduler ? '✅ Yes' : '❌ No'}\n`;
+
+ if (status.environment_vars && Object.keys(status.environment_vars).length > 0) {
+ message += `\n🌍 Environment Variables:\n`;
+ Object.entries(status.environment_vars).forEach(([key, value]) => {
+ message += `• ${key}: ${value}\n`;
+ });
+ }
+
+ // Show in alert dialog
+ alert(message);
+
+ // Also show a toast with a summary
+ const summary = status.scheduler_running ?
+ '✅ Scheduler is running normally' :
+ '⚠️ Scheduler is not running - notifications may not be sent automatically';
+ showToast(summary, status.scheduler_running ? 'success' : 'warning', 8000);
+
+ } catch (error) {
+ console.error('Error checking scheduler status:', error);
+ showToast(`Error checking scheduler status: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Load available timezones from the API
+ * @returns {Promise} A promise that resolves when timezones are loaded
+ */
+function loadTimezones() {
+ return loadTimezonesIntoSelect(timezoneSelect);
+}
+
+function loadTimezonesIntoSelect(selectElement) {
+ if (!selectElement) {
+ return Promise.reject('Select element not provided to loadTimezonesIntoSelect');
+ }
+ console.log(`Loading timezones into ${selectElement.id}...`);
+ return new Promise((resolve, reject) => {
+ fetch('/api/timezones', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to load timezones');
+ }
+ return response.json();
+ })
+ .then(timezoneGroups => {
+ // Clear loading option
+ selectElement.innerHTML = '';
+
+ // Add timezone groups and their options
+ timezoneGroups.forEach(group => {
+ const optgroup = document.createElement('optgroup');
+ optgroup.label = group.region;
+
+ group.timezones.forEach(timezone => {
+ const option = document.createElement('option');
+ option.value = timezone.value;
+ option.textContent = timezone.label;
+ optgroup.appendChild(option);
+ });
+
+ selectElement.appendChild(optgroup);
+ });
+
+ // Set the current timezone from preferences
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ const savedPreferences = JSON.parse(localStorage.getItem(`${prefix}preferences`) || '{}');
+
+ console.log('Loading timezone preference from localStorage', {
+ prefix: prefix,
+ preferenceKey: `${prefix}preferences`,
+ savedTimezone: savedPreferences.timezone
+ });
+
+ if (savedPreferences.timezone) {
+ selectElement.value = savedPreferences.timezone;
+ console.log(`Set ${selectElement.id} to:`, savedPreferences.timezone, 'Current value:', selectElement.value);
+ resolve();
+ } else {
+ // If no timezone preference found in localStorage, load from API as backup
+ console.log('No timezone found in localStorage, fetching from API');
+ fetch('/api/auth/preferences', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => response.json())
+ .then(data => {
+ // API returns preferences directly, not nested
+ if (data && data.timezone) {
+ console.log('Received timezone from API:', data.timezone);
+ selectElement.value = data.timezone;
+ console.log(`Set ${selectElement.id} to:`, data.timezone, 'Current value:', selectElement.value);
+ }
+ resolve();
+ })
+ .catch(error => {
+ console.error('Error loading preferences from API:', error);
+ resolve(); // Still resolve to continue the chain
+ });
+ }
+ })
+ .catch(error => {
+ console.error('Error loading timezones:', error);
+ selectElement.innerHTML = '<option value="UTC">UTC (Coordinated Universal Time)</option>';
+ reject(error);
+ });
+ });
+}
+
+/**
+ * Save email settings
+ */
+function toggleNotificationSettings(channel) {
+ if (emailSettingsContainer) {
+ emailSettingsContainer.style.display = (channel === 'email' || channel === 'both') ? 'block' : 'none';
+ }
+ if (userAppriseSettingsContainer) {
+ userAppriseSettingsContainer.style.display = (channel === 'apprise' || channel === 'both') ? 'block' : 'none';
+ }
+}
+
+async function saveNotificationSettings() {
+ showLoading();
+
+ try {
+ const preferences = {
+ notification_channel: notificationChannel.value,
+ notification_frequency: notificationFrequencySelect.value,
+ notification_time: notificationTimeInput.value,
+ apprise_notification_time: userAppriseNotificationTimeInput ? userAppriseNotificationTimeInput.value : '09:00',
+ apprise_notification_frequency: userAppriseNotificationFrequency ? userAppriseNotificationFrequency.value : 'daily',
+ timezone: timezoneSelect.value,
+ apprise_timezone: userAppriseTimezoneSelect ? userAppriseTimezoneSelect.value : 'UTC'
+ };
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving notification settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferences)
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save notification settings');
+ }
+
+ showToast('Notification settings saved successfully', 'success');
+ } catch (error) {
+ console.error('Error saving notification settings:', error);
+ showToast(`Error saving notification settings: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+// --- Add Storage Event Listener for Real-time Sync ---
+window.addEventListener('storage', (event) => {
+ console.log(`[Settings Storage Listener] Event received: key=${event.key}, newValue=${event.newValue}`); // Log all events
+
+ const prefix = getPreferenceKeyPrefix();
+ const targetKey = `${prefix}defaultView`;
+
+ // Only react to changes in the specific default view key for the current user type
+ if (event.key === targetKey) { // Check key match first
+ console.log(`[Settings Storage Listener] Matched key: ${targetKey}`);
+ console.log(`[Settings Storage Listener] defaultViewSelect exists: ${!!defaultViewSelect}`);
+ if (defaultViewSelect) {
+ console.log(`[Settings Storage Listener] Current dropdown value: ${defaultViewSelect.value}`);
+ }
+ console.log(`[Settings Storage Listener] Event newValue: ${event.newValue}`);
+
+ if (event.newValue && defaultViewSelect && defaultViewSelect.value !== event.newValue) {
+ console.log(`[Settings Storage Listener] Value changed and dropdown exists. Checking options...`);
+ const optionExists = [...defaultViewSelect.options].some(option => option.value === event.newValue);
+ console.log(`[Settings Storage Listener] Option ${event.newValue} exists: ${optionExists}`);
+ if (optionExists) {
+ defaultViewSelect.value = event.newValue;
+ console.log(`[Settings Storage Listener] SUCCESS: Updated settings default view dropdown via storage event to ${event.newValue}.`);
+ } else {
+ console.warn(`[Settings Storage Listener] Storage event value (${event.newValue}) not found in dropdown options.`);
+ }
+ } else if (!event.newValue) {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because newValue is null/empty.`);
+ } else if (!defaultViewSelect) {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because defaultViewSelect element not found.`);
+ } else {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because value hasn't changed (${defaultViewSelect.value} === ${event.newValue}).`);
+ }
+ }
+
+ // Add similar checks for other preferences if needed, e.g., dateFormat, currencySymbol
+ if (event.key === 'dateFormat') { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] dateFormat changed to ${event.newValue}`);
+ if (event.newValue && dateFormatSelect && dateFormatSelect.value !== event.newValue) {
+ const optionExists = [...dateFormatSelect.options].some(option => option.value === event.newValue);
+ if (optionExists) {
+ dateFormatSelect.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings date format dropdown via storage event.');
+ }
+ }
+ }
+
+ if (event.key === `${prefix}currencySymbol`) { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] ${prefix}currencySymbol changed to ${event.newValue}`);
+ if (event.newValue && currencySymbolSelect && currencySymbolSelect.value !== event.newValue) {
+ // Handle standard vs custom symbol update
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === event.newValue);
+ if (standardOption) {
+ currencySymbolSelect.value = event.newValue;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log('[Settings Storage Listener] Updated settings currency dropdown via storage event.');
+ } else if (currencySymbolSelect.value !== 'other' || (currencySymbolCustom && currencySymbolCustom.value !== event.newValue)) {
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = event.newValue;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ console.log('[Settings Storage Listener] Updated settings currency dropdown to custom via storage event.');
+ }
+ }
+ }
+
+ // Add check for expiringSoonDays
+ if (event.key === `${prefix}expiringSoonDays`) { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] ${prefix}expiringSoonDays changed to ${event.newValue}`);
+ if (event.newValue && expiringSoonDaysInput && expiringSoonDaysInput.value !== event.newValue) {
+ expiringSoonDaysInput.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings expiring soon days input via storage event.');
+ }
+ }
+
+ // Add check for currencyPosition
+ if (event.key === `${prefix}currencyPosition`) {
+ console.log(`[Settings Storage Listener] ${prefix}currencyPosition changed to ${event.newValue}`);
+ if (event.newValue && currencyPositionSelect && currencyPositionSelect.value !== event.newValue) {
+ currencyPositionSelect.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings currency position dropdown via storage event.');
+ }
+ }
+
+});
+// --- End Storage Event Listener ---
+
+// Add event listener for dropdown to show/hide custom input
+if (currencySymbolSelect && currencySymbolCustom) {
+ currencySymbolSelect.addEventListener('change', function() {
+ if (this.value === 'other') {
+ currencySymbolCustom.style.display = '';
+ currencySymbolCustom.focus();
+ } else {
+ currencySymbolCustom.style.display = 'none';
+ currencySymbolCustom.value = '';
+ }
+ });
+}
+
+// =====================
+// APPRISE NOTIFICATIONS FUNCTIONALITY
+// =====================
+
+/**
+ * Load Apprise settings and status
+ */
+async function loadAppriseSettings() {
+ try {
+ // Get current Apprise status
+ const statusResponse = await fetch('/api/admin/apprise/status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (statusResponse.status === 403) {
+ // User is not admin, hide Apprise section
+ const appriseCard = document.querySelector('.card:has(#appriseStatusBadge)');
+ if (appriseCard) {
+ appriseCard.style.display = 'none';
+ }
+ return;
+ }
+
+ if (statusResponse.status === 503) {
+ // Apprise not available
+ if (appriseNotAvailable) appriseNotAvailable.style.display = 'block';
+ if (appriseStatusBadge) appriseStatusBadge.textContent = 'Not Available';
+ if (appriseStatusBadge) appriseStatusBadge.className = 'badge badge-danger';
+ return;
+ }
+
+ const statusData = await statusResponse.json();
+
+ // Update status badge
+ if (appriseStatusBadge) {
+ if (statusData.available && statusData.enabled) {
+ appriseStatusBadge.textContent = 'Active';
+ appriseStatusBadge.className = 'badge badge-success';
+ } else if (statusData.available) {
+ appriseStatusBadge.textContent = 'Disabled';
+ appriseStatusBadge.className = 'badge badge-warning';
+ } else {
+ appriseStatusBadge.textContent = 'Not Available';
+ appriseStatusBadge.className = 'badge badge-danger';
+ }
+ }
+
+ // Update status display
+ if (appriseUrlsCount) appriseUrlsCount.textContent = statusData.urls_configured || 0;
+ if (currentAppriseExpirationDays) currentAppriseExpirationDays.textContent = statusData.expiration_days ? statusData.expiration_days.join(', ') : '-';
+
+ // Load settings from site settings
+ await loadAppriseSiteSettings();
+
+ } catch (error) {
+ console.error('Error loading Apprise settings:', error);
+ if (appriseStatusBadge) {
+ appriseStatusBadge.textContent = 'Error';
+ appriseStatusBadge.className = 'badge badge-danger';
+ }
+ }
+}
+
+/**
+ * Load Apprise site settings
+ */
+async function loadAppriseSiteSettings() {
+ try {
+ console.log('📥 Loading Apprise site settings...');
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('📥 Load response status:', response.status);
+
+ if (!response.ok) {
+ console.warn('⚠️ Load response not OK, skipping settings load');
+ return;
+ }
+
+ const data = await response.json();
+ console.log('📥 Loaded settings data:', data);
+
+ // Check if Apprise settings exist in the data
+ const appriseKeys = Object.keys(data).filter(key => key.startsWith('apprise_'));
+ console.log('📥 Found Apprise keys:', appriseKeys);
+
+ // Update form fields
+ if (appriseEnabledToggle && data.apprise_enabled !== undefined) {
+ appriseEnabledToggle.checked = data.apprise_enabled === 'true';
+ console.log('✅ Set appriseEnabled:', data.apprise_enabled);
+
+ // Show/hide settings container based on enabled state
+ const settingsContainer = document.getElementById('appriseSettingsContainer');
+ if (settingsContainer) {
+ settingsContainer.style.display = data.apprise_enabled === 'true' ? 'block' : 'none';
+ }
+ } else {
+ console.log('⚠️ appriseEnabled element not found or apprise_enabled data missing');
+ }
+
+ if (appriseUrlsTextarea && data.apprise_urls) {
+ appriseUrlsTextarea.value = data.apprise_urls.replace(/,/g, '\n');
+ console.log('✅ Set appriseUrls:', data.apprise_urls);
+ } else {
+ console.log('⚠️ appriseUrlsTextarea element not found or apprise_urls data missing');
+ }
+
+ if (appriseExpirationDaysInput && data.apprise_expiration_days) {
+ appriseExpirationDaysInput.value = data.apprise_expiration_days;
+ console.log('✅ Set appriseExpirationDays:', data.apprise_expiration_days);
+ } else {
+ console.log('⚠️ appriseExpirationDaysInput element not found or data missing');
+ }
+
+
+
+ if (appriseTitlePrefixInput && data.apprise_title_prefix) {
+ appriseTitlePrefixInput.value = data.apprise_title_prefix;
+ console.log('✅ Set appriseTitlePrefix:', data.apprise_title_prefix);
+ } else {
+ console.log('⚠️ appriseTitlePrefixInput element not found or data missing');
+ }
+
+ if (appriseNotificationModeSelect && data.apprise_notification_mode) {
+ appriseNotificationModeSelect.value = data.apprise_notification_mode;
+ updateAppriseModeDescription(data.apprise_notification_mode);
+ console.log('✅ Set appriseNotificationMode:', data.apprise_notification_mode);
+ } else {
+ console.log('⚠️ appriseNotificationModeSelect element not found or data missing');
+ // Set default mode if not found
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.value = 'global';
+ updateAppriseModeDescription('global');
+ }
+ }
+
+ if (appriseWarrantyScopeSelect && data.apprise_warranty_scope) {
+ appriseWarrantyScopeSelect.value = data.apprise_warranty_scope;
+ updateAppriseScopeDescription(data.apprise_warranty_scope);
+ console.log('✅ Set appriseWarrantyScope:', data.apprise_warranty_scope);
+ } else {
+ console.log('⚠️ appriseWarrantyScopeSelect element not found or data missing');
+ // Set default scope if not found
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.value = 'all';
+ updateAppriseScopeDescription('all');
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error loading Apprise site settings:', error);
+ }
+}
+
+/**
+ * Save Apprise settings
+ */
+async function saveAppriseSettings() {
+ try {
+ console.log('🔍 Starting saveAppriseSettings...');
+ showLoading();
+
+ // Process URLs - convert newlines to commas and clean up
+ const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
+ const urls = urlsText.split(/[\n,]/)
+ .map(url => url.trim())
+ .filter(url => url.length > 0)
+ .join(',');
+
+ const settings = {
+ apprise_enabled: appriseEnabledToggle ? appriseEnabledToggle.checked.toString() : 'false',
+ apprise_notification_mode: appriseNotificationModeSelect ? appriseNotificationModeSelect.value : 'global',
+ apprise_warranty_scope: appriseWarrantyScopeSelect ? appriseWarrantyScopeSelect.value : 'all',
+ apprise_urls: urls,
+ apprise_expiration_days: appriseExpirationDaysInput ? appriseExpirationDaysInput.value : '7,30',
+ apprise_title_prefix: appriseTitlePrefixInput ? appriseTitlePrefixInput.value : '[Warracker]'
+ };
+
+ console.log('📋 Settings to save:', settings);
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('📡 Saving Apprise settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(settings)
+ });
+
+ console.log('📡 Response status:', response.status);
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('❌ Response error:', errorData);
+ throw new Error(errorData.message || 'Failed to save Apprise settings');
+ }
+
+ const responseData = await response.json();
+ console.log('✅ Save response:', responseData);
+
+ // Reload configuration
+ console.log('🔄 Reloading Apprise configuration...');
+ const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('🔄 Reload response status:', reloadResponse.status);
+
+ showToast('Apprise settings saved successfully', 'success');
+
+ // Reload status
+ console.log('📱 Reloading Apprise settings...');
+ await loadAppriseSettings();
+
+ } catch (error) {
+ console.error('❌ Error saving Apprise settings:', error);
+ showToast(`Error saving Apprise settings: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Send test Apprise notification
+ */
+async function sendTestAppriseNotification() {
+ try {
+ showLoading();
+
+ const testUrl = appriseTestUrlInput ? appriseTestUrlInput.value.trim() : null;
+
+ const payload = testUrl ? { test_url: testUrl } : {};
+
+ const response = await fetch('/api/admin/apprise/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(payload)
+ });
+
+ const data = await response.json();
+
+ if (data.success) {
+ showToast('Test notification sent successfully', 'success');
+ } else {
+ showToast(`Failed to send test notification: ${data.message}`, 'error');
+ }
+
+ } catch (error) {
+ console.error('Error sending test notification:', error);
+ showToast(`Error sending test notification: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Validate Apprise URLs
+ */
+async function validateAppriseUrls() {
+ try {
+ showLoading();
+
+ const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
+ const urls = urlsText.split(/[\n,]/)
+ .map(url => url.trim())
+ .filter(url => url.length > 0);
+
+ if (urls.length === 0) {
+ showToast('No URLs to validate', 'warning');
+ hideLoading();
+ return;
+ }
+
+ let validCount = 0;
+ let invalidUrls = [];
+
+ for (const url of urls) {
+ try {
+ const response = await fetch('/api/admin/apprise/validate-url', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ url: url })
+ });
+
+ const data = await response.json();
+
+ if (data.valid) {
+ validCount++;
+ } else {
+ invalidUrls.push(url);
+ }
+ } catch (error) {
+ invalidUrls.push(url);
+ }
+ }
+
+ let message = `Validation complete: ${validCount}/${urls.length} URLs are valid`;
+ if (invalidUrls.length > 0) {
+ message += `\nInvalid URLs: ${invalidUrls.join(', ')}`;
+ showToast(message, 'warning');
+ } else {
+ showToast(message, 'success');
+ }
+
+ } catch (error) {
+ console.error('Error validating URLs:', error);
+ showToast(`Error validating URLs: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Trigger Apprise expiration notifications
+ */
+async function triggerAppriseExpirationNotifications() {
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/apprise/send-expiration', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const data = await response.json();
+
+ if (data.success) {
+ showToast(data.message, 'success');
+ } else {
+ showToast(`Failed to trigger notifications: ${data.message}`, 'error');
+ }
+
+ } catch (error) {
+ console.error('Error triggering Apprise notifications:', error);
+ showToast(`Error triggering notifications: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * View supported services
+ */
+function viewSupportedAppriseServices() {
+ window.open('https://github.com/caronc/apprise/wiki', '_blank', 'noopener,noreferrer');
+}
+
+/**
+ * Save just the Apprise enabled/disabled state
+ */
+async function saveAppriseEnabledState(enabled) {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ apprise_enabled: enabled.toString()
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save Apprise enabled state');
+ }
+
+ // Reload configuration
+ const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('✅ Apprise enabled state saved:', enabled);
+
+ // Update status badge
+ await loadAppriseSettings();
+
+ } catch (error) {
+ console.error('❌ Error saving Apprise enabled state:', error);
+ showToast(`Error updating Apprise setting: ${error.message}`, 'error');
+
+ // Revert the toggle if save failed
+ if (appriseEnabledToggle) {
+ appriseEnabledToggle.checked = !enabled;
+ }
+ }
+}
+
+/**
+ * Update Apprise mode description text
+ */
+function updateAppriseModeDescription(mode) {
+ if (!appriseModeDescription) return;
+
+ if (mode === 'global') {
+ appriseModeDescription.textContent = 'A single, consolidated notification will be sent to the global Apprise channels defined below.';
+ } else if (mode === 'individual') {
+ appriseModeDescription.textContent = 'A separate notification will be sent for each user with expiring warranties. (Note: This currently uses the global channels. Per-user channels can be a future enhancement.)';
+ }
+}
+
+/**
+ * Update Apprise warranty scope description text
+ */
+function updateAppriseScopeDescription(scope) {
+ if (!appriseScopeDescription) return;
+
+ if (scope === 'all') {
+ appriseScopeDescription.textContent = 'Notifications will include expiring warranties from all users in the system.';
+ } else if (scope === 'admin') {
+ appriseScopeDescription.textContent = 'Notifications will only include expiring warranties belonging to the admin/owner user.';
+ }
+}
+
+/**
+ * Setup Apprise event listeners
+ */
+function setupAppriseEventListeners() {
+ // Enable/disable toggle
+ if (appriseEnabledToggle) {
+ appriseEnabledToggle.addEventListener('change', async function() {
+ const settingsContainer = document.getElementById('appriseSettingsContainer');
+ if (settingsContainer) {
+ settingsContainer.style.display = this.checked ? 'block' : 'none';
+ }
+
+ // Auto-save the enabled state
+ await saveAppriseEnabledState(this.checked);
+ });
+ }
+
+ // Notification mode change
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.addEventListener('change', (e) => {
+ updateAppriseModeDescription(e.target.value);
+ });
+ }
+
+ // Warranty scope change
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.addEventListener('change', (e) => {
+ updateAppriseScopeDescription(e.target.value);
+ });
+ }
+
+ // Save settings
+ if (saveAppriseSettingsBtn) {
+ saveAppriseSettingsBtn.addEventListener('click', saveAppriseSettings);
+ }
+
+ // Test notification
+ if (testAppriseBtn) {
+ testAppriseBtn.addEventListener('click', sendTestAppriseNotification);
+ }
+
+ // Validate URLs
+ if (validateAppriseUrlBtn) {
+ validateAppriseUrlBtn.addEventListener('click', validateAppriseUrls);
+ }
+
+ // Trigger expiration notifications
+ if (triggerAppriseNotificationsBtn) {
+ triggerAppriseNotificationsBtn.addEventListener('click', triggerAppriseExpirationNotifications);
+ }
+
+ // View supported services
+ if (viewSupportedServicesBtn) {
+ viewSupportedServicesBtn.addEventListener('click', viewSupportedAppriseServices);
+ }
+}
+
+// Initialize Apprise functionality
+document.addEventListener('DOMContentLoaded', function() {
+ setupAppriseEventListeners();
+
+ // Load Apprise settings after auth is ready (admin only)
+ setTimeout(() => {
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ const currentUser = window.auth.getCurrentUser();
+ if (currentUser && currentUser.is_admin) {
+ loadAppriseSettings();
+ loadPaperlessSettings(); // Also load Paperless-ngx settings for admin
+ } else {
+ console.log('User is not admin, skipping Apprise settings load in deferred initialization');
+ }
+ }
+ }, 1000);
+});
+
+// ============================================================================
+// Paperless-ngx Integration Functions
+// ============================================================================
+
+/**
+ * Toggle the visibility of Paperless-ngx settings based on enabled state
+ * @param {boolean} enabled - Whether Paperless-ngx is enabled
+ */
+function togglePaperlessSettings(enabled) {
+ if (paperlessSettingsContainer) {
+ paperlessSettingsContainer.style.display = enabled ? 'block' : 'none';
+ }
+}
+
+/**
+ * Load Paperless-ngx settings from the server
+ */
+async function loadPaperlessSettings() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to load settings');
+ }
+
+ const settings = await response.json();
+
+ // Update Paperless-ngx settings UI
+ if (paperlessEnabledToggle) {
+ const isEnabled = settings.paperless_enabled === 'true';
+ paperlessEnabledToggle.checked = isEnabled;
+ togglePaperlessSettings(isEnabled);
+ }
+
+ if (paperlessUrlInput && settings.paperless_url) {
+ paperlessUrlInput.value = settings.paperless_url;
+ }
+
+ // Update API token field placeholder to indicate if token is saved
+ if (paperlessApiTokenInput) {
+ if (settings.paperless_api_token_set === 'true') {
+ paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
+ } else {
+ paperlessApiTokenInput.placeholder = 'Enter API token';
+ }
+ }
+
+ console.log('✅ Paperless-ngx settings loaded successfully');
+
+ } catch (error) {
+ console.error('❌ Error loading Paperless-ngx settings:', error);
+ showToast(`Error loading Paperless-ngx settings: ${error.message}`, 'error');
+ }
+}
+
+/**
+ * Save Paperless-ngx settings to the server
+ */
+async function savePaperlessSettings() {
+ try {
+ showLoading();
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ // Validate URL format
+ const url = paperlessUrlInput.value.trim();
+ if (url && !isValidUrl(url)) {
+ showToast('Please enter a valid URL (e.g., https://paperless.yourdomain.com)', 'error');
+ return;
+ }
+
+ // Prepare settings data
+ const settingsData = {
+ paperless_enabled: paperlessEnabledToggle.checked.toString(),
+ paperless_url: url
+ };
+
+ // Only include API token if it's provided (not empty)
+ const apiToken = paperlessApiTokenInput.value.trim();
+ if (apiToken) {
+ settingsData.paperless_api_token = apiToken;
+ }
+
+ // Save admin settings first
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(settingsData)
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save Paperless-ngx settings');
+ }
+
+ // Also save the user preference for viewing documents in app
+ const paperlessViewInApp = paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false;
+ const preferencesData = {
+ paperless_view_in_app: paperlessViewInApp
+ };
+
+ const preferencesResponse = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferencesData)
+ });
+
+ if (!preferencesResponse.ok) {
+ console.warn('Failed to save paperless view preference, but admin settings were saved');
+ }
+
+ // Update localStorage for the preference
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}paperlessViewInApp`, paperlessViewInApp);
+
+ showToast('Paperless-ngx settings saved successfully!', 'success');
+
+ // Clear the API token input for security
+ if (paperlessApiTokenInput) {
+ paperlessApiTokenInput.value = '';
+ paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
+ }
+
+ console.log('✅ Paperless-ngx settings saved successfully');
+
+ } catch (error) {
+ console.error('❌ Error saving Paperless-ngx settings:', error);
+ showToast(`Error saving Paperless-ngx settings: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Test connection to Paperless-ngx instance
+ */
+async function testPaperlessConnection() {
+ try {
+ showLoading();
+
+ // Clear previous status
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.innerHTML = '';
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ }
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ // Get current values from the form
+ const url = paperlessUrlInput.value.trim();
+ const apiToken = paperlessApiTokenInput.value.trim();
+
+ if (!url) {
+ showToast('Please enter a Paperless-ngx URL first', 'warning');
+ return;
+ }
+
+ // Check if API token is provided in form, otherwise use stored settings
+ if (!apiToken && paperlessApiTokenInput.placeholder.includes('saved')) {
+ // API token is already saved, test with stored settings
+ const response = await fetch('/api/paperless/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const result = await response.json();
+
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ if (result.success) {
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ Connection Successful!</strong><br>
+ ${result.message}
+ ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
+ `;
+ showToast('Paperless-ngx connection test successful!', 'success');
+ } else {
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Failed!</strong><br>
+ ${result.message}
+ `;
+ showToast('Paperless-ngx connection test failed', 'error');
+ }
+ }
+
+ return;
+ }
+
+ if (!apiToken) {
+ showToast('Please enter an API token to test the connection', 'warning');
+ return;
+ }
+
+ const response = await fetch('/api/paperless/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ url: url,
+ api_token: apiToken
+ })
+ });
+
+ const result = await response.json();
+
+ if (paperlessConnectionStatus) {
+ if (result.success) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ Connection Successful!</strong><br>
+ ${result.message}
+ ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
+ `;
+ showToast('Paperless-ngx connection test successful!', 'success');
+ } else {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Failed!</strong><br>
+ ${result.message}
+ `;
+ showToast('Paperless-ngx connection test failed', 'error');
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error testing Paperless-ngx connection:', error);
+
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Error!</strong><br>
+ ${error.message}
+ `;
+ }
+
+ showToast(`Error testing connection: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Debug Paperless-ngx configuration
+ */
+async function debugPaperlessConfiguration() {
+ try {
+ showLoading();
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/paperless/debug', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const result = await response.json();
+
+ // Display debug information
+ console.log('🔍 Paperless-ngx Debug Information:', result);
+
+ let debugHtml = '<h5>📋 Paperless-ngx Debug Information</h5>';
+ debugHtml += `<strong>Enabled:</strong> ${result.paperless_enabled}<br>`;
+ debugHtml += `<strong>URL:</strong> ${result.paperless_url || 'Not set'}<br>`;
+ debugHtml += `<strong>API Token Set:</strong> ${result.paperless_api_token_set}<br>`;
+ debugHtml += `<strong>Handler Available:</strong> ${result.paperless_handler_available}<br>`;
+
+ if (result.test_connection_result) {
+ debugHtml += `<strong>Connection Test:</strong> ${result.test_connection_result.success ? '✅ Success' : '❌ Failed'}<br>`;
+ debugHtml += `<strong>Message:</strong> ${result.test_connection_result.message || result.test_connection_result.error}<br>`;
+ }
+
+ if (result.paperless_handler_error) {
+ debugHtml += `<strong>Handler Error:</strong> ${result.paperless_handler_error}<br>`;
+ }
+
+ // Show in connection status area or create a temporary area
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show info';
+ paperlessConnectionStatus.innerHTML = debugHtml;
+ } else {
+ // Create temporary debug display
+ const debugArea = document.createElement('div');
+ debugArea.innerHTML = debugHtml;
+ document.body.appendChild(debugArea);
+ setTimeout(() => debugArea.remove(), 10000); // Remove after 10 seconds
+ }
+
+ showToast('Debug information logged to console', 'info');
+
+ } catch (error) {
+ console.error('❌ Error running Paperless debug:', error);
+ showToast(`Debug error: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Test basic file upload mechanism
+ */
+async function testFileUpload() {
+ try {
+ showLoading();
+
+ // Create a simple test file
+ const testContent = 'This is a test file for Paperless-ngx upload debugging';
+ const testFile = new File([testContent], 'test.txt', { type: 'text/plain' });
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const formData = new FormData();
+ formData.append('file', testFile);
+ formData.append('document_type', 'test');
+
+ const response = await fetch('/api/paperless/test-upload', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ },
+ body: formData
+ });
+
+ const result = await response.json();
+
+ console.log('🧪 File Upload Test Result:', result);
+
+ if (result.success) {
+ showToast('File upload test successful!', 'success');
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ File Upload Test Successful!</strong><br>
+ ${result.message}<br>
+ <small>File: ${result.file_info.filename} (${result.file_info.size} bytes)</small>
+ `;
+ }
+ } else {
+ showToast('File upload test failed', 'error');
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ File Upload Test Failed!</strong><br>
+ ${result.error}
+ `;
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error testing file upload:', error);
+ showToast(window.t('messages.file_upload_test_error', { error: error.message }), 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Validate if a string is a valid URL
+ * @param {string} string - The string to validate
+ * @returns {boolean} - Whether the string is a valid URL
+ */
+function isValidUrl(string) {
+ try {
+ const url = new URL(string);
+ return url.protocol === 'http:' || url.protocol === 'https:';
+ } catch (_) {
+ return false;
+ }
+}
diff --git a/frontend/status.html b/frontend/src/status.html
similarity index 96%
rename from frontend/status.html
rename to frontend/src/status.html
index e909f48..1c0863e 100644
--- a/frontend/status.html
+++ b/frontend/src/status.html
@@ -2,43 +2,46 @@
<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
+ <script src="/auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js?v=20250119001"></script>
+
<!-- File utilities script for secure file handling -->
- <script src="file-utils.js?v=20250119001"></script>
+ <script src="/file-utils.js?v=20250119001"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="status.title">Status - Warracker</title>
<!-- Favicons -->
- <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
- <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
- <link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css?v=20250119004">
- <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
+ <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon-16x16.png?v=2">
+ <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon-512x512.png">
+ <link rel="manifest" href="/manifest.json">
+ <link rel="stylesheet" href="/style.css?v=20250119004">
+ <script src="/theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script type="module" src="/js/store.js"></script>
+ <script type="module" src="/js/services/authService.js"></script>
+ <script type="module" src="/js/services/apiService.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <link rel="stylesheet" href="/header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250119002">
+ <link rel="stylesheet" href="/mobile-header.css?v=20250119002">
<!-- Chart.js for visualizations -->
- <script src="chart.js?v=20250119001"></script>
+ <script src="/chart.js?v=20250119001"></script>
<!-- i18next Local Scripts -->
- <script src="js/lib/i18next.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
- <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="/js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
<!-- i18n initialization script -->
- <script src="js/i18n.js?v=20250119001"></script>
+ <script src="/js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
- <script src="script.js?v=20250119002" defer></script> <!-- Added script.js -->
- <script src="status.js?v=20250119001" defer></script> <!-- Status page specific functionality -->
+
+ <script src="/script.js?v=20250119002" defer></script> <!-- Added script.js -->
+ <script type="module" src="/status.js?v=20250119001"></script> <!-- Status page specific functionality -->
<style>
.user-menu {
position: relative;
@@ -822,14 +825,14 @@
<div class="loading-spinner"></div>
</div>
- <script src="auth.js?v=20250119001"></script>
- <script src="status.js?v=20250119001" defer></script>
+
+ <script type="module" src="/status.js?v=20250119001"></script>
<!-- Footer Width Fix -->
- <script src="footer-fix.js?v=20251024001"></script>
+ <script src="/footer-fix.js?v=20251024001"></script>
<!-- Footer Content Manager -->
- <script src="footer-content.js?v=20250119001"></script>
+ <script src="/footer-content.js?v=20250119001"></script>
<!-- Powered by Warracker Footer -->
<footer class="warracker-footer" id="warrackerFooter">
diff --git a/frontend/status.js b/frontend/src/status.js
similarity index 100%
rename from frontend/status.js
rename to frontend/src/status.js
diff --git a/frontend/style.css b/frontend/src/style.css
similarity index 100%
rename from frontend/style.css
rename to frontend/src/style.css
diff --git a/frontend/styles.css b/frontend/src/styles.css
similarity index 100%
rename from frontend/styles.css
rename to frontend/src/styles.css
diff --git a/frontend/src/sw.js b/frontend/src/sw.js
new file mode 100644
index 0000000..97b932f
--- /dev/null
+++ b/frontend/src/sw.js
@@ -0,0 +1,114 @@
+const CACHE_NAME = 'warracker-cache-v20251030001';
+const urlsToCache = [
+ // HTML pages
+ './',
+ './index.html',
+ './status.html',
+ './settings-new.html',
+ './about.html',
+ './login.html',
+ './register.html',
+ './reset-password.html',
+ './reset-password-request.html',
+ './auth-redirect.html',
+ './debug-export.html',
+
+ // Stylesheets (versioned)
+ './style.css?v=20250119004',
+ './styles.css?v=20250119001',
+ './settings-styles.css?v=20250119001',
+ './header-fix.css?v=20250119001',
+ './mobile-header.css?v=20250119002',
+
+ // JavaScript (versioned)
+ './script.js?v=20250119002',
+ './auth.js?v=20250119001',
+ './settings-new.js?v=20250119001',
+ './status.js?v=20250119001',
+ './theme-loader.js?v=20250119001',
+ './footer-fix.js?v=20251024001',
+ './footer-content.js?v=20250119001',
+ './include-auth-new.js?v=20250119001',
+ './file-utils.js?v=20250119001',
+ './fix-auth-buttons-loader.js?v=20250119001',
+ './auth-redirect.js?v=20250119001',
+ './mobile-menu.js?v=20250119002',
+ './version-checker.js?v=20250119001',
+
+ // i18n libraries and config (versioned)
+ './js/i18n.js?v=20250119001',
+ './js/lib/i18next.min.js?v=20250119001',
+ './js/lib/i18nextHttpBackend.min.js?v=20250119001',
+ './js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001',
+
+ // Charts
+ './chart.js?v=20250119001',
+
+ // App manifest and icons
+ './manifest.json',
+ './favicon.ico',
+ './img/favicon-16x16.png?v=2',
+ './img/favicon-32x32.png?v=2',
+ './img/favicon-512x512.png'
+];
+
+self.addEventListener('install', event => {
+ event.waitUntil(
+ caches.open(CACHE_NAME)
+ .then(cache => {
+ console.log('Opened cache');
+ return cache.addAll(urlsToCache);
+ })
+ );
+ // Activate the new service worker immediately after installation
+ self.skipWaiting();
+});
+
+self.addEventListener('fetch', event => {
+ if (event.request.method !== 'GET') {
+ return;
+ }
+
+ const requestUrl = new URL(event.request.url);
+
+ event.respondWith(
+ caches.match(event.request).then(cachedResponse => {
+ const fetchPromise = fetch(event.request)
+ .then(networkResponse => {
+ const isSameOrigin = requestUrl.origin === self.location.origin;
+ const okToCache = isSameOrigin && networkResponse && networkResponse.status === 200 &&
+ ['document', 'script', 'style', 'image', 'font'].includes(event.request.destination);
+
+ if (okToCache) {
+ const responseToCache = networkResponse.clone();
+ caches.open(CACHE_NAME).then(cache => cache.put(event.request, responseToCache));
+ }
+ return networkResponse;
+ })
+ .catch(() => {
+ if (cachedResponse) return cachedResponse;
+ if (event.request.mode === 'navigate') {
+ return caches.match('./index.html');
+ }
+ return Promise.reject(new Error('Network error and no cache.'));
+ });
+
+ return cachedResponse || fetchPromise;
+ })
+ );
+});
+
+self.addEventListener('activate', event => {
+ const cacheWhitelist = [CACHE_NAME];
+ event.waitUntil(
+ caches.keys().then(cacheNames => {
+ return Promise.all(
+ cacheNames.map(cacheName => {
+ if (cacheWhitelist.indexOf(cacheName) === -1) {
+ return caches.delete(cacheName);
+ }
+ })
+ );
+ }).then(() => self.clients.claim())
+ );
+});
\ No newline at end of file
diff --git a/frontend/temp-toast-debug.js b/frontend/src/temp-toast-debug.js
similarity index 100%
rename from frontend/temp-toast-debug.js
rename to frontend/src/temp-toast-debug.js
diff --git a/frontend/src/theme-loader.js b/frontend/src/theme-loader.js
new file mode 100644
index 0000000..8f6d8dc
--- /dev/null
+++ b/frontend/src/theme-loader.js
@@ -0,0 +1,48 @@
+// theme-loader.js
+(function() {
+ try {
+ // Function to apply the theme directly to the root element
+ function applyTheme(isDark) {
+ const theme = isDark ? 'dark' : 'light';
+ document.documentElement.setAttribute('data-theme', theme);
+ // No need for console log in production loader script
+ // console.log(`Theme applied on load: ${theme}`);
+ }
+
+ function getCookie(name) {
+ const value = `; ${document.cookie}`;
+ const parts = value.split(`; ${name}=`);
+ if (parts.length === 2) return parts.pop().split(';').shift();
+ return null;
+ }
+
+ // Default to light theme initially
+ let isDarkMode = false;
+
+ // Priority: cookie 'theme' -> localStorage 'darkMode' -> system preference
+ const themeCookie = getCookie('theme');
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (themeCookie === 'dark' || themeCookie === 'light') {
+ isDarkMode = themeCookie === 'dark';
+ } else if (savedTheme !== null) {
+ // Use the saved theme preference
+ isDarkMode = savedTheme === 'true';
+ } else {
+ // Fallback to system preference if no theme saved in localStorage
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ // console.log(`No saved theme found, falling back to system preference: ${prefersDarkMode ? 'dark' : 'light'}`);
+ isDarkMode = prefersDarkMode;
+ // Optionally, save the detected system preference as the initial setting for future loads
+ // localStorage.setItem('darkMode', isDarkMode); // Consider if this is desired behavior
+ }
+
+ // Apply the determined theme
+ applyTheme(isDarkMode);
+
+ } catch (e) {
+ console.error("Error applying theme from theme-loader.js:", e);
+ // Fallback to light theme in case of error
+ document.documentElement.setAttribute('data-theme', 'light');
+ }
+})();
diff --git a/frontend/src/version-checker.js b/frontend/src/version-checker.js
new file mode 100644
index 0000000..b1e5b78
--- /dev/null
+++ b/frontend/src/version-checker.js
@@ -0,0 +1,82 @@
+// Version checker for Warracker
+document.addEventListener('DOMContentLoaded', () => {
+ const currentVersion = '1.0.3'; // Current version of the application
+ const updateStatus = document.getElementById('updateStatus');
+ const updateLink = document.getElementById('updateLink');
+ const versionDisplay = document.getElementById('versionDisplay');
+
+ // Function to compare versions
+ function compareVersions(v1, v2) {
+ const v1Parts = v1.split('.').map(Number);
+ const v2Parts = v2.split('.').map(Number);
+
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
+ const v1Part = v1Parts[i] || 0;
+ const v2Part = v2Parts[i] || 0;
+
+ if (v1Part > v2Part) return 1;
+ if (v1Part < v2Part) return -1;
+ }
+ return 0;
+ }
+
+ // Function to check for updates
+ async function checkForUpdates() {
+ try {
+ const response = await fetch('https://api.github.com/repos/sassanix/Warracker/releases/latest');
+ if (!response.ok) throw new Error('Failed to fetch release information');
+
+ const data = await response.json();
+ const latestVersion = data.tag_name.replace('v', ''); // Remove 'v' prefix if present
+
+ const comparison = compareVersions(latestVersion, currentVersion);
+
+ if (comparison > 0) {
+ // New version available
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.new_version_available', { version: data.tag_name });
+ } else {
+ updateStatus.textContent = `New version ${data.tag_name} available!`;
+ }
+ updateStatus.style.color = 'var(--success-color)';
+ updateLink.href = data.html_url;
+ updateLink.style.display = 'inline-block';
+ } else {
+ // Up to date
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.latest_version');
+ } else {
+ updateStatus.textContent = 'You are using the latest version';
+ }
+ updateStatus.style.color = 'var(--success-color)';
+ }
+ } catch (error) {
+ console.error('Error checking for updates:', error);
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.update_check_failed');
+ } else {
+ updateStatus.textContent = 'Failed to check for updates';
+ }
+ updateStatus.style.color = 'var(--error-color)';
+ }
+ }
+
+ // Update version display if element exists
+ if (versionDisplay) {
+ // Wait for i18next to be ready
+ const updateVersionDisplay = () => {
+ if (window.i18next && window.i18next.t) {
+ versionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;
+ } else {
+ versionDisplay.textContent = 'Version v' + currentVersion;
+ }
+ };
+
+ // Try immediately and also after a delay for i18next
+ updateVersionDisplay();
+ setTimeout(updateVersionDisplay, 500);
+ }
+
+ // Check for updates when the page loads
+ checkForUpdates();
+});
\ No newline at end of file
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
new file mode 100644
index 0000000..539dc78
--- /dev/null
+++ b/frontend/vite.config.js
@@ -0,0 +1,35 @@
+import { defineConfig } from 'vite';
+import { resolve } from 'node:path';
+
+export default defineConfig({
+ root: 'src',
+ publicDir: resolve(__dirname, 'public'),
+ build: {
+ outDir: '../dist',
+ rollupOptions: {
+ input: {
+ index: resolve(__dirname, 'src/index.html'),
+ login: resolve(__dirname, 'src/login.html'),
+ register: resolve(__dirname, 'src/register.html'),
+ status: resolve(__dirname, 'src/status.html'),
+ settings: resolve(__dirname, 'src/settings-new.html'),
+ resetPassword: resolve(__dirname, 'src/reset-password.html'),
+ resetPasswordRequest: resolve(__dirname, 'src/reset-password-request.html'),
+ authRedirect: resolve(__dirname, 'src/auth-redirect.html'),
+ about: resolve(__dirname, 'src/about.html'),
+ debugExport: resolve(__dirname, 'src/debug-export.html'),
+ },
+ },
+ },
+ server: {
+ proxy: {
+ '/api': {
+ target: 'http://localhost:5000',
+ changeOrigin: true,
+ secure: false,
+ },
+ },
+ },
+});
+
+